Coverage Report

Created: 2026-08-24 12:17

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 <unordered_set>
46
#include <utility>
47
#include <variant>
48
49
#include "common/defer.h"
50
#include "common/stopwatch.h"
51
#include "meta-service/meta_service.h"
52
#include "meta-service/meta_service_helper.h"
53
#include "meta-service/meta_service_schema.h"
54
#include "meta-store/blob_message.h"
55
#include "meta-store/meta_reader.h"
56
#include "meta-store/txn_kv.h"
57
#include "meta-store/txn_kv_error.h"
58
#include "meta-store/versioned_value.h"
59
#include "recycler/checker.h"
60
#ifdef ENABLE_HDFS_STORAGE_VAULT
61
#include "recycler/hdfs_accessor.h"
62
#endif
63
#include "recycler/s3_accessor.h"
64
#include "recycler/storage_vault_accessor.h"
65
#ifdef UNIT_TEST
66
#include "../test/mock_accessor.h"
67
#endif
68
#include "common/bvars.h"
69
#include "common/config.h"
70
#include "common/encryption_util.h"
71
#include "common/logging.h"
72
#include "common/rowset_segment_id.h"
73
#include "common/simple_thread_pool.h"
74
#include "common/util.h"
75
#include "cpp/sync_point.h"
76
#include "meta-store/codec.h"
77
#include "meta-store/document_message.h"
78
#include "meta-store/keys.h"
79
#include "recycler/recycler_service.h"
80
#include "recycler/sync_executor.h"
81
#include "recycler/util.h"
82
#include "snapshot/snapshot_manager_factory.h"
83
84
namespace doris::cloud {
85
86
using namespace std::chrono;
87
88
namespace {
89
90
constexpr size_t kRowsetBatchGetSize = 256;
91
92
0
int64_t packed_file_retry_sleep_ms() {
93
0
    const int64_t min_ms = std::max<int64_t>(0, config::packed_file_txn_retry_sleep_min_ms);
94
0
    const int64_t max_ms = std::max<int64_t>(min_ms, config::packed_file_txn_retry_sleep_max_ms);
95
0
    thread_local std::mt19937_64 gen(std::random_device {}());
96
0
    std::uniform_int_distribution<int64_t> dist(min_ms, max_ms);
97
0
    return dist(gen);
98
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
99
100
0
void sleep_for_packed_file_retry() {
101
0
    std::this_thread::sleep_for(std::chrono::milliseconds(packed_file_retry_sleep_ms()));
102
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
103
104
868k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
105
868k
    const auto& locations = rowset.packed_slice_locations();
106
868k
    auto it = locations.find(path);
107
868k
    return it != locations.end() && it->second.has_packed_file_path() &&
108
868k
           !it->second.packed_file_path().empty();
109
868k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
104
7
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
105
7
    const auto& locations = rowset.packed_slice_locations();
106
7
    auto it = locations.find(path);
107
7
    return it != locations.end() && it->second.has_packed_file_path() &&
108
7
           !it->second.packed_file_path().empty();
109
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
104
868k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
105
868k
    const auto& locations = rowset.packed_slice_locations();
106
868k
    auto it = locations.find(path);
107
868k
    return it != locations.end() && it->second.has_packed_file_path() &&
108
868k
           !it->second.packed_file_path().empty();
109
868k
}
110
111
void add_file_to_delete_if_not_packed(const doris::RowsetMetaCloudPB& rowset,
112
                                      const std::string& path,
113
868k
                                      std::vector<std::string>* file_paths) {
114
870k
    if (!is_packed_slice_path(rowset, path)) {
115
870k
        file_paths->push_back(path);
116
870k
    }
117
868k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
113
7
                                      std::vector<std::string>* file_paths) {
114
7
    if (!is_packed_slice_path(rowset, path)) {
115
7
        file_paths->push_back(path);
116
7
    }
117
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
113
868k
                                      std::vector<std::string>* file_paths) {
114
870k
    if (!is_packed_slice_path(rowset, path)) {
115
870k
        file_paths->push_back(path);
116
870k
    }
117
868k
}
118
119
37
bool filter_out_instance(const std::string& instance_id) {
120
37
    if (config::recycle_whitelist.empty()) {
121
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
122
35
               config::recycle_blacklist.end();
123
35
    }
124
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
125
2
           config::recycle_whitelist.end();
126
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
119
37
bool filter_out_instance(const std::string& instance_id) {
120
37
    if (config::recycle_whitelist.empty()) {
121
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
122
35
               config::recycle_blacklist.end();
123
35
    }
124
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
125
2
           config::recycle_whitelist.end();
126
37
}
127
128
} // namespace
129
130
// return 0 for success get a key, 1 for key not found, negative for error
131
0
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
132
0
    std::unique_ptr<Transaction> txn;
133
0
    TxnErrorCode err = txn_kv->create_txn(&txn);
134
0
    if (err != TxnErrorCode::TXN_OK) {
135
0
        return -1;
136
0
    }
137
0
    switch (txn->get(key, &val, true)) {
138
0
    case TxnErrorCode::TXN_OK:
139
0
        return 0;
140
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
141
0
        return 1;
142
0
    default:
143
0
        return -1;
144
0
    };
145
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
146
147
// 0 for success, negative for error
148
static int txn_get(TxnKv* txn_kv, std::string_view begin, std::string_view end,
149
396
                   std::unique_ptr<RangeGetIterator>& it) {
150
396
    std::unique_ptr<Transaction> txn;
151
396
    TxnErrorCode err = txn_kv->create_txn(&txn);
152
396
    if (err != TxnErrorCode::TXN_OK) {
153
0
        return -1;
154
0
    }
155
396
    switch (txn->get(begin, end, &it, true)) {
156
396
    case TxnErrorCode::TXN_OK:
157
396
        return 0;
158
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
159
0
        return 1;
160
0
    default:
161
0
        return -1;
162
396
    };
163
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
149
36
                   std::unique_ptr<RangeGetIterator>& it) {
150
36
    std::unique_ptr<Transaction> txn;
151
36
    TxnErrorCode err = txn_kv->create_txn(&txn);
152
36
    if (err != TxnErrorCode::TXN_OK) {
153
0
        return -1;
154
0
    }
155
36
    switch (txn->get(begin, end, &it, true)) {
156
36
    case TxnErrorCode::TXN_OK:
157
36
        return 0;
158
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
159
0
        return 1;
160
0
    default:
161
0
        return -1;
162
36
    };
163
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
149
360
                   std::unique_ptr<RangeGetIterator>& it) {
150
360
    std::unique_ptr<Transaction> txn;
151
360
    TxnErrorCode err = txn_kv->create_txn(&txn);
152
360
    if (err != TxnErrorCode::TXN_OK) {
153
0
        return -1;
154
0
    }
155
360
    switch (txn->get(begin, end, &it, true)) {
156
360
    case TxnErrorCode::TXN_OK:
157
360
        return 0;
158
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
159
0
        return 1;
160
0
    default:
161
0
        return -1;
162
360
    };
163
0
}
164
165
// return 0 for success otherwise error
166
10
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
167
10
    std::unique_ptr<Transaction> txn;
168
10
    TxnErrorCode err = txn_kv->create_txn(&txn);
169
10
    if (err != TxnErrorCode::TXN_OK) {
170
0
        return -1;
171
0
    }
172
18
    for (auto k : keys) {
173
18
        txn->remove(k);
174
18
    }
175
10
    switch (txn->commit()) {
176
10
    case TxnErrorCode::TXN_OK:
177
10
        return 0;
178
0
    case TxnErrorCode::TXN_CONFLICT:
179
0
        return -1;
180
0
    default:
181
0
        return -1;
182
10
    }
183
10
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
166
3
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
167
3
    std::unique_ptr<Transaction> txn;
168
3
    TxnErrorCode err = txn_kv->create_txn(&txn);
169
3
    if (err != TxnErrorCode::TXN_OK) {
170
0
        return -1;
171
0
    }
172
3
    for (auto k : keys) {
173
3
        txn->remove(k);
174
3
    }
175
3
    switch (txn->commit()) {
176
3
    case TxnErrorCode::TXN_OK:
177
3
        return 0;
178
0
    case TxnErrorCode::TXN_CONFLICT:
179
0
        return -1;
180
0
    default:
181
0
        return -1;
182
3
    }
183
3
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
166
7
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
167
7
    std::unique_ptr<Transaction> txn;
168
7
    TxnErrorCode err = txn_kv->create_txn(&txn);
169
7
    if (err != TxnErrorCode::TXN_OK) {
170
0
        return -1;
171
0
    }
172
15
    for (auto k : keys) {
173
15
        txn->remove(k);
174
15
    }
175
7
    switch (txn->commit()) {
176
7
    case TxnErrorCode::TXN_OK:
177
7
        return 0;
178
0
    case TxnErrorCode::TXN_CONFLICT:
179
0
        return -1;
180
0
    default:
181
0
        return -1;
182
7
    }
183
7
}
184
185
// return 0 for success otherwise error
186
360
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
187
360
    std::unique_ptr<Transaction> txn;
188
360
    TxnErrorCode err = txn_kv->create_txn(&txn);
189
360
    if (err != TxnErrorCode::TXN_OK) {
190
0
        return -1;
191
0
    }
192
106k
    for (auto& k : keys) {
193
106k
        txn->remove(k);
194
106k
    }
195
360
    switch (txn->commit()) {
196
360
    case TxnErrorCode::TXN_OK:
197
360
        return 0;
198
0
    case TxnErrorCode::TXN_CONFLICT:
199
0
        return -1;
200
0
    default:
201
0
        return -1;
202
360
    }
203
360
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
186
33
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
187
33
    std::unique_ptr<Transaction> txn;
188
33
    TxnErrorCode err = txn_kv->create_txn(&txn);
189
33
    if (err != TxnErrorCode::TXN_OK) {
190
0
        return -1;
191
0
    }
192
33
    for (auto& k : keys) {
193
17
        txn->remove(k);
194
17
    }
195
33
    switch (txn->commit()) {
196
33
    case TxnErrorCode::TXN_OK:
197
33
        return 0;
198
0
    case TxnErrorCode::TXN_CONFLICT:
199
0
        return -1;
200
0
    default:
201
0
        return -1;
202
33
    }
203
33
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
186
327
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
187
327
    std::unique_ptr<Transaction> txn;
188
327
    TxnErrorCode err = txn_kv->create_txn(&txn);
189
327
    if (err != TxnErrorCode::TXN_OK) {
190
0
        return -1;
191
0
    }
192
106k
    for (auto& k : keys) {
193
106k
        txn->remove(k);
194
106k
    }
195
327
    switch (txn->commit()) {
196
327
    case TxnErrorCode::TXN_OK:
197
327
        return 0;
198
0
    case TxnErrorCode::TXN_CONFLICT:
199
0
        return -1;
200
0
    default:
201
0
        return -1;
202
327
    }
203
327
}
204
205
// return 0 for success otherwise error
206
[[maybe_unused]] static int txn_remove(TxnKv* txn_kv, std::string_view begin,
207
106k
                                       std::string_view end) {
208
106k
    std::unique_ptr<Transaction> txn;
209
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
210
106k
    if (err != TxnErrorCode::TXN_OK) {
211
0
        return -1;
212
0
    }
213
106k
    txn->remove(begin, end);
214
106k
    switch (txn->commit()) {
215
106k
    case TxnErrorCode::TXN_OK:
216
106k
        return 0;
217
0
    case TxnErrorCode::TXN_CONFLICT:
218
0
        return -1;
219
0
    default:
220
0
        return -1;
221
106k
    }
222
106k
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
207
17
                                       std::string_view end) {
208
17
    std::unique_ptr<Transaction> txn;
209
17
    TxnErrorCode err = txn_kv->create_txn(&txn);
210
17
    if (err != TxnErrorCode::TXN_OK) {
211
0
        return -1;
212
0
    }
213
17
    txn->remove(begin, end);
214
17
    switch (txn->commit()) {
215
17
    case TxnErrorCode::TXN_OK:
216
17
        return 0;
217
0
    case TxnErrorCode::TXN_CONFLICT:
218
0
        return -1;
219
0
    default:
220
0
        return -1;
221
17
    }
222
17
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
207
106k
                                       std::string_view end) {
208
106k
    std::unique_ptr<Transaction> txn;
209
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
210
106k
    if (err != TxnErrorCode::TXN_OK) {
211
0
        return -1;
212
0
    }
213
106k
    txn->remove(begin, end);
214
106k
    switch (txn->commit()) {
215
106k
    case TxnErrorCode::TXN_OK:
216
106k
        return 0;
217
0
    case TxnErrorCode::TXN_CONFLICT:
218
0
        return -1;
219
0
    default:
220
0
        return -1;
221
106k
    }
222
106k
}
223
224
void scan_restore_job_rowset(
225
        Transaction* txn, const std::string& instance_id, int64_t tablet_id, MetaServiceCode& code,
226
        std::string& msg,
227
        std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>* restore_job_rs_metas);
228
229
static inline void check_recycle_task(const std::string& instance_id, const std::string& task_name,
230
                                      int64_t num_scanned, int64_t num_recycled,
231
55
                                      int64_t start_time) {
232
55
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
233
0
        int64_t cost =
234
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
235
0
        if (cost > config::recycle_task_threshold_seconds) {
236
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
237
0
                    .tag("instance_id", instance_id)
238
0
                    .tag("task", task_name)
239
0
                    .tag("num_scanned", num_scanned)
240
0
                    .tag("num_recycled", num_recycled);
241
0
        }
242
0
    }
243
55
    return;
244
55
}
recycler.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
231
4
                                      int64_t start_time) {
232
4
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
233
0
        int64_t cost =
234
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
235
0
        if (cost > config::recycle_task_threshold_seconds) {
236
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
237
0
                    .tag("instance_id", instance_id)
238
0
                    .tag("task", task_name)
239
0
                    .tag("num_scanned", num_scanned)
240
0
                    .tag("num_recycled", num_recycled);
241
0
        }
242
0
    }
243
4
    return;
244
4
}
recycler_test.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
231
51
                                      int64_t start_time) {
232
51
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
233
0
        int64_t cost =
234
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
235
0
        if (cost > config::recycle_task_threshold_seconds) {
236
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
237
0
                    .tag("instance_id", instance_id)
238
0
                    .tag("task", task_name)
239
0
                    .tag("num_scanned", num_scanned)
240
0
                    .tag("num_recycled", num_recycled);
241
0
        }
242
0
    }
243
51
    return;
244
51
}
245
246
6
Recycler::Recycler(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
247
6
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
248
249
6
    auto s3_producer_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
250
6
                                                               "s3_producer_pool");
251
6
    s3_producer_pool->start();
252
6
    auto recycle_tablet_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
253
6
                                                                  "recycle_tablet_pool");
254
6
    recycle_tablet_pool->start();
255
6
    auto group_recycle_function_pool = std::make_shared<SimpleThreadPool>(
256
6
            config::recycle_pool_parallelism, "group_recycle_function_pool");
257
6
    group_recycle_function_pool->start();
258
6
    _thread_pool_group =
259
6
            RecyclerThreadPoolGroup(std::move(s3_producer_pool), std::move(recycle_tablet_pool),
260
6
                                    std::move(group_recycle_function_pool));
261
262
6
    auto resource_mgr = std::make_shared<ResourceManager>(txn_kv_);
263
6
    txn_lazy_committer_ = std::make_shared<TxnLazyCommitter>(txn_kv_, std::move(resource_mgr));
264
6
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
265
6
}
266
267
6
Recycler::~Recycler() {
268
6
    if (!stopped()) {
269
0
        stop();
270
0
    }
271
6
}
272
273
5
void Recycler::instance_scanner_callback() {
274
    // sleep 60 seconds before scheduling for the launch procedure to complete:
275
    // some bad hdfs connection may cause some log to stdout stderr
276
    // which may pollute .out file and affect the script to check success
277
5
    std::this_thread::sleep_for(
278
5
            std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
279
1.19k
    while (!stopped()) {
280
1.19k
        if (config::enable_recycler) {
281
4
            std::vector<InstanceInfoPB> instances;
282
4
            get_all_instances(txn_kv_.get(), instances);
283
            // TODO(plat1ko): delete job recycle kv of non-existent instances
284
4
            LOG(INFO) << "Recycler get instances: " << [&instances] {
285
4
                std::stringstream ss;
286
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
287
4
                return ss.str();
288
4
            }();
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
Line
Count
Source
284
4
            LOG(INFO) << "Recycler get instances: " << [&instances] {
285
4
                std::stringstream ss;
286
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
287
4
                return ss.str();
288
4
            }();
289
4
            if (!instances.empty()) {
290
                // enqueue instances
291
3
                std::lock_guard lock(mtx_);
292
30
                for (auto& instance : instances) {
293
30
                    if (filter_out_instance(instance.instance_id())) continue;
294
30
                    auto [_, success] = pending_instance_set_.insert(instance.instance_id());
295
                    // skip instance already in pending queue
296
30
                    if (success) {
297
30
                        pending_instance_queue_.push_back(std::move(instance));
298
30
                    }
299
30
                }
300
3
                pending_instance_cond_.notify_all();
301
3
            }
302
1.18k
        } else {
303
1.18k
            LOG(WARNING) << "Skip recycler since enable_recycler is false";
304
1.18k
        }
305
1.19k
        {
306
1.19k
            std::unique_lock lock(mtx_);
307
1.19k
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
308
2.38k
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
308
2.38k
                               [&]() { return stopped(); });
309
1.19k
        }
310
1.19k
    }
311
5
}
312
313
9
void Recycler::recycle_callback() {
314
40
    while (!stopped()) {
315
39
        InstanceInfoPB instance;
316
39
        {
317
39
            std::unique_lock lock(mtx_);
318
39
            pending_instance_cond_.wait(
319
53
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
319
53
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
320
39
            if (stopped()) {
321
8
                return;
322
8
            }
323
31
            instance = std::move(pending_instance_queue_.front());
324
31
            pending_instance_queue_.pop_front();
325
31
            pending_instance_set_.erase(instance.instance_id());
326
31
        }
327
0
        auto& instance_id = instance.instance_id();
328
31
        {
329
31
            std::lock_guard lock(mtx_);
330
            // skip instance in recycling
331
31
            if (recycling_instance_map_.count(instance_id)) continue;
332
31
        }
333
31
        if (!config::enable_recycler) {
334
1
            LOG(WARNING) << "Skip recycle instance_id=" << instance_id
335
1
                         << " since enable_recycler is false";
336
1
            continue;
337
1
        }
338
30
        auto instance_recycler = std::make_shared<InstanceRecycler>(
339
30
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
340
341
30
        if (int r = instance_recycler->init(); r != 0) {
342
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
343
0
                         << " ret=" << r;
344
0
            continue;
345
0
        }
346
30
        std::string recycle_job_key;
347
30
        job_recycle_key({instance_id}, &recycle_job_key);
348
30
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
349
30
                                               ip_port_, config::recycle_interval_seconds * 1000);
350
30
        if (ret != 0) { // Prepare failed
351
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
352
20
                         << " ret=" << ret;
353
20
            continue;
354
20
        } else {
355
10
            std::lock_guard lock(mtx_);
356
10
            recycling_instance_map_.emplace(instance_id, instance_recycler);
357
10
        }
358
10
        if (stopped()) return;
359
10
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
360
10
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
361
10
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
362
10
        g_bvar_recycler_instance_recycle_task_status.put({"submitted"}, 1);
363
10
        ret = instance_recycler->do_recycle();
364
        // If instance recycler has been aborted, don't finish this job
365
366
10
        if (!instance_recycler->stopped()) {
367
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
368
10
                                        ret == 0, ctime_ms);
369
10
        }
370
10
        if (instance_recycler->stopped() || ret != 0) {
371
0
            g_bvar_recycler_instance_recycle_task_status.put({"error"}, 1);
372
0
        }
373
10
        {
374
10
            std::lock_guard lock(mtx_);
375
10
            recycling_instance_map_.erase(instance_id);
376
10
        }
377
378
10
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
379
10
        auto elpased_ms = now - ctime_ms;
380
10
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
381
10
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
382
10
        g_bvar_recycler_instance_next_ts.put({instance_id},
383
10
                                             now + config::recycle_interval_seconds * 1000);
384
10
        g_bvar_recycler_instance_recycle_task_status.put({"completed"}, 1);
385
10
        LOG(INFO) << "recycle instance done, "
386
10
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
387
10
                  << " now: " << now;
388
389
10
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
390
391
10
        LOG_WARNING("finish recycle instance")
392
10
                .tag("instance_id", instance_id)
393
10
                .tag("cost_ms", elpased_ms);
394
10
    }
395
9
}
396
397
4
void Recycler::lease_recycle_jobs() {
398
54
    while (!stopped()) {
399
50
        std::vector<std::string> instances;
400
50
        instances.reserve(recycling_instance_map_.size());
401
50
        {
402
50
            std::lock_guard lock(mtx_);
403
50
            for (auto& [id, _] : recycling_instance_map_) {
404
30
                instances.push_back(id);
405
30
            }
406
50
        }
407
50
        for (auto& i : instances) {
408
30
            std::string recycle_job_key;
409
30
            job_recycle_key({i}, &recycle_job_key);
410
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
411
30
            if (ret == 1) {
412
0
                std::lock_guard lock(mtx_);
413
0
                if (auto it = recycling_instance_map_.find(i);
414
0
                    it != recycling_instance_map_.end()) {
415
0
                    it->second->stop();
416
0
                }
417
0
            }
418
30
        }
419
50
        {
420
50
            std::unique_lock lock(mtx_);
421
50
            notifier_.wait_for(lock,
422
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
423
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
423
100
                               [&]() { return stopped(); });
424
50
        }
425
50
    }
426
4
}
427
428
4
void Recycler::check_recycle_tasks() {
429
7
    while (!stopped()) {
430
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
431
3
        {
432
3
            std::lock_guard lock(mtx_);
433
3
            recycling_instance_map = recycling_instance_map_;
434
3
        }
435
3
        for (auto& entry : recycling_instance_map) {
436
0
            entry.second->check_recycle_tasks();
437
0
        }
438
439
3
        std::unique_lock lock(mtx_);
440
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
441
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
441
6
                           [&]() { return stopped(); });
442
3
    }
443
4
}
444
445
4
int Recycler::start(brpc::Server* server) {
446
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
447
4
    S3Environment::getInstance();
448
449
4
    if (config::enable_checker) {
450
0
        checker_ = std::make_unique<Checker>(txn_kv_);
451
0
        int ret = checker_->start();
452
0
        std::string msg;
453
0
        if (ret != 0) {
454
0
            msg = "failed to start checker";
455
0
            LOG(ERROR) << msg;
456
0
            std::cerr << msg << std::endl;
457
0
            return ret;
458
0
        }
459
0
        msg = "checker started";
460
0
        LOG(INFO) << msg;
461
0
        std::cout << msg << std::endl;
462
0
    }
463
464
4
    if (server) {
465
        // Add service
466
1
        auto recycler_service =
467
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
468
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
469
1
    }
470
471
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
471
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
472
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
473
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
473
8
        workers_.emplace_back([this] { recycle_callback(); });
474
8
    }
475
476
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
477
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
478
479
4
    if (config::enable_snapshot_data_migrator) {
480
0
        snapshot_data_migrator_ = std::make_shared<SnapshotDataMigrator>(txn_kv_);
481
0
        int ret = snapshot_data_migrator_->start();
482
0
        if (ret != 0) {
483
0
            LOG(ERROR) << "failed to start snapshot data migrator";
484
0
            return ret;
485
0
        }
486
0
        LOG(INFO) << "snapshot data migrator started";
487
0
    }
488
489
4
    if (config::enable_snapshot_chain_compactor) {
490
0
        snapshot_chain_compactor_ = std::make_shared<SnapshotChainCompactor>(txn_kv_);
491
0
        int ret = snapshot_chain_compactor_->start();
492
0
        if (ret != 0) {
493
0
            LOG(ERROR) << "failed to start snapshot chain compactor";
494
0
            return ret;
495
0
        }
496
0
        LOG(INFO) << "snapshot chain compactor started";
497
0
    }
498
499
4
    return 0;
500
4
}
501
502
4
void Recycler::stop() {
503
4
    stopped_ = true;
504
4
    notifier_.notify_all();
505
4
    pending_instance_cond_.notify_all();
506
4
    {
507
4
        std::lock_guard lock(mtx_);
508
4
        for (auto& [_, recycler] : recycling_instance_map_) {
509
0
            recycler->stop();
510
0
        }
511
4
    }
512
20
    for (auto& w : workers_) {
513
20
        if (w.joinable()) w.join();
514
20
    }
515
4
    if (checker_) {
516
0
        checker_->stop();
517
0
    }
518
4
    if (snapshot_data_migrator_) {
519
0
        snapshot_data_migrator_->stop();
520
0
    }
521
4
    if (snapshot_chain_compactor_) {
522
0
        snapshot_chain_compactor_->stop();
523
0
    }
524
4
}
525
526
class InstanceRecycler::InvertedIndexIdCache {
527
public:
528
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
529
175
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
530
531
    // Return 0 if success, 1 if schema kv not found, negative for error
532
    // For the same index_id, schema_version, res, since `get` is not completely atomic
533
    // one thread has not finished inserting, and another thread has not get the index_id and schema_version,
534
    // resulting in repeated addition and inaccuracy.
535
    // however, this approach can reduce the lock range and sacrifice a bit of meta repeated get to improve concurrency performance.
536
    // repeated addition does not affect correctness.
537
28.4k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
538
28.4k
        {
539
28.4k
            std::lock_guard lock(mtx_);
540
28.4k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
541
4.70k
                return 0;
542
4.70k
            }
543
23.7k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
544
23.7k
                it != inverted_index_id_map_.end()) {
545
18.1k
                res = it->second;
546
18.1k
                return 0;
547
18.1k
            }
548
23.7k
        }
549
        // Get schema from kv
550
        // TODO(plat1ko): Single flight
551
5.54k
        std::unique_ptr<Transaction> txn;
552
5.54k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
553
5.54k
        if (err != TxnErrorCode::TXN_OK) {
554
0
            LOG(WARNING) << "failed to create txn, err=" << err;
555
0
            return -1;
556
0
        }
557
5.54k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
558
5.54k
        ValueBuf val_buf;
559
5.54k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
560
5.54k
        if (err != TxnErrorCode::TXN_OK) {
561
500
            LOG(WARNING) << "failed to get schema, err=" << err;
562
500
            return static_cast<int>(err);
563
500
        }
564
5.04k
        doris::TabletSchemaCloudPB schema;
565
5.04k
        if (!parse_schema_value(val_buf, &schema)) {
566
0
            LOG(WARNING) << "malformed schema value, key=" << hex(schema_key);
567
0
            return -1;
568
0
        }
569
5.04k
        if (schema.index_size() > 0) {
570
4.01k
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
571
4.01k
            if (schema.has_inverted_index_storage_format()) {
572
4.00k
                index_format = schema.inverted_index_storage_format();
573
4.00k
            }
574
4.01k
            res.first = index_format;
575
4.01k
            res.second.reserve(schema.index_size());
576
10.0k
            for (auto& i : schema.index()) {
577
10.0k
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
578
10.0k
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
579
10.0k
                }
580
10.0k
            }
581
4.01k
        }
582
5.04k
        insert(index_id, schema_version, res);
583
5.04k
        return 0;
584
5.04k
    }
585
586
    // Empty `ids` means this schema has no inverted index
587
5.04k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
588
5.04k
        if (index_info.second.empty()) {
589
1.03k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
590
1.03k
            std::lock_guard lock(mtx_);
591
1.03k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
592
4.01k
        } else {
593
4.01k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
594
4.01k
            std::lock_guard lock(mtx_);
595
4.01k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
596
4.01k
        }
597
5.04k
    }
598
599
private:
600
    std::string instance_id_;
601
    std::shared_ptr<TxnKv> txn_kv_;
602
603
    std::mutex mtx_;
604
    using Key = std::pair<int64_t, int32_t>; // <index_id, schema_version>
605
    struct HashOfKey {
606
57.2k
        size_t operator()(const Key& key) const {
607
57.2k
            size_t seed = 0;
608
57.2k
            seed = std::hash<int64_t> {}(key.first);
609
57.2k
            seed = std::hash<int32_t> {}(key.second);
610
57.2k
            return seed;
611
57.2k
        }
612
    };
613
    // <index_id, schema_version> -> inverted_index_ids
614
    std::unordered_map<Key, InvertedIndexInfo, HashOfKey> inverted_index_id_map_;
615
    // Store <index_id, schema_version> of schema which doesn't have inverted index
616
    std::unordered_set<Key, HashOfKey> schemas_without_inverted_index_;
617
};
618
619
InstanceRecycler::InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
620
                                   RecyclerThreadPoolGroup thread_pool_group,
621
                                   std::shared_ptr<TxnLazyCommitter> txn_lazy_committer)
622
175
        : txn_kv_(std::move(txn_kv)),
623
175
          instance_id_(instance.instance_id()),
624
175
          instance_info_(instance),
625
175
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
626
175
          _thread_pool_group(std::move(thread_pool_group)),
627
175
          txn_lazy_committer_(std::move(txn_lazy_committer)),
628
175
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
629
175
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
630
175
    delete_bitmap_lock_white_list_->init();
631
175
    resource_mgr_->init();
632
633
175
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
634
635
    // Since the recycler's resource manager could not be notified when instance info changes,
636
    // we need to refresh the instance info here to ensure the resource manager has the latest info.
637
175
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
638
175
};
639
640
175
InstanceRecycler::~InstanceRecycler() = default;
641
642
149
int InstanceRecycler::init_obj_store_accessors() {
643
149
    for (const auto& obj_info : instance_info_.obj_info()) {
644
106
#ifdef UNIT_TEST
645
106
        auto accessor = std::make_shared<MockAccessor>();
646
#else
647
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
648
        if (!s3_conf) {
649
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
650
            return -1;
651
        }
652
653
        std::shared_ptr<S3Accessor> accessor;
654
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
655
        if (ret != 0) {
656
            LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
657
                         << " resource_id=" << obj_info.id();
658
            return ret;
659
        }
660
#endif
661
106
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
662
106
    }
663
664
149
    return 0;
665
149
}
666
667
149
int InstanceRecycler::init_storage_vault_accessors() {
668
149
    if (instance_info_.resource_ids().empty()) {
669
142
        return 0;
670
142
    }
671
672
7
    FullRangeGetOptions opts(txn_kv_);
673
7
    opts.prefetch = true;
674
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
675
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
676
677
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
678
18
        auto [k, v] = *kv;
679
18
        StorageVaultPB vault;
680
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
681
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
682
0
            return -1;
683
0
        }
684
18
        std::string recycler_storage_vault_white_list = accumulate(
685
18
                config::recycler_storage_vault_white_list.begin(),
686
18
                config::recycler_storage_vault_white_list.end(), std::string(),
687
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
687
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
688
18
        LOG_INFO("config::recycler_storage_vault_white_list")
689
18
                .tag("", recycler_storage_vault_white_list);
690
18
        if (!config::recycler_storage_vault_white_list.empty()) {
691
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
692
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
693
8
                it == config::recycler_storage_vault_white_list.end()) {
694
2
                LOG_WARNING(
695
2
                        "failed to init accessor for vault because this vault is not in "
696
2
                        "config::recycler_storage_vault_white_list. ")
697
2
                        .tag(" vault name:", vault.name())
698
2
                        .tag(" config::recycler_storage_vault_white_list:",
699
2
                             recycler_storage_vault_white_list);
700
2
                continue;
701
2
            }
702
8
        }
703
18
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
704
16
                                 &accessor_map_, &vault);
705
16
        if (vault.has_hdfs_info()) {
706
9
#ifdef ENABLE_HDFS_STORAGE_VAULT
707
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
708
9
            int ret = accessor->init();
709
9
            if (ret != 0) {
710
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
711
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
712
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
713
4
                continue;
714
4
            }
715
9
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
716
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
717
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
718
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
719
#else
720
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
721
                       << "but HDFS storage vaults were detected";
722
#endif
723
7
        } else if (vault.has_obj_info()) {
724
            // TODO: Propagate object storage session tokens to Recycler in a follow-up PR.
725
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
726
7
            if (!s3_conf) {
727
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
728
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
729
1
                continue;
730
1
            }
731
732
6
            std::shared_ptr<S3Accessor> accessor;
733
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
734
6
            if (ret != 0) {
735
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
736
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
737
0
                             << " ret=" << ret
738
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
739
0
                continue;
740
0
            }
741
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
742
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
743
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
744
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
745
6
        }
746
16
    }
747
748
7
    if (!it->is_valid()) {
749
0
        LOG_WARNING("failed to get storage vault kv");
750
0
        return -1;
751
0
    }
752
753
7
    if (accessor_map_.empty()) {
754
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
755
1
        return -2;
756
1
    }
757
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
758
6
             instance_id_);
759
760
6
    return 0;
761
7
}
762
763
150
int InstanceRecycler::init() {
764
150
    if (instance_info_.status() == InstanceInfoPB::DELETED &&
765
150
        (instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING ||
766
4
         instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED)) {
767
1
        return 0;
768
1
    }
769
770
149
    int ret = init_obj_store_accessors();
771
149
    if (ret != 0) {
772
0
        return ret;
773
0
    }
774
775
149
    return init_storage_vault_accessors();
776
149
}
777
778
template <typename... Func>
779
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
120
    return [funcs...]() {
781
120
        return [](std::initializer_list<int> ret_vals) {
782
120
            int i = 0;
783
140
            for (int ret : ret_vals) {
784
140
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
140
            }
788
120
            return i;
789
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
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
20
            for (int ret : ret_vals) {
784
20
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
20
            }
788
10
            return i;
789
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
20
            for (int ret : ret_vals) {
784
20
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
20
            }
788
10
            return i;
789
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
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
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
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
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
792
793
11
int InstanceRecycler::do_recycle() {
794
11
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
795
11
    tablet_metrics_context_.reset();
796
11
    segment_metrics_context_.reset();
797
11
    DORIS_CLOUD_DEFER {
798
11
        tablet_metrics_context_.finish_report();
799
11
        segment_metrics_context_.finish_report();
800
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
797
11
    DORIS_CLOUD_DEFER {
798
11
        tablet_metrics_context_.finish_report();
799
11
        segment_metrics_context_.finish_report();
800
11
    };
801
11
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
802
1
        int res = recycle_cluster_snapshots();
803
1
        if (res != 0) {
804
0
            return -1;
805
0
        }
806
1
        return recycle_deleted_instance();
807
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
808
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
809
10
                                        fmt::format("instance id {}", instance_id_),
810
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
810
120
                                        [](int r) { return r != 0; });
811
10
        sync_executor
812
10
                .add(task_wrapper(
813
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
813
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
814
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
814
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
815
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
816
                                   // becase they may both recycle the same set of tablets
817
                        // recycle dropped table or idexes(mv, rollup)
818
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
818
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
819
                        // recycle dropped partitions
820
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
820
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
821
10
                .add(task_wrapper(
822
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
822
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
823
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
823
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
824
10
                .add(task_wrapper(
825
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
825
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
826
10
                .add(task_wrapper(
827
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
827
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
828
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
828
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
829
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
829
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
830
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
830
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
831
10
                .add(task_wrapper(
832
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
832
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
833
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
833
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
834
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
834
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
835
10
        bool finished = true;
836
10
        std::vector<int> rets = sync_executor.when_all(&finished);
837
120
        for (int ret : rets) {
838
120
            if (ret != 0) {
839
0
                return ret;
840
0
            }
841
120
        }
842
10
        return finished ? 0 : -1;
843
10
    } else {
844
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
845
0
                     << " instance_id=" << instance_id_;
846
0
        return -1;
847
0
    }
848
11
}
849
850
/**
851
* 1. delete all remote data
852
* 2. delete all kv
853
* 3. remove instance kv depend on config::retain_deleted_instance_tombstone
854
*/
855
13
int InstanceRecycler::recycle_deleted_instance() {
856
13
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
857
858
13
    int ret = 0;
859
13
    auto start_time = steady_clock::now();
860
13
    const auto recycle_state = instance_info_.recycle_state();
861
862
13
    if (config::retain_deleted_instance_tombstone &&
863
13
        recycle_state == InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
864
4
        return 0;
865
4
    }
866
867
9
    DORIS_CLOUD_DEFER {
868
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
869
9
        if (ret != 0) {
870
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
871
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
872
0
                         << "s, instance_id=" << instance_id_;
873
9
        } else if (recycle_state ==
874
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
875
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
876
0
                      << "s, instance_id=" << instance_id_;
877
9
        } else {
878
9
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
879
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
880
9
                      << "s, instance_id=" << instance_id_;
881
9
        }
882
9
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
867
9
    DORIS_CLOUD_DEFER {
868
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
869
9
        if (ret != 0) {
870
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
871
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
872
0
                         << "s, instance_id=" << instance_id_;
873
9
        } else if (recycle_state ==
874
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
875
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
876
0
                      << "s, instance_id=" << instance_id_;
877
9
        } else {
878
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
879
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
880
9
                      << "s, instance_id=" << instance_id_;
881
9
        }
882
9
    };
883
884
9
    switch (recycle_state) {
885
6
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING:
886
6
        ret = recycle_deleted_instance_data();
887
6
        break;
888
3
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING:
889
3
        ret = recycle_deleted_instance_metadata();
890
3
        break;
891
0
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED:
892
0
        ret = remove_instance_key();
893
0
        break;
894
0
    default:
895
0
        LOG_WARNING("invalid instance recycle state")
896
0
                .tag("instance_id", instance_id_)
897
0
                .tag("recycle_state", instance_info_.recycle_state());
898
0
        ret = -1;
899
0
        break;
900
9
    }
901
902
9
    return ret;
903
9
}
904
905
6
int InstanceRecycler::recycle_deleted_instance_data() {
906
6
    int ret = 0;
907
908
    // Step 1: Recycle tmp rowsets (contains ref count but txn is not committed)
909
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
910
6
        int res = recycle_tmp_rowsets();
911
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
912
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
913
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
914
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
915
            // and cannot be recycled.
916
0
            res = recycle_tmp_rowsets();
917
0
        }
918
6
        return res;
919
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
Line
Count
Source
909
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
910
6
        int res = recycle_tmp_rowsets();
911
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
912
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
913
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
914
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
915
            // and cannot be recycled.
916
0
            res = recycle_tmp_rowsets();
917
0
        }
918
6
        return res;
919
6
    };
920
921
6
    if (recycle_tmp_rowsets_with_mark_delete_enabled() != 0) {
922
0
        LOG_WARNING("failed to recycle tmp rowsets").tag("instance_id", instance_id_);
923
0
        return -1;
924
0
    }
925
926
    // Step 2: Recycle versioned rowsets in recycle space (already marked for deletion)
927
6
    if (recycle_versioned_rowsets() != 0) {
928
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
929
0
        return -1;
930
0
    }
931
932
    // Step 3: Recycle operation logs (can recycle logs not referenced by snapshots)
933
6
    if (recycle_operation_logs() != 0) {
934
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
935
0
        return -1;
936
0
    }
937
938
    // Step 4: Check if there are still cluster snapshots
939
6
    bool has_snapshots = false;
940
6
    if (has_cluster_snapshots(&has_snapshots) != 0) {
941
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
942
0
        return -1;
943
6
    } else if (has_snapshots) {
944
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
945
1
        return 0;
946
1
    }
947
948
5
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
949
5
                            instance_info().snapshot_switch_status() !=
950
1
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
951
5
    if (snapshot_enabled) {
952
1
        bool has_unrecycled_rowsets = false;
953
1
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
954
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
955
0
            return -1;
956
1
        } else if (has_unrecycled_rowsets) {
957
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
958
0
                    .tag("instance_id", instance_id_);
959
0
            return ret;
960
0
        }
961
4
    } else { // delete all remote data if snapshot is disabled
962
4
        for (auto& [_, accessor] : accessor_map_) {
963
4
            if (stopped()) {
964
0
                return ret;
965
0
            }
966
967
4
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
968
4
            int del_ret = accessor->delete_all();
969
4
            if (del_ret == 0) {
970
4
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
971
4
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
972
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
973
                // so the recycling has been successful.
974
0
                ret = -1;
975
0
            }
976
4
        }
977
978
4
        if (ret != 0) {
979
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
980
0
            return ret;
981
0
        }
982
4
    }
983
984
5
    if (update_instance_recycle_state(
985
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING,
986
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) != 0) {
987
0
        return -1;
988
0
    }
989
990
5
    return 0;
991
5
}
992
993
7
int InstanceRecycler::recycle_deleted_instance_metadata() {
994
    // Check successor instance, if exists, skip deleting kv because successor instance may still need the data in kv
995
7
    if (instance_info_.has_successor_instance_id() &&
996
7
        !instance_info_.successor_instance_id().empty()) {
997
4
        std::string key = instance_key(instance_info_.successor_instance_id());
998
4
        std::unique_ptr<Transaction> txn;
999
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1000
4
        if (err != TxnErrorCode::TXN_OK) {
1001
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_
1002
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1003
0
                         << " err=" << err;
1004
0
            return -1;
1005
0
        }
1006
1007
4
        InstanceInfoPB successor_instance;
1008
4
        std::string value;
1009
4
        err = txn->get(key, &value);
1010
4
        if (err == TxnErrorCode::TXN_OK) {
1011
3
            InstanceInfoPB successor_instance;
1012
3
            if (!successor_instance.ParseFromString(value)) {
1013
0
                LOG(WARNING) << "failed to parse successor instance, instance_id=" << instance_id_
1014
0
                             << " successor_instance_id=" << instance_info_.successor_instance_id();
1015
0
                return -1;
1016
0
            }
1017
3
            if (!successor_instance.has_recycle_state() ||
1018
3
                successor_instance.recycle_state() !=
1019
2
                        InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1020
2
                LOG(INFO) << "instance successor has not completed recycling, skip deleting kv,"
1021
2
                          << " instance_id=" << instance_id_
1022
2
                          << " successor_instance_id=" << instance_info_.successor_instance_id()
1023
2
                          << " successor_status=" << successor_instance.status()
1024
2
                          << " successor_recycled_state=" << successor_instance.recycle_state();
1025
2
                return 0;
1026
2
            }
1027
3
        } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1028
0
            LOG(WARNING) << "failed to get successor instance, instance_id=" << instance_id_
1029
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1030
0
                         << " err=" << err;
1031
0
            return -1;
1032
0
        }
1033
4
    }
1034
1035
    // delete all kv
1036
5
    std::unique_ptr<Transaction> txn;
1037
5
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1038
5
    if (err != TxnErrorCode::TXN_OK) {
1039
0
        LOG(WARNING) << "failed to create txn";
1040
0
        return -1;
1041
0
    }
1042
5
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
1043
    // delete kv before deleting objects to prevent the checker from misjudging data loss
1044
5
    std::string start_txn_key = txn_key_prefix(instance_id_);
1045
5
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
1046
5
    txn->remove(start_txn_key, end_txn_key);
1047
5
    std::string start_version_key = version_key_prefix(instance_id_);
1048
5
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
1049
5
    txn->remove(start_version_key, end_version_key);
1050
5
    std::string start_meta_key = meta_key_prefix(instance_id_);
1051
5
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
1052
5
    txn->remove(start_meta_key, end_meta_key);
1053
5
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
1054
5
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
1055
5
    txn->remove(start_recycle_key, end_recycle_key);
1056
5
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
1057
5
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1058
5
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
1059
5
    std::string start_copy_key = copy_key_prefix(instance_id_);
1060
5
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
1061
5
    txn->remove(start_copy_key, end_copy_key);
1062
    // should not remove job key range, because we need to reserve job recycle kv
1063
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
1064
5
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
1065
5
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1066
5
    txn->remove(start_job_tablet_key, end_job_tablet_key);
1067
5
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
1068
5
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
1069
5
    std::string start_vault_key = storage_vault_key(key_info0);
1070
5
    std::string end_vault_key = storage_vault_key(key_info1);
1071
5
    txn->remove(start_vault_key, end_vault_key);
1072
5
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
1073
5
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
1074
5
    txn->remove(versioned_version_key_start, versioned_version_key_end);
1075
5
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
1076
5
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
1077
5
    txn->remove(versioned_index_key_start, versioned_index_key_end);
1078
5
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
1079
5
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
1080
5
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
1081
5
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
1082
5
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
1083
5
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
1084
5
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
1085
5
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
1086
5
    txn->remove(versioned_data_key_start, versioned_data_key_end);
1087
5
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
1088
5
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
1089
5
    txn->remove(versioned_log_key_start, versioned_log_key_end);
1090
1091
    // Updating the recycle state also commits this transaction, making the metadata deletions
1092
    // and state transition atomic.
1093
5
    if (update_instance_recycle_state(
1094
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING,
1095
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED, txn.get()) != 0) {
1096
0
        return -1;
1097
0
    }
1098
1099
5
    return 0;
1100
5
}
1101
1102
0
int InstanceRecycler::remove_instance_key() {
1103
0
    std::unique_ptr<Transaction> txn;
1104
0
    std::string key = instance_key(instance_info_.instance_id());
1105
0
    std::string value;
1106
0
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1107
0
    if (err != TxnErrorCode::TXN_OK) {
1108
0
        LOG(WARNING) << "failed to create txn";
1109
0
        return -1;
1110
0
    }
1111
1112
0
    err = txn->get(key, &value);
1113
0
    if (err != TxnErrorCode::TXN_OK) {
1114
0
        LOG(WARNING) << "failed to get instance, instance_id=" << instance_info_.instance_id()
1115
0
                     << ", err=" << err;
1116
0
        return -1;
1117
0
    }
1118
1119
0
    InstanceInfoPB instance;
1120
0
    if (!instance.ParseFromString(value)) {
1121
0
        LOG(WARNING) << "malformed instance info, key=" << key;
1122
0
        return -1;
1123
0
    }
1124
1125
0
    if (instance.status() != InstanceInfoPB::DELETED) {
1126
0
        LOG(WARNING) << "failed to remove instance key, instance is not deleted, instance_id="
1127
0
                     << instance_id_ << ", status=" << instance.status();
1128
0
        return -1;
1129
0
    }
1130
1131
0
    if (instance.recycle_state() != INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1132
0
        LOG(WARNING) << "failed to remove instance key, invalid recycle state, instance_id="
1133
0
                     << instance_id_
1134
0
                     << ", current_state=" << InstanceRecycleState_Name(instance.recycle_state())
1135
0
                     << ", expected_state="
1136
0
                     << InstanceRecycleState_Name(INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1137
0
        return -1;
1138
0
    }
1139
1140
0
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1141
0
    txn->remove(key);
1142
0
    err = txn->commit();
1143
0
    if (err != TxnErrorCode::TXN_OK) {
1144
0
        LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
1145
0
                     << " err=" << err;
1146
0
        return -1;
1147
0
    }
1148
0
    return 0;
1149
0
}
1150
1151
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState expected_state,
1152
7
                                                    InstanceRecycleState target_state) {
1153
7
    std::unique_ptr<Transaction> txn;
1154
7
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1155
7
    if (err != TxnErrorCode::TXN_OK) {
1156
0
        LOG(WARNING) << "failed to create txn";
1157
0
        return -1;
1158
0
    }
1159
7
    return update_instance_recycle_state(expected_state, target_state, txn.get());
1160
7
}
1161
1162
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState current_state,
1163
                                                    InstanceRecycleState target_state,
1164
12
                                                    Transaction* txn) {
1165
12
    const bool valid_transition =
1166
12
            (current_state == INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING &&
1167
12
             target_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) ||
1168
12
            (current_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING &&
1169
6
             target_state == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1170
1171
12
    if (!valid_transition) {
1172
1
        LOG_WARNING("invalid instance recycled state transition")
1173
1
                .tag("instance_id", instance_id_)
1174
1
                .tag("current_state", InstanceRecycleState_Name(current_state))
1175
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1176
1
        return -1;
1177
1
    }
1178
1179
11
    std::string key = instance_key({instance_id_});
1180
11
    std::string value;
1181
11
    TxnErrorCode err = txn->get(key, &value);
1182
11
    if (err != TxnErrorCode::TXN_OK) {
1183
0
        LOG_WARNING("failed to get instance when updating instance recycled state")
1184
0
                .tag("instance_id", instance_id_)
1185
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1186
0
                .tag("target_state", InstanceRecycleState_Name(target_state))
1187
0
                .tag("err", err);
1188
0
        return -1;
1189
0
    }
1190
1191
11
    InstanceInfoPB instance;
1192
11
    if (!instance.ParseFromString(value)) {
1193
0
        LOG_WARNING("failed to parse InstanceInfoPB when updating instance recycled state")
1194
0
                .tag("instance_id", instance_id_)
1195
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1196
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1197
0
        return -1;
1198
0
    }
1199
11
    if (instance.status() != InstanceInfoPB::DELETED) {
1200
0
        LOG_WARNING("instance is not deleted when updating instance recycled state")
1201
0
                .tag("instance_id", instance_id_)
1202
0
                .tag("status", instance.status())
1203
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1204
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1205
0
        return -1;
1206
0
    }
1207
11
    if (instance.recycle_state() != current_state) {
1208
1
        LOG_WARNING("instance recycled state changed before update")
1209
1
                .tag("instance_id", instance_id_)
1210
1
                .tag("current_state", InstanceRecycleState_Name(instance.recycle_state()))
1211
1
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1212
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1213
1
        return -1;
1214
1
    }
1215
1216
10
    instance.set_recycle_state(target_state);
1217
10
    instance.set_recycle_state_update_time_ms(
1218
10
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count());
1219
10
    if (!instance.SerializeToString(&value)) {
1220
0
        LOG_WARNING("failed to serialize InstanceInfoPB when updating instance recycled state")
1221
0
                .tag("instance_id", instance_id_)
1222
0
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1223
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1224
0
        return -1;
1225
0
    }
1226
1227
10
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1228
10
    txn->put(key, value);
1229
10
    err = txn->commit();
1230
10
    if (err != TxnErrorCode::TXN_OK) {
1231
0
        LOG(WARNING) << "failed to commit fdb txn when updating instance recycled state, "
1232
0
                     << "instance_id=" << instance_id_ << ", err=" << err;
1233
0
        return -1;
1234
0
    }
1235
1236
10
    instance_info_.Swap(&instance);
1237
10
    LOG_INFO("updated instance recycled state")
1238
10
            .tag("instance_id", instance_id_)
1239
10
            .tag("recycle_state", InstanceRecycleState_Name(target_state));
1240
10
    return 0;
1241
10
}
1242
1243
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
1244
9
                                          bool* exists, PackedFileRecycleStats* stats) {
1245
9
    if (exists == nullptr) {
1246
0
        return -1;
1247
0
    }
1248
9
    *exists = false;
1249
1250
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
1251
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1252
9
    std::string scan_begin = begin;
1253
1254
9
    while (true) {
1255
9
        std::unique_ptr<RangeGetIterator> it_range;
1256
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
1257
9
        if (get_ret < 0) {
1258
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1259
0
                    .tag("instance_id", instance_id_)
1260
0
                    .tag("tablet_id", tablet_id)
1261
0
                    .tag("ret", get_ret);
1262
0
            return -1;
1263
0
        }
1264
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1265
6
            return 0;
1266
6
        }
1267
1268
3
        std::string last_key;
1269
3
        while (it_range->has_next()) {
1270
3
            auto [k, v] = it_range->next();
1271
3
            last_key.assign(k.data(), k.size());
1272
3
            doris::RowsetMetaCloudPB rowset_meta;
1273
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1274
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1275
0
                        .tag("instance_id", instance_id_)
1276
0
                        .tag("tablet_id", tablet_id)
1277
0
                        .tag("key", hex(k));
1278
0
                continue;
1279
0
            }
1280
3
            if (stats) {
1281
3
                ++stats->rowset_scan_count;
1282
3
            }
1283
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1284
3
                *exists = true;
1285
3
                return 0;
1286
3
            }
1287
3
        }
1288
1289
0
        if (!it_range->more()) {
1290
0
            return 0;
1291
0
        }
1292
1293
        // Continue scanning from the next key to keep each transaction short.
1294
0
        scan_begin = std::move(last_key);
1295
0
        scan_begin.push_back('\x00');
1296
0
    }
1297
9
}
1298
1299
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1300
                                                          const std::string& rowset_id,
1301
                                                          int64_t txn_id, bool* recycle_exists,
1302
11
                                                          bool* tmp_exists) {
1303
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1304
0
        return -1;
1305
0
    }
1306
11
    *recycle_exists = false;
1307
11
    *tmp_exists = false;
1308
1309
11
    if (txn_id <= 0) {
1310
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1311
0
                .tag("instance_id", instance_id_)
1312
0
                .tag("tablet_id", tablet_id)
1313
0
                .tag("rowset_id", rowset_id)
1314
0
                .tag("txn_id", txn_id);
1315
0
        return -1;
1316
0
    }
1317
1318
11
    std::unique_ptr<Transaction> txn;
1319
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1320
11
    if (err != TxnErrorCode::TXN_OK) {
1321
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1322
0
                .tag("instance_id", instance_id_)
1323
0
                .tag("tablet_id", tablet_id)
1324
0
                .tag("rowset_id", rowset_id)
1325
0
                .tag("txn_id", txn_id)
1326
0
                .tag("err", err);
1327
0
        return -1;
1328
0
    }
1329
1330
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1331
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1332
11
    if (ret == TxnErrorCode::TXN_OK) {
1333
1
        *recycle_exists = true;
1334
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1335
0
        LOG_WARNING("failed to check recycle rowset existence")
1336
0
                .tag("instance_id", instance_id_)
1337
0
                .tag("tablet_id", tablet_id)
1338
0
                .tag("rowset_id", rowset_id)
1339
0
                .tag("key", hex(recycle_key))
1340
0
                .tag("err", ret);
1341
0
        return -1;
1342
0
    }
1343
1344
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1345
11
    ret = key_exists(txn.get(), tmp_key, true);
1346
11
    if (ret == TxnErrorCode::TXN_OK) {
1347
1
        *tmp_exists = true;
1348
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1349
0
        LOG_WARNING("failed to check tmp rowset existence")
1350
0
                .tag("instance_id", instance_id_)
1351
0
                .tag("tablet_id", tablet_id)
1352
0
                .tag("txn_id", txn_id)
1353
0
                .tag("key", hex(tmp_key))
1354
0
                .tag("err", ret);
1355
0
        return -1;
1356
0
    }
1357
1358
11
    return 0;
1359
11
}
1360
1361
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1362
8
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1363
8
    if (!hint.empty()) {
1364
8
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1365
8
            return {hint, it->second};
1366
8
        }
1367
8
    }
1368
1369
0
    return {"", nullptr};
1370
8
}
1371
1372
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1373
                                               const std::string& packed_file_path,
1374
3
                                               PackedFileRecycleStats* stats) {
1375
3
    bool local_changed = false;
1376
3
    int64_t left_num = 0;
1377
3
    int64_t left_bytes = 0;
1378
3
    bool all_small_files_confirmed = true;
1379
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1380
1381
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1382
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1383
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1384
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1385
14
        LOG_INFO("packed slice correction status")
1386
14
                .tag("instance_id", instance_id_)
1387
14
                .tag("packed_file_path", packed_file_path)
1388
14
                .tag("small_file_path", file.path())
1389
14
                .tag("tablet_id", tablet_id)
1390
14
                .tag("rowset_id", rowset_id)
1391
14
                .tag("txn_id", txn_id)
1392
14
                .tag("size", file.size())
1393
14
                .tag("deleted", file.deleted())
1394
14
                .tag("corrected", file.corrected())
1395
14
                .tag("confirmed_this_round", confirmed_this_round);
1396
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
1381
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1382
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1383
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1384
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1385
        LOG_INFO("packed slice correction status")
1386
14
                .tag("instance_id", instance_id_)
1387
14
                .tag("packed_file_path", packed_file_path)
1388
14
                .tag("small_file_path", file.path())
1389
14
                .tag("tablet_id", tablet_id)
1390
14
                .tag("rowset_id", rowset_id)
1391
14
                .tag("txn_id", txn_id)
1392
14
                .tag("size", file.size())
1393
14
                .tag("deleted", file.deleted())
1394
14
                .tag("corrected", file.corrected())
1395
14
                .tag("confirmed_this_round", confirmed_this_round);
1396
14
    };
1397
1398
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1399
14
        auto* small_file = packed_info->mutable_slices(i);
1400
14
        if (small_file->deleted()) {
1401
3
            log_small_file_status(*small_file, small_file->corrected());
1402
3
            continue;
1403
3
        }
1404
1405
11
        if (small_file->corrected()) {
1406
0
            left_num++;
1407
0
            left_bytes += small_file->size();
1408
0
            log_small_file_status(*small_file, true);
1409
0
            continue;
1410
0
        }
1411
1412
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1413
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1414
0
                    .tag("instance_id", instance_id_)
1415
0
                    .tag("small_file_path", small_file->path())
1416
0
                    .tag("index", i);
1417
0
            return -1;
1418
0
        }
1419
1420
11
        int64_t tablet_id = small_file->tablet_id();
1421
11
        const std::string& rowset_id = small_file->rowset_id();
1422
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1423
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1424
0
                    .tag("instance_id", instance_id_)
1425
0
                    .tag("small_file_path", small_file->path())
1426
0
                    .tag("index", i)
1427
0
                    .tag("tablet_id", tablet_id)
1428
0
                    .tag("rowset_id", rowset_id)
1429
0
                    .tag("has_txn_id", small_file->has_txn_id())
1430
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1431
0
            return -1;
1432
0
        }
1433
11
        int64_t txn_id = small_file->txn_id();
1434
11
        bool recycle_exists = false;
1435
11
        bool tmp_exists = false;
1436
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1437
11
                                                &tmp_exists) != 0) {
1438
0
            return -1;
1439
0
        }
1440
1441
11
        bool small_file_confirmed = false;
1442
11
        if (tmp_exists) {
1443
1
            left_num++;
1444
1
            left_bytes += small_file->size();
1445
1
            small_file_confirmed = true;
1446
10
        } else if (recycle_exists) {
1447
1
            left_num++;
1448
1
            left_bytes += small_file->size();
1449
            // keep small_file_confirmed=false so the packed file remains uncorrected
1450
9
        } else {
1451
9
            bool rowset_exists = false;
1452
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1453
0
                return -1;
1454
0
            }
1455
1456
9
            if (!rowset_exists) {
1457
6
                if (!small_file->deleted()) {
1458
6
                    small_file->set_deleted(true);
1459
6
                    local_changed = true;
1460
6
                }
1461
6
                if (!small_file->corrected()) {
1462
6
                    small_file->set_corrected(true);
1463
6
                    local_changed = true;
1464
6
                }
1465
6
                small_file_confirmed = true;
1466
6
            } else {
1467
3
                left_num++;
1468
3
                left_bytes += small_file->size();
1469
3
                small_file_confirmed = true;
1470
3
            }
1471
9
        }
1472
1473
11
        if (!small_file_confirmed) {
1474
1
            all_small_files_confirmed = false;
1475
1
        }
1476
1477
11
        if (small_file->corrected() != small_file_confirmed) {
1478
4
            small_file->set_corrected(small_file_confirmed);
1479
4
            local_changed = true;
1480
4
        }
1481
1482
11
        log_small_file_status(*small_file, small_file_confirmed);
1483
11
    }
1484
1485
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1486
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1487
3
        local_changed = true;
1488
3
    }
1489
3
    if (packed_info->ref_cnt() != left_num) {
1490
3
        auto old_ref_cnt = packed_info->ref_cnt();
1491
3
        packed_info->set_ref_cnt(left_num);
1492
3
        LOG_INFO("corrected packed file ref count")
1493
3
                .tag("instance_id", instance_id_)
1494
3
                .tag("resource_id", packed_info->resource_id())
1495
3
                .tag("packed_file_path", packed_file_path)
1496
3
                .tag("old_ref_cnt", old_ref_cnt)
1497
3
                .tag("new_ref_cnt", left_num);
1498
3
        local_changed = true;
1499
3
    }
1500
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1501
2
        packed_info->set_corrected(all_small_files_confirmed);
1502
2
        local_changed = true;
1503
2
    }
1504
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1505
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1506
1
        local_changed = true;
1507
1
    }
1508
1509
3
    if (changed != nullptr) {
1510
3
        *changed = local_changed;
1511
3
    }
1512
3
    return 0;
1513
3
}
1514
1515
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1516
                                                 const std::string& packed_file_path,
1517
3
                                                 PackedFileRecycleStats* stats) {
1518
3
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1519
3
    bool correction_ok = false;
1520
3
    cloud::PackedFileInfoPB packed_info;
1521
1522
3
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1523
3
        if (stopped()) {
1524
0
            LOG_WARNING("recycler stopped before processing packed file")
1525
0
                    .tag("instance_id", instance_id_)
1526
0
                    .tag("packed_file_path", packed_file_path)
1527
0
                    .tag("attempt", attempt);
1528
0
            return -1;
1529
0
        }
1530
1531
3
        std::unique_ptr<Transaction> txn;
1532
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1533
3
        if (err != TxnErrorCode::TXN_OK) {
1534
0
            LOG_WARNING("failed to create txn when processing packed file")
1535
0
                    .tag("instance_id", instance_id_)
1536
0
                    .tag("packed_file_path", packed_file_path)
1537
0
                    .tag("attempt", attempt)
1538
0
                    .tag("err", err);
1539
0
            return -1;
1540
0
        }
1541
1542
3
        std::string packed_val;
1543
3
        err = txn->get(packed_key, &packed_val);
1544
3
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1545
0
            return 0;
1546
0
        }
1547
3
        if (err != TxnErrorCode::TXN_OK) {
1548
0
            LOG_WARNING("failed to get packed file kv")
1549
0
                    .tag("instance_id", instance_id_)
1550
0
                    .tag("packed_file_path", packed_file_path)
1551
0
                    .tag("attempt", attempt)
1552
0
                    .tag("err", err);
1553
0
            return -1;
1554
0
        }
1555
1556
3
        if (!packed_info.ParseFromString(packed_val)) {
1557
0
            LOG_WARNING("failed to parse packed file info")
1558
0
                    .tag("instance_id", instance_id_)
1559
0
                    .tag("packed_file_path", packed_file_path)
1560
0
                    .tag("attempt", attempt);
1561
0
            return -1;
1562
0
        }
1563
1564
3
        int64_t now_sec = ::time(nullptr);
1565
3
        bool corrected = packed_info.corrected();
1566
3
        bool due = config::force_immediate_recycle ||
1567
3
                   now_sec - packed_info.created_at_sec() >=
1568
3
                           config::packed_file_correction_delay_seconds;
1569
1570
3
        if (!corrected && due) {
1571
3
            bool changed = false;
1572
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1573
0
                LOG_WARNING("correct_packed_file_info failed")
1574
0
                        .tag("instance_id", instance_id_)
1575
0
                        .tag("packed_file_path", packed_file_path)
1576
0
                        .tag("attempt", attempt);
1577
0
                return -1;
1578
0
            }
1579
3
            if (changed) {
1580
3
                std::string updated;
1581
3
                if (!packed_info.SerializeToString(&updated)) {
1582
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1583
0
                            .tag("instance_id", instance_id_)
1584
0
                            .tag("packed_file_path", packed_file_path)
1585
0
                            .tag("attempt", attempt);
1586
0
                    return -1;
1587
0
                }
1588
3
                txn->put(packed_key, updated);
1589
3
                err = txn->commit();
1590
3
                if (err == TxnErrorCode::TXN_OK) {
1591
3
                    if (stats) {
1592
3
                        ++stats->num_corrected;
1593
3
                    }
1594
3
                } else {
1595
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1596
0
                        LOG_WARNING(
1597
0
                                "failed to commit correction for packed file due to conflict, "
1598
0
                                "retrying")
1599
0
                                .tag("instance_id", instance_id_)
1600
0
                                .tag("packed_file_path", packed_file_path)
1601
0
                                .tag("attempt", attempt);
1602
0
                        sleep_for_packed_file_retry();
1603
0
                        packed_info.Clear();
1604
0
                        continue;
1605
0
                    }
1606
0
                    LOG_WARNING("failed to commit correction for packed file")
1607
0
                            .tag("instance_id", instance_id_)
1608
0
                            .tag("packed_file_path", packed_file_path)
1609
0
                            .tag("attempt", attempt)
1610
0
                            .tag("err", err);
1611
0
                    return -1;
1612
0
                }
1613
3
            }
1614
3
        }
1615
1616
3
        correction_ok = true;
1617
3
        break;
1618
3
    }
1619
1620
3
    if (!correction_ok) {
1621
0
        return -1;
1622
0
    }
1623
1624
3
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1625
3
          packed_info.ref_cnt() == 0)) {
1626
2
        return 0;
1627
2
    }
1628
1629
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1630
0
        LOG_WARNING("packed file missing resource id when recycling")
1631
0
                .tag("instance_id", instance_id_)
1632
0
                .tag("packed_file_path", packed_file_path);
1633
0
        return -1;
1634
0
    }
1635
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1636
1
    if (!accessor) {
1637
0
        LOG_WARNING("no accessor available to delete packed file")
1638
0
                .tag("instance_id", instance_id_)
1639
0
                .tag("packed_file_path", packed_file_path)
1640
0
                .tag("resource_id", packed_info.resource_id());
1641
0
        return -1;
1642
0
    }
1643
1
    int del_ret = accessor->delete_file(packed_file_path);
1644
1
    if (del_ret != 0 && del_ret != 1) {
1645
0
        LOG_WARNING("failed to delete packed file")
1646
0
                .tag("instance_id", instance_id_)
1647
0
                .tag("packed_file_path", packed_file_path)
1648
0
                .tag("resource_id", resource_id)
1649
0
                .tag("ret", del_ret);
1650
0
        return -1;
1651
0
    }
1652
1
    if (del_ret == 1) {
1653
0
        LOG_INFO("packed file already removed")
1654
0
                .tag("instance_id", instance_id_)
1655
0
                .tag("packed_file_path", packed_file_path)
1656
0
                .tag("resource_id", resource_id);
1657
1
    } else {
1658
1
        LOG_INFO("deleted packed file")
1659
1
                .tag("instance_id", instance_id_)
1660
1
                .tag("packed_file_path", packed_file_path)
1661
1
                .tag("resource_id", resource_id);
1662
1
    }
1663
1664
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1665
1
        std::unique_ptr<Transaction> del_txn;
1666
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1667
1
        if (err != TxnErrorCode::TXN_OK) {
1668
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1669
0
                    .tag("instance_id", instance_id_)
1670
0
                    .tag("packed_file_path", packed_file_path)
1671
0
                    .tag("del_attempt", del_attempt)
1672
0
                    .tag("err", err);
1673
0
            return -1;
1674
0
        }
1675
1676
1
        std::string latest_val;
1677
1
        err = del_txn->get(packed_key, &latest_val);
1678
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1679
0
            return 0;
1680
0
        }
1681
1
        if (err != TxnErrorCode::TXN_OK) {
1682
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1683
0
                    .tag("instance_id", instance_id_)
1684
0
                    .tag("packed_file_path", packed_file_path)
1685
0
                    .tag("del_attempt", del_attempt)
1686
0
                    .tag("err", err);
1687
0
            return -1;
1688
0
        }
1689
1690
1
        cloud::PackedFileInfoPB latest_info;
1691
1
        if (!latest_info.ParseFromString(latest_val)) {
1692
0
            LOG_WARNING("failed to parse packed file info before removal")
1693
0
                    .tag("instance_id", instance_id_)
1694
0
                    .tag("packed_file_path", packed_file_path)
1695
0
                    .tag("del_attempt", del_attempt);
1696
0
            return -1;
1697
0
        }
1698
1699
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1700
1
              latest_info.ref_cnt() == 0)) {
1701
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1702
0
                    .tag("instance_id", instance_id_)
1703
0
                    .tag("packed_file_path", packed_file_path)
1704
0
                    .tag("del_attempt", del_attempt);
1705
0
            return 0;
1706
0
        }
1707
1708
1
        del_txn->remove(packed_key);
1709
1
        err = del_txn->commit();
1710
1
        if (err == TxnErrorCode::TXN_OK) {
1711
1
            if (stats) {
1712
1
                ++stats->num_deleted;
1713
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1714
1
                                        static_cast<int64_t>(latest_val.size());
1715
1
                if (del_ret == 0 || del_ret == 1) {
1716
1
                    ++stats->num_object_deleted;
1717
1
                    int64_t object_size = latest_info.total_slice_bytes();
1718
1
                    if (object_size <= 0) {
1719
0
                        object_size = packed_info.total_slice_bytes();
1720
0
                    }
1721
1
                    stats->bytes_object_deleted += object_size;
1722
1
                }
1723
1
            }
1724
1
            LOG_INFO("removed packed file metadata")
1725
1
                    .tag("instance_id", instance_id_)
1726
1
                    .tag("packed_file_path", packed_file_path);
1727
1
            return 0;
1728
1
        }
1729
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1730
0
            if (del_attempt >= max_retry_times) {
1731
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1732
0
                        .tag("instance_id", instance_id_)
1733
0
                        .tag("packed_file_path", packed_file_path)
1734
0
                        .tag("del_attempt", del_attempt);
1735
0
                return -1;
1736
0
            }
1737
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1738
0
                    .tag("instance_id", instance_id_)
1739
0
                    .tag("packed_file_path", packed_file_path)
1740
0
                    .tag("del_attempt", del_attempt);
1741
0
            sleep_for_packed_file_retry();
1742
0
            continue;
1743
0
        }
1744
0
        LOG_WARNING("failed to remove packed file kv")
1745
0
                .tag("instance_id", instance_id_)
1746
0
                .tag("packed_file_path", packed_file_path)
1747
0
                .tag("del_attempt", del_attempt)
1748
0
                .tag("err", err);
1749
0
        return -1;
1750
0
    }
1751
1752
0
    return -1;
1753
1
}
1754
1755
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view value,
1756
4
                                            PackedFileRecycleStats* stats, int* ret) {
1757
4
    if (stats) {
1758
4
        ++stats->num_scanned;
1759
4
    }
1760
4
    std::string packed_file_path;
1761
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1762
0
        LOG_WARNING("failed to decode packed file key")
1763
0
                .tag("instance_id", instance_id_)
1764
0
                .tag("key", hex(key));
1765
0
        if (stats) {
1766
0
            ++stats->num_failed;
1767
0
        }
1768
0
        if (ret) {
1769
0
            *ret = -1;
1770
0
        }
1771
0
        return 0;
1772
0
    }
1773
1774
4
    cloud::PackedFileInfoPB packed_info;
1775
4
    if (!packed_info.ParseFromArray(value.data(), value.size())) {
1776
0
        LOG_WARNING("failed to parse packed file info from scan")
1777
0
                .tag("instance_id", instance_id_)
1778
0
                .tag("packed_file_path", packed_file_path);
1779
0
        if (stats) {
1780
0
            ++stats->num_failed;
1781
0
        }
1782
0
        if (ret) {
1783
0
            *ret = -1;
1784
0
        }
1785
0
        return 0;
1786
0
    }
1787
1788
4
    const int64_t now_sec = ::time(nullptr);
1789
4
    const bool due =
1790
4
            config::force_immediate_recycle ||
1791
4
            now_sec - packed_info.created_at_sec() >= config::packed_file_correction_delay_seconds;
1792
4
    const bool need_correction = !packed_info.corrected() && due;
1793
4
    const bool need_recycle =
1794
4
            packed_info.state() == cloud::PackedFileInfoPB::RECYCLING && packed_info.ref_cnt() == 0;
1795
4
    if (!need_correction && !need_recycle) {
1796
1
        return 0;
1797
1
    }
1798
1799
3
    std::string packed_key(key);
1800
3
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1801
3
    if (process_ret != 0) {
1802
0
        if (stats) {
1803
0
            ++stats->num_failed;
1804
0
        }
1805
0
        if (ret) {
1806
0
            *ret = -1;
1807
0
        }
1808
0
    }
1809
3
    return 0;
1810
4
}
1811
1812
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1813
6.34k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1814
6.34k
    if (config::force_immediate_recycle) {
1815
295
        return 0L;
1816
295
    }
1817
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1818
6.05k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1819
6.05k
    int64_t retention_seconds = config::retention_seconds;
1820
6.05k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1821
4.75k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1822
4.75k
    }
1823
6.05k
    int64_t final_expiration = expiration + retention_seconds;
1824
6.05k
    if (*earlest_ts > final_expiration) {
1825
17
        *earlest_ts = final_expiration;
1826
17
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1827
17
    }
1828
6.05k
    return final_expiration;
1829
6.34k
}
1830
1831
int64_t calculate_partition_expired_time(
1832
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1833
11
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1834
11
    if (config::force_immediate_recycle) {
1835
5
        return 0L;
1836
5
    }
1837
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1838
6
                                                            : partition_meta_pb.creation_time();
1839
6
    int64_t retention_seconds = config::retention_seconds;
1840
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1841
6
        retention_seconds =
1842
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1843
6
    }
1844
6
    int64_t final_expiration = expiration + retention_seconds;
1845
6
    if (*earlest_ts > final_expiration) {
1846
2
        *earlest_ts = final_expiration;
1847
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1848
2
    }
1849
6
    return final_expiration;
1850
11
}
1851
1852
int64_t calculate_index_expired_time(const std::string& instance_id_,
1853
                                     const RecycleIndexPB& index_meta_pb,
1854
14
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1855
14
    if (config::force_immediate_recycle) {
1856
8
        return 0L;
1857
8
    }
1858
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1859
6
                                                        : index_meta_pb.creation_time();
1860
6
    int64_t retention_seconds = config::retention_seconds;
1861
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1862
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1863
6
    }
1864
6
    int64_t final_expiration = expiration + retention_seconds;
1865
6
    if (*earlest_ts > final_expiration) {
1866
2
        *earlest_ts = final_expiration;
1867
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1868
2
    }
1869
6
    return final_expiration;
1870
14
}
1871
1872
int64_t calculate_tmp_rowset_expired_time(
1873
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1874
53.2k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1875
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1876
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1877
    //  duration or timeout always < `retention_time` in practice.
1878
53.2k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1879
53.2k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1880
53.2k
                                 : tmp_rowset_meta_pb.creation_time();
1881
53.2k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1882
53.2k
    int64_t final_expiration = expiration + config::retention_seconds;
1883
53.2k
    if (*earlest_ts > final_expiration) {
1884
20
        *earlest_ts = final_expiration;
1885
20
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1886
20
    }
1887
53.2k
    return final_expiration;
1888
53.2k
}
1889
1890
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1891
30.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1892
30.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1893
30.0k
    if (*earlest_ts > final_expiration / 1000) {
1894
8
        *earlest_ts = final_expiration / 1000;
1895
8
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1896
8
    }
1897
30.0k
    return final_expiration;
1898
30.0k
}
1899
1900
int64_t calculate_restore_job_expired_time(
1901
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1902
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1903
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1904
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1905
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1906
        // final state, recycle immediately
1907
41
        return 0L;
1908
41
    }
1909
    // not final state, wait much longer than the FE's timeout(1 day)
1910
0
    int64_t last_modified_s =
1911
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1912
0
    int64_t expiration = restore_job.expired_at_s() > 0
1913
0
                                 ? last_modified_s + restore_job.expired_at_s()
1914
0
                                 : last_modified_s;
1915
0
    int64_t final_expiration = expiration + config::retention_seconds;
1916
0
    if (*earlest_ts > final_expiration) {
1917
0
        *earlest_ts = final_expiration;
1918
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1919
0
    }
1920
0
    return final_expiration;
1921
41
}
1922
1923
537
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1924
537
    AbortTxnRequest req;
1925
537
    TxnInfoPB txn_info;
1926
537
    MetaServiceCode code = MetaServiceCode::OK;
1927
537
    std::string msg;
1928
537
    std::stringstream ss;
1929
537
    std::unique_ptr<Transaction> txn;
1930
537
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1931
537
    if (err != TxnErrorCode::TXN_OK) {
1932
0
        LOG_WARNING("failed to create txn").tag("err", err);
1933
0
        return -1;
1934
0
    }
1935
1936
    // get txn index
1937
537
    TxnIndexPB txn_idx_pb;
1938
537
    auto index_key = txn_index_key({instance_id_, txn_id});
1939
537
    std::string index_val;
1940
537
    err = txn->get(index_key, &index_val);
1941
537
    if (err != TxnErrorCode::TXN_OK) {
1942
2
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1943
            // maybe recycled
1944
2
            LOG_WARNING("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1945
2
                    .tag("key", hex(index_key))
1946
2
                    .tag("txn_id", txn_id);
1947
2
            return 0;
1948
2
        }
1949
0
        LOG_WARNING("failed to get txn index")
1950
0
                .tag("err", err)
1951
0
                .tag("key", hex(index_key))
1952
0
                .tag("txn_id", txn_id);
1953
0
        return -1;
1954
2
    }
1955
535
    if (!txn_idx_pb.ParseFromString(index_val)) {
1956
1
        LOG_WARNING("failed to parse txn index")
1957
1
                .tag("err", err)
1958
1
                .tag("key", hex(index_key))
1959
1
                .tag("txn_id", txn_id);
1960
1
        return -1;
1961
1
    }
1962
534
    if (!txn_idx_pb.has_tablet_index() || !txn_idx_pb.tablet_index().has_db_id() ||
1963
534
        txn_idx_pb.tablet_index().db_id() <= 0) {
1964
3
        LOG_WARNING("malformed txn index, tablet index is missing or db id is invalid")
1965
3
                .tag("key", hex(index_key))
1966
3
                .tag("txn_id", txn_id)
1967
3
                .tag("db_id",
1968
3
                     txn_idx_pb.has_tablet_index() ? txn_idx_pb.tablet_index().db_id() : 0);
1969
3
        return -1;
1970
3
    }
1971
1972
531
    const int64_t db_id = txn_idx_pb.tablet_index().db_id();
1973
531
    const int64_t owner_txn_id =
1974
531
            txn_idx_pb.has_parent_txn_id() ? txn_idx_pb.parent_txn_id() : txn_id;
1975
531
    if (owner_txn_id <= 0) {
1976
1
        LOG_WARNING("malformed txn index, owner txn id is invalid")
1977
1
                .tag("key", hex(index_key))
1978
1
                .tag("txn_id", txn_id)
1979
1
                .tag("owner_txn_id", owner_txn_id);
1980
1
        return -1;
1981
1
    }
1982
1983
530
    auto info_key = txn_info_key({instance_id_, db_id, owner_txn_id});
1984
530
    std::string info_val;
1985
530
    err = txn->get(info_key, &info_val);
1986
530
    if (err != TxnErrorCode::TXN_OK) {
1987
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1988
            // maybe recycled
1989
1
            LOG_WARNING("txn info not found, txn_id={} owner_txn_id={} instance_id={}", txn_id,
1990
1
                        owner_txn_id, instance_id_)
1991
1
                    .tag("key", hex(info_key))
1992
1
                    .tag("txn_id", txn_id)
1993
1
                    .tag("owner_txn_id", owner_txn_id);
1994
1
            return 0;
1995
1
        }
1996
0
        LOG_WARNING("failed to get txn info")
1997
0
                .tag("err", err)
1998
0
                .tag("key", hex(info_key))
1999
0
                .tag("txn_id", txn_id)
2000
0
                .tag("owner_txn_id", owner_txn_id);
2001
0
        return -1;
2002
1
    }
2003
529
    if (!txn_info.ParseFromString(info_val)) {
2004
1
        LOG_WARNING("failed to parse txn info")
2005
1
                .tag("err", err)
2006
1
                .tag("key", hex(info_key))
2007
1
                .tag("txn_id", txn_id)
2008
1
                .tag("owner_txn_id", owner_txn_id);
2009
1
        return -1;
2010
1
    }
2011
528
    if (!txn_info.has_txn_id() || txn_info.txn_id() != owner_txn_id) {
2012
1
        LOG_WARNING("malformed txn info, txn id does not match owner txn id")
2013
1
                .tag("key", hex(info_key))
2014
1
                .tag("txn_id", txn_id)
2015
1
                .tag("owner_txn_id", owner_txn_id)
2016
1
                .tag("txn_info_txn_id", txn_info.txn_id());
2017
1
        return -1;
2018
1
    }
2019
2020
527
    if (txn_info.status() == TxnStatusPB::TXN_STATUS_ABORTED) {
2021
514
        LOG_INFO("txn has already been aborted, txn_id={} owner_txn_id={}", txn_id, owner_txn_id)
2022
514
                .tag("key", hex(info_key))
2023
514
                .tag("txn_id", txn_id)
2024
514
                .tag("owner_txn_id", owner_txn_id);
2025
514
        return 0;
2026
514
    }
2027
13
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
2028
4
        LOG_WARNING("txn cannot be aborted, txn_id={} owner_txn_id={} status={}", txn_id,
2029
4
                    owner_txn_id, txn_info.status())
2030
4
                .tag("key", hex(info_key))
2031
4
                .tag("txn_id", txn_id)
2032
4
                .tag("owner_txn_id", owner_txn_id);
2033
4
        return -1;
2034
4
    }
2035
2036
9
    req.set_txn_id(owner_txn_id);
2037
9
    req.set_db_id(db_id);
2038
2039
9
    LOG(WARNING) << "begin abort txn for related rowset, txn_id=" << txn_id
2040
9
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2041
9
                 << " txn_info=" << txn_info.ShortDebugString();
2042
2043
9
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
2044
9
    if (code != MetaServiceCode::OK) {
2045
0
        LOG(WARNING) << "failed to abort txn for related rowset, txn_id=" << txn_id
2046
0
                     << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2047
0
                     << " code=" << code << " msg=" << msg;
2048
0
        return -1;
2049
0
    }
2050
2051
9
    err = txn->commit();
2052
9
    if (err != TxnErrorCode::TXN_OK) {
2053
0
        code = cast_as<ErrCategory::COMMIT>(err);
2054
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
2055
0
        msg = ss.str();
2056
0
        return -1;
2057
0
    }
2058
2059
9
    LOG(WARNING) << "finish abort txn for related rowset, txn_id=" << txn_id
2060
9
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2061
9
                 << " txn_info=" << txn_info.ShortDebugString() << " code=" << code
2062
9
                 << " msg=" << msg;
2063
2064
9
    return 0;
2065
9
}
2066
2067
int InstanceRecycler::abort_job_for_related_rowset(int64_t tablet_id, const std::string& rowset_id,
2068
11
                                                   const std::string& job_id) {
2069
11
    FinishTabletJobRequest req;
2070
11
    FinishTabletJobResponse res;
2071
11
    req.set_action(FinishTabletJobRequest::ABORT);
2072
11
    MetaServiceCode code = MetaServiceCode::OK;
2073
11
    std::string msg;
2074
11
    std::stringstream ss;
2075
2076
11
    TabletIndexPB tablet_idx;
2077
11
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, tablet_id, tablet_idx);
2078
11
    if (ret == 1) {
2079
        // tablet maybe recycled, directly return 0
2080
1
        return 0;
2081
10
    } else if (ret != 0) {
2082
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << tablet_id
2083
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
2084
0
        return ret;
2085
0
    }
2086
2087
10
    std::unique_ptr<Transaction> txn;
2088
10
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2089
10
    if (err != TxnErrorCode::TXN_OK) {
2090
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
2091
0
        return -1;
2092
0
    }
2093
2094
10
    std::string job_key =
2095
10
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
2096
10
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
2097
10
    std::string job_val;
2098
10
    err = txn->get(job_key, &job_val);
2099
10
    if (err != TxnErrorCode::TXN_OK) {
2100
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2101
1
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
2102
1
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2103
            // A previous recycler round may have aborted the job. The caller must recheck the
2104
            // recycle key before deleting object data.
2105
1
            return 0;
2106
1
        }
2107
1
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
2108
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
2109
0
                     << " key=" << hex(job_key);
2110
0
        return -1;
2111
1
    }
2112
2113
9
    TabletJobInfoPB job_pb;
2114
9
    if (!job_pb.ParseFromString(job_val)) {
2115
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
2116
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2117
0
        return -1;
2118
0
    }
2119
2120
9
    const TabletCompactionJobPB* matched_compaction = nullptr;
2121
9
    for (const auto& compaction : job_pb.compaction()) {
2122
9
        if (compaction.id() == job_id) {
2123
5
            matched_compaction = &compaction;
2124
5
            break;
2125
5
        }
2126
9
    }
2127
9
    const TabletSchemaChangeJobPB* matched_schema_change = nullptr;
2128
9
    if (matched_compaction == nullptr && job_pb.has_schema_change() &&
2129
9
        job_pb.schema_change().id() == job_id) {
2130
3
        matched_schema_change = &job_pb.schema_change();
2131
3
    }
2132
2133
9
    if (matched_compaction != nullptr || matched_schema_change != nullptr) {
2134
8
        LOG(WARNING) << "begin to abort job for related rowset, job_id=" << job_id
2135
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
2136
        // Compaction jobs belong to the rowset's tablet. A schema-change job is mirrored under
2137
        // the new tablet key, but its recorded index remains the base tablet so ABORT can remove
2138
        // both the base and mirrored schema-change records.
2139
8
        if (matched_compaction != nullptr) {
2140
5
            req.mutable_job()->mutable_idx()->CopyFrom(tablet_idx);
2141
5
            req.mutable_job()->add_compaction()->CopyFrom(*matched_compaction);
2142
5
        } else {
2143
3
            req.mutable_job()->mutable_idx()->CopyFrom(job_pb.idx());
2144
3
            req.mutable_job()->mutable_schema_change()->CopyFrom(*matched_schema_change);
2145
3
        }
2146
8
        req.set_action(FinishTabletJobRequest::ABORT);
2147
8
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
2148
8
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
2149
8
                           ss);
2150
8
        if (code != MetaServiceCode::OK) {
2151
            // These two codes mean that the job cannot be aborted anymore.
2152
            // TABLET_NOT_FOUND means that the tablet has been dropped or recycled.
2153
            // There is no running job that still owns the PREPARE rowset, so the caller may
2154
            // recheck the recycle key.
2155
0
            bool no_job_to_abort = code == MetaServiceCode::TABLET_NOT_FOUND;
2156
            // INVALID_ARGUMENT has more than one meaning. It may mean that this job was removed or
2157
            // replaced by a newer job, but it may also report invalid metadata. Read the current
2158
            // job again and continue recycling only when the target job id no longer exists.
2159
0
            if (!no_job_to_abort && code == MetaServiceCode::INVALID_ARGUMENT) {
2160
0
                std::unique_ptr<Transaction> check_txn;
2161
0
                err = txn_kv_->create_txn(&check_txn);
2162
0
                if (err != TxnErrorCode::TXN_OK) {
2163
0
                    LOG(WARNING) << "failed to create txn to check related job, instance_id="
2164
0
                                 << instance_id_ << " err=" << err;
2165
0
                    return -1;
2166
0
                }
2167
2168
0
                const auto& idx = req.job().idx();
2169
0
                std::string current_job_key =
2170
0
                        job_tablet_key({instance_id_, idx.table_id(), idx.index_id(),
2171
0
                                        idx.partition_id(), idx.tablet_id()});
2172
0
                std::string current_job_val;
2173
0
                err = check_txn->get(current_job_key, &current_job_val);
2174
0
                if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2175
0
                    no_job_to_abort = true;
2176
0
                } else if (err != TxnErrorCode::TXN_OK) {
2177
0
                    LOG(WARNING) << "failed to check related job, instance_id=" << instance_id_
2178
0
                                 << " tablet_id=" << idx.tablet_id() << " err=" << err
2179
0
                                 << " key=" << hex(current_job_key);
2180
0
                    return -1;
2181
0
                } else {
2182
0
                    TabletJobInfoPB current_job;
2183
0
                    if (!current_job.ParseFromString(current_job_val)) {
2184
0
                        LOG(WARNING) << "failed to parse related job, instance_id=" << instance_id_
2185
0
                                     << " tablet_id=" << idx.tablet_id()
2186
0
                                     << " key=" << hex(current_job_key);
2187
0
                        return -1;
2188
0
                    }
2189
0
                    if (matched_compaction != nullptr) {
2190
0
                        no_job_to_abort = true;
2191
0
                        for (const auto& compaction : current_job.compaction()) {
2192
0
                            if (compaction.id() == job_id) {
2193
0
                                no_job_to_abort = false;
2194
0
                                break;
2195
0
                            }
2196
0
                        }
2197
0
                    } else {
2198
0
                        no_job_to_abort = !current_job.has_schema_change() ||
2199
0
                                          current_job.schema_change().id() != job_id;
2200
0
                    }
2201
0
                }
2202
0
            }
2203
0
            if (no_job_to_abort) {
2204
0
                return 0;
2205
0
            }
2206
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
2207
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
2208
0
                         << " msg=" << msg;
2209
0
            return -1;
2210
0
        }
2211
8
        LOG(WARNING) << "finish abort job for related rowset, job_id=" << job_id
2212
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
2213
8
                     << " code=" << code << " msg=" << msg;
2214
8
    } else {
2215
        // clang-format off
2216
1
        LOG(INFO) << "there is no job for related rowset, recheck recycle rowset before deletion"
2217
1
                  << ", instance_id=" << instance_id_ 
2218
1
                  << ", tablet_id=" << tablet_idx.tablet_id() 
2219
1
                  << ", job_id=" << job_id
2220
1
                  << ", rowset_id=" << rowset_id;
2221
        // clang-format on
2222
1
    }
2223
2224
9
    return 0;
2225
9
}
2226
2227
template <typename T>
2228
22
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2229
22
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2230
13
        return rowset_meta_pb.mutable_rowset_meta();
2231
13
    } else {
2232
9
        return &rowset_meta_pb;
2233
9
    }
2234
22
}
_ZN5doris5cloud19mutable_rowset_metaINS0_15RecycleRowsetPBEEEPNS_17RowsetMetaCloudPBERT_
Line
Count
Source
2228
13
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2229
13
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2230
13
        return rowset_meta_pb.mutable_rowset_meta();
2231
    } else {
2232
        return &rowset_meta_pb;
2233
    }
2234
13
}
_ZN5doris5cloud19mutable_rowset_metaINS_17RowsetMetaCloudPBEEEPS2_RT_
Line
Count
Source
2228
9
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2229
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2230
        return rowset_meta_pb.mutable_rowset_meta();
2231
9
    } else {
2232
9
        return &rowset_meta_pb;
2233
9
    }
2234
9
}
2235
2236
template <typename T>
2237
1.63k
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2238
1.63k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2239
833
        return rowset_meta_pb.rowset_meta();
2240
833
    } else {
2241
799
        return rowset_meta_pb;
2242
799
    }
2243
1.63k
}
_ZN5doris5cloud11rowset_metaINS0_15RecycleRowsetPBEEERKNS_17RowsetMetaCloudPBERKT_
Line
Count
Source
2237
833
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2238
833
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2239
833
        return rowset_meta_pb.rowset_meta();
2240
    } else {
2241
        return rowset_meta_pb;
2242
    }
2243
833
}
_ZN5doris5cloud11rowset_metaINS_17RowsetMetaCloudPBEEERKS2_RKT_
Line
Count
Source
2237
799
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2238
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2239
        return rowset_meta_pb.rowset_meta();
2240
799
    } else {
2241
799
        return rowset_meta_pb;
2242
799
    }
2243
799
}
2244
2245
template <typename T>
2246
std::optional<RelatedTxnOrJobAbortTask> make_related_txn_or_job_abort_task(
2247
1.07k
        const T& rowset_meta_pb) {
2248
1.07k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2249
545
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2250
0
            return std::nullopt;
2251
0
        }
2252
545
    }
2253
2254
545
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2255
1.07k
    RelatedTxnOrJobAbortTask task;
2256
1.07k
    task.tablet_id = rs_meta.tablet_id();
2257
1.07k
    task.start_version = rs_meta.start_version();
2258
1.07k
    task.end_version = rs_meta.end_version();
2259
1.07k
    task.rowset_id = rs_meta.rowset_id_v2();
2260
1.07k
    if (rs_meta.has_load_id()) {
2261
1.05k
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2262
1.05k
        task.txn_id = rs_meta.txn_id();
2263
1.05k
        return task;
2264
1.05k
    }
2265
19
    if (rs_meta.has_job_id()) {
2266
14
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2267
14
        task.job_id = rs_meta.job_id();
2268
14
        return task;
2269
14
    }
2270
5
    return std::nullopt;
2271
19
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2247
545
        const T& rowset_meta_pb) {
2248
545
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2249
545
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2250
0
            return std::nullopt;
2251
0
        }
2252
545
    }
2253
2254
545
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2255
545
    RelatedTxnOrJobAbortTask task;
2256
545
    task.tablet_id = rs_meta.tablet_id();
2257
545
    task.start_version = rs_meta.start_version();
2258
545
    task.end_version = rs_meta.end_version();
2259
545
    task.rowset_id = rs_meta.rowset_id_v2();
2260
545
    if (rs_meta.has_load_id()) {
2261
534
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2262
534
        task.txn_id = rs_meta.txn_id();
2263
534
        return task;
2264
534
    }
2265
11
    if (rs_meta.has_job_id()) {
2266
10
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2267
10
        task.job_id = rs_meta.job_id();
2268
10
        return task;
2269
10
    }
2270
1
    return std::nullopt;
2271
11
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2247
526
        const T& rowset_meta_pb) {
2248
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2249
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2250
            return std::nullopt;
2251
        }
2252
    }
2253
2254
526
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2255
526
    RelatedTxnOrJobAbortTask task;
2256
526
    task.tablet_id = rs_meta.tablet_id();
2257
526
    task.start_version = rs_meta.start_version();
2258
526
    task.end_version = rs_meta.end_version();
2259
526
    task.rowset_id = rs_meta.rowset_id_v2();
2260
526
    if (rs_meta.has_load_id()) {
2261
518
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2262
518
        task.txn_id = rs_meta.txn_id();
2263
518
        return task;
2264
518
    }
2265
8
    if (rs_meta.has_job_id()) {
2266
4
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2267
4
        task.job_id = rs_meta.job_id();
2268
4
        return task;
2269
4
    }
2270
4
    return std::nullopt;
2271
8
}
2272
2273
template <typename T>
2274
bool matches_related_txn_or_job_abort_task(const T& rowset_meta_pb,
2275
529
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2276
529
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2277
268
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2278
0
            return false;
2279
0
        }
2280
268
    }
2281
2282
268
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2283
529
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2284
529
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2285
0
        return false;
2286
0
    }
2287
529
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2288
523
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2289
523
    }
2290
6
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2291
529
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2275
268
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2276
268
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2277
268
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2278
0
            return false;
2279
0
        }
2280
268
    }
2281
2282
268
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2283
268
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2284
268
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2285
0
        return false;
2286
0
    }
2287
268
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2288
264
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2289
264
    }
2290
4
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2291
268
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2275
261
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2276
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2277
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2278
            return false;
2279
        }
2280
    }
2281
2282
261
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2283
261
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2284
261
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2285
0
        return false;
2286
0
    }
2287
261
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2288
259
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2289
259
    }
2290
2
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2291
261
}
2292
2293
71
bool need_mark_rowset_as_recycled(const RowsetMetaCloudPB& rowset_meta_pb) {
2294
71
    return !rowset_meta_pb.has_is_recycled() || !rowset_meta_pb.is_recycled();
2295
71
}
2296
2297
template <typename T>
2298
int batch_mark_rowsets_as_recycled(TxnKv* txn_kv, const std::string& instance_id,
2299
18
                                   const std::vector<std::string>& keys) {
2300
35
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2301
18
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2302
18
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2303
18
        std::unique_ptr<Transaction> txn;
2304
18
        TxnErrorCode err = txn_kv->create_txn(&txn);
2305
18
        if (err != TxnErrorCode::TXN_OK) {
2306
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2307
0
            return -1;
2308
0
        }
2309
18
        std::vector<std::optional<std::string>> values;
2310
18
        err = txn->batch_get(&values, batch_keys);
2311
18
        if (err != TxnErrorCode::TXN_OK) {
2312
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2313
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2314
0
            return -1;
2315
0
        }
2316
18
        DCHECK_EQ(values.size(), batch_keys.size());
2317
40
        for (size_t i = 0; i < batch_keys.size(); i++) {
2318
22
            if (!values[i].has_value()) {
2319
                // has already been removed by commit_rowset
2320
0
                continue;
2321
0
            }
2322
22
            const auto& key = batch_keys[i];
2323
22
            auto val = values[i].value();
2324
22
            T rowset_meta_pb;
2325
22
            if (!rowset_meta_pb.ParseFromString(val)) {
2326
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2327
0
                             << " key=" << hex(key);
2328
0
                return -1;
2329
0
            }
2330
22
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2331
0
                continue;
2332
0
            }
2333
22
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2334
22
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2335
13
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2336
13
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2337
13
            }
2338
22
            val.clear();
2339
22
            rowset_meta_pb.SerializeToString(&val);
2340
22
            txn->put(key, val);
2341
22
        }
2342
18
        err = txn->commit();
2343
18
        if (err != TxnErrorCode::TXN_OK) {
2344
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2345
1
            return -1;
2346
1
        }
2347
18
    }
2348
2349
17
    return 0;
2350
18
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2299
11
                                   const std::vector<std::string>& keys) {
2300
21
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2301
11
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2302
11
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2303
11
        std::unique_ptr<Transaction> txn;
2304
11
        TxnErrorCode err = txn_kv->create_txn(&txn);
2305
11
        if (err != TxnErrorCode::TXN_OK) {
2306
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2307
0
            return -1;
2308
0
        }
2309
11
        std::vector<std::optional<std::string>> values;
2310
11
        err = txn->batch_get(&values, batch_keys);
2311
11
        if (err != TxnErrorCode::TXN_OK) {
2312
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2313
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2314
0
            return -1;
2315
0
        }
2316
11
        DCHECK_EQ(values.size(), batch_keys.size());
2317
24
        for (size_t i = 0; i < batch_keys.size(); i++) {
2318
13
            if (!values[i].has_value()) {
2319
                // has already been removed by commit_rowset
2320
0
                continue;
2321
0
            }
2322
13
            const auto& key = batch_keys[i];
2323
13
            auto val = values[i].value();
2324
13
            T rowset_meta_pb;
2325
13
            if (!rowset_meta_pb.ParseFromString(val)) {
2326
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2327
0
                             << " key=" << hex(key);
2328
0
                return -1;
2329
0
            }
2330
13
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2331
0
                continue;
2332
0
            }
2333
13
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2334
13
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2335
13
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2336
13
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2337
13
            }
2338
13
            val.clear();
2339
13
            rowset_meta_pb.SerializeToString(&val);
2340
13
            txn->put(key, val);
2341
13
        }
2342
11
        err = txn->commit();
2343
11
        if (err != TxnErrorCode::TXN_OK) {
2344
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2345
1
            return -1;
2346
1
        }
2347
11
    }
2348
2349
10
    return 0;
2350
11
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2299
7
                                   const std::vector<std::string>& keys) {
2300
14
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2301
7
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2302
7
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2303
7
        std::unique_ptr<Transaction> txn;
2304
7
        TxnErrorCode err = txn_kv->create_txn(&txn);
2305
7
        if (err != TxnErrorCode::TXN_OK) {
2306
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2307
0
            return -1;
2308
0
        }
2309
7
        std::vector<std::optional<std::string>> values;
2310
7
        err = txn->batch_get(&values, batch_keys);
2311
7
        if (err != TxnErrorCode::TXN_OK) {
2312
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2313
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2314
0
            return -1;
2315
0
        }
2316
7
        DCHECK_EQ(values.size(), batch_keys.size());
2317
16
        for (size_t i = 0; i < batch_keys.size(); i++) {
2318
9
            if (!values[i].has_value()) {
2319
                // has already been removed by commit_rowset
2320
0
                continue;
2321
0
            }
2322
9
            const auto& key = batch_keys[i];
2323
9
            auto val = values[i].value();
2324
9
            T rowset_meta_pb;
2325
9
            if (!rowset_meta_pb.ParseFromString(val)) {
2326
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2327
0
                             << " key=" << hex(key);
2328
0
                return -1;
2329
0
            }
2330
9
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2331
0
                continue;
2332
0
            }
2333
9
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2334
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2335
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2336
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2337
            }
2338
9
            val.clear();
2339
9
            rowset_meta_pb.SerializeToString(&val);
2340
9
            txn->put(key, val);
2341
9
        }
2342
7
        err = txn->commit();
2343
7
        if (err != TxnErrorCode::TXN_OK) {
2344
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2345
0
            return -1;
2346
0
        }
2347
7
    }
2348
2349
7
    return 0;
2350
7
}
2351
2352
template <typename T>
2353
void InstanceRecycler::submit_batch_mark_rowsets_as_recycled_job(
2354
18
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2355
18
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2356
18
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2357
1
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2358
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2359
1
        }
2360
18
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2355
11
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2356
11
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2357
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2358
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2359
1
        }
2360
11
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2355
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2356
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2357
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2358
0
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2359
0
        }
2360
7
    });
2361
18
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2354
11
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2355
11
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2356
11
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2357
11
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2358
11
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2359
11
        }
2360
11
    });
2361
11
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2354
7
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2355
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2356
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2357
7
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2358
7
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2359
7
        }
2360
7
    });
2361
7
}
2362
2363
template <typename T>
2364
int collect_deferred_abort_tasks(TxnKv* txn_kv, const std::string& instance_id,
2365
                                 const std::vector<std::string>& keys,
2366
20
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2367
42
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2368
22
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2369
22
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2370
22
        std::unique_ptr<Transaction> txn;
2371
22
        TxnErrorCode err = txn_kv->create_txn(&txn);
2372
22
        if (err != TxnErrorCode::TXN_OK) {
2373
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2374
0
            return -1;
2375
0
        }
2376
22
        std::vector<std::optional<std::string>> values;
2377
22
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2378
22
        if (err != TxnErrorCode::TXN_OK) {
2379
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2380
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2381
0
            return -1;
2382
0
        }
2383
22
        DCHECK_EQ(values.size(), batch_keys.size());
2384
555
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2385
533
            const std::string& key = batch_keys[idx];
2386
533
            if (!values[idx].has_value()) {
2387
                // has already been removed
2388
0
                continue;
2389
0
            }
2390
533
            T rowset_meta_pb;
2391
533
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2392
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2393
0
                             << " key=" << hex(key);
2394
0
                return -1;
2395
0
            }
2396
533
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2397
533
                abort_task.has_value()) {
2398
533
                abort_task->key = key;
2399
533
                abort_tasks->emplace_back(std::move(*abort_task));
2400
533
            }
2401
533
        }
2402
22
    }
2403
20
    return 0;
2404
20
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2366
15
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2367
31
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2368
16
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2369
16
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2370
16
        std::unique_ptr<Transaction> txn;
2371
16
        TxnErrorCode err = txn_kv->create_txn(&txn);
2372
16
        if (err != TxnErrorCode::TXN_OK) {
2373
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2374
0
            return -1;
2375
0
        }
2376
16
        std::vector<std::optional<std::string>> values;
2377
16
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2378
16
        if (err != TxnErrorCode::TXN_OK) {
2379
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2380
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2381
0
            return -1;
2382
0
        }
2383
16
        DCHECK_EQ(values.size(), batch_keys.size());
2384
288
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2385
272
            const std::string& key = batch_keys[idx];
2386
272
            if (!values[idx].has_value()) {
2387
                // has already been removed
2388
0
                continue;
2389
0
            }
2390
272
            T rowset_meta_pb;
2391
272
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2392
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2393
0
                             << " key=" << hex(key);
2394
0
                return -1;
2395
0
            }
2396
272
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2397
272
                abort_task.has_value()) {
2398
272
                abort_task->key = key;
2399
272
                abort_tasks->emplace_back(std::move(*abort_task));
2400
272
            }
2401
272
        }
2402
16
    }
2403
15
    return 0;
2404
15
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2366
5
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2367
11
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2368
6
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2369
6
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2370
6
        std::unique_ptr<Transaction> txn;
2371
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2372
6
        if (err != TxnErrorCode::TXN_OK) {
2373
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2374
0
            return -1;
2375
0
        }
2376
6
        std::vector<std::optional<std::string>> values;
2377
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2378
6
        if (err != TxnErrorCode::TXN_OK) {
2379
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2380
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2381
0
            return -1;
2382
0
        }
2383
6
        DCHECK_EQ(values.size(), batch_keys.size());
2384
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2385
261
            const std::string& key = batch_keys[idx];
2386
261
            if (!values[idx].has_value()) {
2387
                // has already been removed
2388
0
                continue;
2389
0
            }
2390
261
            T rowset_meta_pb;
2391
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2392
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2393
0
                             << " key=" << hex(key);
2394
0
                return -1;
2395
0
            }
2396
261
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2397
261
                abort_task.has_value()) {
2398
261
                abort_task->key = key;
2399
261
                abort_tasks->emplace_back(std::move(*abort_task));
2400
261
            }
2401
261
        }
2402
6
    }
2403
5
    return 0;
2404
5
}
2405
2406
template <typename T>
2407
int batch_recheck_rowsets_after_abort(
2408
        TxnKv* txn_kv, const std::string& instance_id,
2409
        const std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck,
2410
18
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2411
18
    int ret = 0;
2412
38
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2413
20
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2414
20
        std::vector<std::string> batch_keys;
2415
20
        batch_keys.reserve(limit - offset);
2416
550
        for (size_t idx = offset; idx < limit; ++idx) {
2417
530
            batch_keys.push_back(keys_to_recheck[idx].first);
2418
530
        }
2419
2420
20
        std::unique_ptr<Transaction> txn;
2421
20
        TxnErrorCode err = txn_kv->create_txn(&txn);
2422
20
        if (err != TxnErrorCode::TXN_OK) {
2423
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2424
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2425
0
            ret = -1;
2426
0
            continue;
2427
0
        }
2428
2429
20
        std::vector<std::optional<std::string>> values;
2430
20
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2431
20
        if (err != TxnErrorCode::TXN_OK) {
2432
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2433
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2434
0
            ret = -1;
2435
0
            continue;
2436
0
        }
2437
20
        DCHECK_EQ(values.size(), batch_keys.size());
2438
20
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2439
20
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2440
20
                                 &batch_size);
2441
2442
550
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2443
530
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2444
530
            if (!values[idx].has_value()) {
2445
1
                continue;
2446
1
            }
2447
2448
529
            T rowset_meta_pb;
2449
529
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2450
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2451
0
                             << instance_id << " key=" << hex(key);
2452
0
                ret = -1;
2453
0
                continue;
2454
0
            }
2455
529
            if (config::enable_mark_delete_rowset_before_recycle &&
2456
529
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2457
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2458
0
                             << instance_id << " key=" << hex(key);
2459
0
                continue;
2460
0
            }
2461
529
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2462
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2463
1
                             << instance_id << " key=" << hex(key);
2464
1
                continue;
2465
1
            }
2466
528
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2467
528
        }
2468
20
    }
2469
18
    return ret;
2470
18
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2410
13
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2411
13
    int ret = 0;
2412
27
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2413
14
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2414
14
        std::vector<std::string> batch_keys;
2415
14
        batch_keys.reserve(limit - offset);
2416
283
        for (size_t idx = offset; idx < limit; ++idx) {
2417
269
            batch_keys.push_back(keys_to_recheck[idx].first);
2418
269
        }
2419
2420
14
        std::unique_ptr<Transaction> txn;
2421
14
        TxnErrorCode err = txn_kv->create_txn(&txn);
2422
14
        if (err != TxnErrorCode::TXN_OK) {
2423
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2424
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2425
0
            ret = -1;
2426
0
            continue;
2427
0
        }
2428
2429
14
        std::vector<std::optional<std::string>> values;
2430
14
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2431
14
        if (err != TxnErrorCode::TXN_OK) {
2432
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2433
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2434
0
            ret = -1;
2435
0
            continue;
2436
0
        }
2437
14
        DCHECK_EQ(values.size(), batch_keys.size());
2438
14
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2439
14
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2440
14
                                 &batch_size);
2441
2442
283
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2443
269
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2444
269
            if (!values[idx].has_value()) {
2445
1
                continue;
2446
1
            }
2447
2448
268
            T rowset_meta_pb;
2449
268
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2450
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2451
0
                             << instance_id << " key=" << hex(key);
2452
0
                ret = -1;
2453
0
                continue;
2454
0
            }
2455
268
            if (config::enable_mark_delete_rowset_before_recycle &&
2456
268
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2457
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2458
0
                             << instance_id << " key=" << hex(key);
2459
0
                continue;
2460
0
            }
2461
268
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2462
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2463
1
                             << instance_id << " key=" << hex(key);
2464
1
                continue;
2465
1
            }
2466
267
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2467
267
        }
2468
14
    }
2469
13
    return ret;
2470
13
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2410
5
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2411
5
    int ret = 0;
2412
11
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2413
6
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2414
6
        std::vector<std::string> batch_keys;
2415
6
        batch_keys.reserve(limit - offset);
2416
267
        for (size_t idx = offset; idx < limit; ++idx) {
2417
261
            batch_keys.push_back(keys_to_recheck[idx].first);
2418
261
        }
2419
2420
6
        std::unique_ptr<Transaction> txn;
2421
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2422
6
        if (err != TxnErrorCode::TXN_OK) {
2423
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2424
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2425
0
            ret = -1;
2426
0
            continue;
2427
0
        }
2428
2429
6
        std::vector<std::optional<std::string>> values;
2430
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2431
6
        if (err != TxnErrorCode::TXN_OK) {
2432
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2433
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2434
0
            ret = -1;
2435
0
            continue;
2436
0
        }
2437
6
        DCHECK_EQ(values.size(), batch_keys.size());
2438
6
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2439
6
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2440
6
                                 &batch_size);
2441
2442
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2443
261
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2444
261
            if (!values[idx].has_value()) {
2445
0
                continue;
2446
0
            }
2447
2448
261
            T rowset_meta_pb;
2449
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2450
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2451
0
                             << instance_id << " key=" << hex(key);
2452
0
                ret = -1;
2453
0
                continue;
2454
0
            }
2455
261
            if (config::enable_mark_delete_rowset_before_recycle &&
2456
261
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2457
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2458
0
                             << instance_id << " key=" << hex(key);
2459
0
                continue;
2460
0
            }
2461
261
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2462
0
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2463
0
                             << instance_id << " key=" << hex(key);
2464
0
                continue;
2465
0
            }
2466
261
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2467
261
        }
2468
6
    }
2469
5
    return ret;
2470
5
}
2471
2472
template <typename T>
2473
int InstanceRecycler::batch_abort_txn_or_job_for_recycle(
2474
        const std::vector<std::string>& keys,
2475
20
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2476
20
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2477
20
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2478
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2479
0
        return -1;
2480
0
    }
2481
20
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2482
20
    int ret = 0;
2483
533
    for (const auto& abort_task : abort_tasks) {
2484
533
        int abort_ret = 0;
2485
533
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2486
526
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2487
526
        } else {
2488
7
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2489
7
                                                     abort_task.job_id);
2490
7
        }
2491
533
        if (abort_ret != 0) {
2492
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2493
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2494
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2495
3
            ret = abort_ret;
2496
3
            continue;
2497
3
        }
2498
530
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2499
530
    }
2500
20
    return ret;
2501
20
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2475
15
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2476
15
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2477
15
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2478
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2479
0
        return -1;
2480
0
    }
2481
15
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2482
15
    int ret = 0;
2483
272
    for (const auto& abort_task : abort_tasks) {
2484
272
        int abort_ret = 0;
2485
272
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2486
267
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2487
267
        } else {
2488
5
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2489
5
                                                     abort_task.job_id);
2490
5
        }
2491
272
        if (abort_ret != 0) {
2492
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2493
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2494
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2495
3
            ret = abort_ret;
2496
3
            continue;
2497
3
        }
2498
269
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2499
269
    }
2500
15
    return ret;
2501
15
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2475
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2476
5
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2477
5
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2478
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2479
0
        return -1;
2480
0
    }
2481
5
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2482
5
    int ret = 0;
2483
261
    for (const auto& abort_task : abort_tasks) {
2484
261
        int abort_ret = 0;
2485
261
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2486
259
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2487
259
        } else {
2488
2
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2489
2
                                                     abort_task.job_id);
2490
2
        }
2491
261
        if (abort_ret != 0) {
2492
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2493
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2494
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2495
0
            ret = abort_ret;
2496
0
            continue;
2497
0
        }
2498
261
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2499
261
    }
2500
5
    return ret;
2501
5
}
2502
2503
void InstanceRecycler::submit_recycle_prepare_rowsets_job(
2504
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_abort,
2505
15
        std::atomic_long* num_recycled) {
2506
15
    int ret = worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort),
2507
15
                                  num_recycled]() mutable {
2508
15
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2509
15
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2510
15
                                                                            keys_to_recheck);
2511
15
        if (abort_ret != 0) {
2512
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2513
2
                            "instance_id="
2514
2
                         << instance_id_;
2515
2
        }
2516
15
        if (keys_to_recheck.empty()) {
2517
2
            return;
2518
2
        }
2519
2520
13
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2521
13
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2522
13
                                                            keys_to_recheck, &rowsets_to_recycle);
2523
13
        if (recheck_ret != 0) {
2524
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2525
0
                         << instance_id_;
2526
0
        }
2527
267
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2528
267
            const auto& current_meta = current_rowset.rowset_meta();
2529
267
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2530
267
                                   current_meta.rowset_id_v2()) != 0) {
2531
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2532
1
                continue;
2533
1
            }
2534
266
            if (delete_versioned_delete_bitmap_kvs(current_meta.tablet_id(),
2535
266
                                                   current_meta.rowset_id_v2()) != 0) {
2536
0
                continue;
2537
0
            }
2538
266
            std::vector<std::string> keys {key};
2539
266
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2540
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2541
0
                continue;
2542
0
            }
2543
266
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2544
266
        }
2545
13
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEEN3$_0clEv
Line
Count
Source
2507
2
                                  num_recycled]() mutable {
2508
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2509
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2510
2
                                                                            keys_to_recheck);
2511
2
        if (abort_ret != 0) {
2512
0
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2513
0
                            "instance_id="
2514
0
                         << instance_id_;
2515
0
        }
2516
2
        if (keys_to_recheck.empty()) {
2517
0
            return;
2518
0
        }
2519
2520
2
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2521
2
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2522
2
                                                            keys_to_recheck, &rowsets_to_recycle);
2523
2
        if (recheck_ret != 0) {
2524
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2525
0
                         << instance_id_;
2526
0
        }
2527
2
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2528
2
            const auto& current_meta = current_rowset.rowset_meta();
2529
2
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2530
2
                                   current_meta.rowset_id_v2()) != 0) {
2531
0
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2532
0
                continue;
2533
0
            }
2534
2
            if (delete_versioned_delete_bitmap_kvs(current_meta.tablet_id(),
2535
2
                                                   current_meta.rowset_id_v2()) != 0) {
2536
0
                continue;
2537
0
            }
2538
2
            std::vector<std::string> keys {key};
2539
2
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2540
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2541
0
                continue;
2542
0
            }
2543
2
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2544
2
        }
2545
2
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEEN3$_0clEv
Line
Count
Source
2507
13
                                  num_recycled]() mutable {
2508
13
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2509
13
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2510
13
                                                                            keys_to_recheck);
2511
13
        if (abort_ret != 0) {
2512
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2513
2
                            "instance_id="
2514
2
                         << instance_id_;
2515
2
        }
2516
13
        if (keys_to_recheck.empty()) {
2517
2
            return;
2518
2
        }
2519
2520
11
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2521
11
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2522
11
                                                            keys_to_recheck, &rowsets_to_recycle);
2523
11
        if (recheck_ret != 0) {
2524
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2525
0
                         << instance_id_;
2526
0
        }
2527
265
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2528
265
            const auto& current_meta = current_rowset.rowset_meta();
2529
265
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2530
265
                                   current_meta.rowset_id_v2()) != 0) {
2531
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2532
1
                continue;
2533
1
            }
2534
264
            if (delete_versioned_delete_bitmap_kvs(current_meta.tablet_id(),
2535
264
                                                   current_meta.rowset_id_v2()) != 0) {
2536
0
                continue;
2537
0
            }
2538
264
            std::vector<std::string> keys {key};
2539
264
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2540
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2541
0
                continue;
2542
0
            }
2543
264
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2544
264
        }
2545
11
    });
2546
15
    if (ret != 0) {
2547
0
        LOG(WARNING) << "failed to submit recycle prepare rowset job, instance_id=" << instance_id_;
2548
0
    }
2549
15
}
2550
2551
void InstanceRecycler::submit_recycle_tmp_rowsets_job(SimpleThreadPool& worker_pool,
2552
                                                      std::vector<std::string> rowset_keys_to_abort,
2553
                                                      std::atomic_long* num_recycled,
2554
5
                                                      RecyclerMetricsContext* metrics_context) {
2555
5
    if (rowset_keys_to_abort.empty()) {
2556
0
        return;
2557
0
    }
2558
5
    worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort), num_recycled,
2559
5
                        metrics_context]() mutable {
2560
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2561
5
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2562
5
                rowset_keys_to_abort, abort_keys_to_recheck);
2563
5
        if (abort_ret != 0) {
2564
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2565
0
                            "instance_id="
2566
0
                         << instance_id_;
2567
0
        }
2568
2569
5
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2570
5
        std::vector<std::string> keys_to_delete;
2571
5
        std::vector<std::string> ref_count_keys_to_delete;
2572
5
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2573
5
        int recheck_ret = batch_recheck_rowsets_after_abort(
2574
5
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2575
5
        if (recheck_ret != 0) {
2576
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2577
0
                         << instance_id_;
2578
0
        }
2579
261
        for (auto& [key, rowset] : rowsets_to_recycle) {
2580
261
            keys_to_delete.push_back(key);
2581
261
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2582
261
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2583
261
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2584
261
        }
2585
2586
5
        if (keys_to_delete.empty()) {
2587
0
            return;
2588
0
        }
2589
5
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2590
5
                               *metrics_context) != 0) {
2591
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2592
0
            return;
2593
0
        }
2594
261
        for (const auto& [_, rowset] : rowsets_to_delete) {
2595
261
            if (delete_versioned_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) !=
2596
261
                0) {
2597
0
                return;
2598
0
            }
2599
261
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2600
0
                return;
2601
0
            }
2602
261
        }
2603
5
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2604
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2605
0
            return;
2606
0
        }
2607
5
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2608
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2609
0
                         << instance_id_;
2610
0
            return;
2611
0
        }
2612
5
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2613
5
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2559
3
                        metrics_context]() mutable {
2560
3
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2561
3
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2562
3
                rowset_keys_to_abort, abort_keys_to_recheck);
2563
3
        if (abort_ret != 0) {
2564
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2565
0
                            "instance_id="
2566
0
                         << instance_id_;
2567
0
        }
2568
2569
3
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2570
3
        std::vector<std::string> keys_to_delete;
2571
3
        std::vector<std::string> ref_count_keys_to_delete;
2572
3
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2573
3
        int recheck_ret = batch_recheck_rowsets_after_abort(
2574
3
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2575
3
        if (recheck_ret != 0) {
2576
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2577
0
                         << instance_id_;
2578
0
        }
2579
3
        for (auto& [key, rowset] : rowsets_to_recycle) {
2580
3
            keys_to_delete.push_back(key);
2581
3
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2582
3
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2583
3
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2584
3
        }
2585
2586
3
        if (keys_to_delete.empty()) {
2587
0
            return;
2588
0
        }
2589
3
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2590
3
                               *metrics_context) != 0) {
2591
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2592
0
            return;
2593
0
        }
2594
3
        for (const auto& [_, rowset] : rowsets_to_delete) {
2595
3
            if (delete_versioned_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) !=
2596
3
                0) {
2597
0
                return;
2598
0
            }
2599
3
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2600
0
                return;
2601
0
            }
2602
3
        }
2603
3
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2604
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2605
0
            return;
2606
0
        }
2607
3
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2608
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2609
0
                         << instance_id_;
2610
0
            return;
2611
0
        }
2612
3
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2613
3
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2559
2
                        metrics_context]() mutable {
2560
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2561
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2562
2
                rowset_keys_to_abort, abort_keys_to_recheck);
2563
2
        if (abort_ret != 0) {
2564
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2565
0
                            "instance_id="
2566
0
                         << instance_id_;
2567
0
        }
2568
2569
2
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2570
2
        std::vector<std::string> keys_to_delete;
2571
2
        std::vector<std::string> ref_count_keys_to_delete;
2572
2
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2573
2
        int recheck_ret = batch_recheck_rowsets_after_abort(
2574
2
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2575
2
        if (recheck_ret != 0) {
2576
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2577
0
                         << instance_id_;
2578
0
        }
2579
258
        for (auto& [key, rowset] : rowsets_to_recycle) {
2580
258
            keys_to_delete.push_back(key);
2581
258
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2582
258
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2583
258
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2584
258
        }
2585
2586
2
        if (keys_to_delete.empty()) {
2587
0
            return;
2588
0
        }
2589
2
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2590
2
                               *metrics_context) != 0) {
2591
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2592
0
            return;
2593
0
        }
2594
258
        for (const auto& [_, rowset] : rowsets_to_delete) {
2595
258
            if (delete_versioned_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) !=
2596
258
                0) {
2597
0
                return;
2598
0
            }
2599
258
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2600
0
                return;
2601
0
            }
2602
258
        }
2603
2
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2604
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2605
0
            return;
2606
0
        }
2607
2
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2608
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2609
0
                         << instance_id_;
2610
0
            return;
2611
0
        }
2612
2
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2613
2
    });
2614
5
}
2615
2616
1
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
2617
1
    const std::string task_name = "recycle_ref_rowsets";
2618
1
    *has_unrecycled_rowsets = false;
2619
2620
1
    std::string data_rowset_ref_count_key_start =
2621
1
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
2622
1
    std::string data_rowset_ref_count_key_end =
2623
1
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
2624
2625
1
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
2626
2627
1
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2628
1
    register_recycle_task(task_name, start_time);
2629
2630
1
    DORIS_CLOUD_DEFER {
2631
1
        unregister_recycle_task(task_name);
2632
1
        int64_t cost =
2633
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2634
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2635
1
                .tag("instance_id", instance_id_);
2636
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Line
Count
Source
2630
1
    DORIS_CLOUD_DEFER {
2631
1
        unregister_recycle_task(task_name);
2632
1
        int64_t cost =
2633
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2634
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2635
1
                .tag("instance_id", instance_id_);
2636
1
    };
2637
2638
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
2639
1
    std::set<int64_t> tablets_with_refs;
2640
1
    int64_t num_scanned = 0;
2641
2642
1
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
2643
0
        ++num_scanned;
2644
0
        int64_t tablet_id;
2645
0
        std::string rowset_id;
2646
0
        std::string_view key(k);
2647
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
2648
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
2649
0
            return 0; // Continue scanning
2650
0
        }
2651
2652
0
        tablets_with_refs.insert(tablet_id);
2653
0
        return 0;
2654
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
2655
2656
1
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
2657
1
                         std::move(scan_func)) != 0) {
2658
0
        LOG_WARNING("failed to scan data rowset ref count keys");
2659
0
        return -1;
2660
0
    }
2661
2662
1
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
2663
1
             tablets_with_refs.size(), num_scanned)
2664
1
            .tag("instance_id", instance_id_);
2665
2666
    // Phase 2: Recycle each tablet
2667
1
    int64_t num_recycled_tablets = 0;
2668
1
    for (int64_t tablet_id : tablets_with_refs) {
2669
0
        if (stopped()) {
2670
0
            LOG_INFO("recycler stopped, skip remaining tablets")
2671
0
                    .tag("instance_id", instance_id_)
2672
0
                    .tag("tablets_processed", num_recycled_tablets)
2673
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
2674
0
            break;
2675
0
        }
2676
2677
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
2678
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
2679
0
            LOG_WARNING("failed to recycle tablet")
2680
0
                    .tag("instance_id", instance_id_)
2681
0
                    .tag("tablet_id", tablet_id);
2682
0
            return -1;
2683
0
        }
2684
0
        ++num_recycled_tablets;
2685
0
    }
2686
2687
1
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
2688
1
            .tag("instance_id", instance_id_)
2689
1
            .tag("total_tablets", tablets_with_refs.size());
2690
2691
    // Phase 3: Scan again to check if any ref count keys still exist
2692
1
    std::unique_ptr<Transaction> txn;
2693
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2694
1
    if (err != TxnErrorCode::TXN_OK) {
2695
0
        LOG_WARNING("failed to create txn for final check")
2696
0
                .tag("instance_id", instance_id_)
2697
0
                .tag("err", err);
2698
0
        return -1;
2699
0
    }
2700
2701
1
    std::unique_ptr<RangeGetIterator> iter;
2702
1
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2703
1
    if (err != TxnErrorCode::TXN_OK) {
2704
0
        LOG_WARNING("failed to create range iterator for final check")
2705
0
                .tag("instance_id", instance_id_)
2706
0
                .tag("err", err);
2707
0
        return -1;
2708
0
    }
2709
2710
1
    *has_unrecycled_rowsets = iter->has_next();
2711
1
    if (*has_unrecycled_rowsets) {
2712
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2713
0
                .tag("instance_id", instance_id_);
2714
0
    }
2715
2716
1
    return 0;
2717
1
}
2718
2719
int InstanceRecycler::recycle_table_stream_offset_prefix(std::string prefix,
2720
6
                                                         RecyclerMetricsContext* metrics_context) {
2721
6
    std::string end = prefix;
2722
6
    end.push_back('\xff');
2723
6
    std::vector<std::string_view> keys;
2724
8
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2725
8
        keys.push_back(key);
2726
8
        return 0;
2727
8
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_1clESt17basic_string_viewIcS5_ESC_
Line
Count
Source
2724
2
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2725
2
        keys.push_back(key);
2726
2
        return 0;
2727
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_1clESt17basic_string_viewIcS5_ESC_
Line
Count
Source
2724
6
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2725
6
        keys.push_back(key);
2726
6
        return 0;
2727
6
    };
2728
6
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2729
4
        if (keys.empty()) {
2730
0
            return 0;
2731
0
        }
2732
4
        DORIS_CLOUD_DEFER {
2733
4
            keys.clear();
2734
4
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlvE_clEv
Line
Count
Source
2732
2
        DORIS_CLOUD_DEFER {
2733
2
            keys.clear();
2734
2
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlvE_clEv
Line
Count
Source
2732
2
        DORIS_CLOUD_DEFER {
2733
2
            keys.clear();
2734
2
        };
2735
4
        const size_t num_keys = keys.size();
2736
4
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2737
0
            LOG_WARNING("failed to delete table stream offsets")
2738
0
                    .tag("instance_id", instance_id_)
2739
0
                    .tag("num_keys", num_keys);
2740
0
            return -1;
2741
0
        }
2742
4
        metrics_context->total_recycled_num += num_keys;
2743
4
        metrics_context->report();
2744
4
        return 0;
2745
4
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2728
2
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2729
2
        if (keys.empty()) {
2730
0
            return 0;
2731
0
        }
2732
2
        DORIS_CLOUD_DEFER {
2733
2
            keys.clear();
2734
2
        };
2735
2
        const size_t num_keys = keys.size();
2736
2
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2737
0
            LOG_WARNING("failed to delete table stream offsets")
2738
0
                    .tag("instance_id", instance_id_)
2739
0
                    .tag("num_keys", num_keys);
2740
0
            return -1;
2741
0
        }
2742
2
        metrics_context->total_recycled_num += num_keys;
2743
2
        metrics_context->report();
2744
2
        return 0;
2745
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2728
2
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2729
2
        if (keys.empty()) {
2730
0
            return 0;
2731
0
        }
2732
2
        DORIS_CLOUD_DEFER {
2733
2
            keys.clear();
2734
2
        };
2735
2
        const size_t num_keys = keys.size();
2736
2
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2737
0
            LOG_WARNING("failed to delete table stream offsets")
2738
0
                    .tag("instance_id", instance_id_)
2739
0
                    .tag("num_keys", num_keys);
2740
0
            return -1;
2741
0
        }
2742
2
        metrics_context->total_recycled_num += num_keys;
2743
2
        metrics_context->report();
2744
2
        return 0;
2745
2
    };
2746
6
    return scan_and_recycle(std::move(prefix), end, std::move(collect_key), std::move(remove_keys));
2747
6
}
2748
2749
int InstanceRecycler::finalize_recycle_stream(int64_t stream_id,
2750
                                              const RecycleIndexPB& recycle_index,
2751
3
                                              std::string_view recycle_key) {
2752
3
    std::unique_ptr<Transaction> txn;
2753
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2754
3
    if (err != TxnErrorCode::TXN_OK) {
2755
0
        LOG_WARNING("failed to create transaction for final table stream cleanup")
2756
0
                .tag("instance_id", instance_id_)
2757
0
                .tag("stream_id", stream_id)
2758
0
                .tag("err", err);
2759
0
        return -1;
2760
0
    }
2761
2762
3
    std::string current_recycle_value;
2763
3
    err = txn->get(recycle_key, &current_recycle_value);
2764
3
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2765
0
        return 0;
2766
0
    }
2767
3
    if (err != TxnErrorCode::TXN_OK) {
2768
0
        LOG_WARNING("failed to read table stream recycle index")
2769
0
                .tag("instance_id", instance_id_)
2770
0
                .tag("stream_id", stream_id)
2771
0
                .tag("err", err);
2772
0
        return -1;
2773
0
    }
2774
3
    RecycleIndexPB current_recycle_index;
2775
3
    if (!current_recycle_index.ParseFromString(current_recycle_value) ||
2776
3
        current_recycle_index.state() != RecycleIndexPB::RECYCLING ||
2777
3
        current_recycle_index.object_type() != IndexObjectTypePB::TABLE_STREAM ||
2778
3
        current_recycle_index.db_id() != recycle_index.db_id() ||
2779
3
        current_recycle_index.table_id() != recycle_index.table_id() ||
2780
3
        current_recycle_index.stream_db_id() != recycle_index.stream_db_id()) {
2781
0
        LOG_WARNING("table stream recycle index changed during recycling")
2782
0
                .tag("instance_id", instance_id_)
2783
0
                .tag("stream_id", stream_id);
2784
0
        return -1;
2785
0
    }
2786
2787
3
    txn->remove(recycle_key);
2788
3
    err = txn->commit();
2789
3
    if (err != TxnErrorCode::TXN_OK) {
2790
0
        LOG_WARNING("failed to commit final table stream cleanup")
2791
0
                .tag("instance_id", instance_id_)
2792
0
                .tag("stream_id", stream_id)
2793
0
                .tag("err", err);
2794
0
        return -1;
2795
0
    }
2796
3
    return 0;
2797
3
}
2798
2799
int InstanceRecycler::recycle_stream(int64_t stream_id, const RecycleIndexPB& recycle_index,
2800
3
                                     std::string_view recycle_key) {
2801
3
    if (!recycle_index.has_db_id() || !recycle_index.has_stream_db_id()) {
2802
0
        LOG_WARNING("table stream recycle index is missing binding")
2803
0
                .tag("instance_id", instance_id_)
2804
0
                .tag("stream_id", stream_id);
2805
0
        return -1;
2806
0
    }
2807
2808
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stream");
2809
3
    DORIS_CLOUD_DEFER {
2810
3
        metrics_context.finish_report();
2811
3
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_streamElRKNS0_14RecycleIndexPBESt17basic_string_viewIcSt11char_traitsIcEEENK3$_0clEv
Line
Count
Source
2809
2
    DORIS_CLOUD_DEFER {
2810
2
        metrics_context.finish_report();
2811
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_streamElRKNS0_14RecycleIndexPBESt17basic_string_viewIcSt11char_traitsIcEEENK3$_0clEv
Line
Count
Source
2809
1
    DORIS_CLOUD_DEFER {
2810
1
        metrics_context.finish_report();
2811
1
    };
2812
3
    const std::string latest_offset_prefix = table_stream_offset_key_prefix(
2813
3
            instance_id_, recycle_index.db_id(), recycle_index.table_id(),
2814
3
            recycle_index.stream_db_id(), stream_id);
2815
3
    if (recycle_table_stream_offset_prefix(latest_offset_prefix, &metrics_context) != 0) {
2816
0
        return -1;
2817
0
    }
2818
3
    const std::string versioned_offset_prefix = versioned::table_stream_offset_key_prefix(
2819
3
            instance_id_, recycle_index.db_id(), recycle_index.table_id(),
2820
3
            recycle_index.stream_db_id(), stream_id);
2821
3
    if (recycle_table_stream_offset_prefix(versioned_offset_prefix, &metrics_context) != 0 ||
2822
3
        stopped()) {
2823
0
        return -1;
2824
0
    }
2825
3
    return finalize_recycle_stream(stream_id, recycle_index, recycle_key);
2826
3
}
2827
2828
int InstanceRecycler::recycle_partition_table_stream_offsets(
2829
        int64_t db_id, int64_t table_id, int64_t partition_id,
2830
10
        const google::protobuf::RepeatedPtrField<TableStreamIdentityPB>& table_streams) {
2831
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stream_partition_offsets");
2832
10
    DORIS_CLOUD_DEFER {
2833
10
        metrics_context.finish_report();
2834
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler38recycle_partition_table_stream_offsetsElllRKN6google8protobuf16RepeatedPtrFieldINS0_21TableStreamIdentityPBEEEENK3$_0clEv
Line
Count
Source
2832
1
    DORIS_CLOUD_DEFER {
2833
1
        metrics_context.finish_report();
2834
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler38recycle_partition_table_stream_offsetsElllRKN6google8protobuf16RepeatedPtrFieldINS0_21TableStreamIdentityPBEEEENK3$_0clEv
Line
Count
Source
2832
9
    DORIS_CLOUD_DEFER {
2833
9
        metrics_context.finish_report();
2834
9
    };
2835
10
    const size_t batch_size = std::max(1, config::recycler_max_tasks_per_batch);
2836
12
    for (size_t begin_index = 0; begin_index < table_streams.size(); begin_index += batch_size) {
2837
2
        const size_t end_index =
2838
2
                std::min(static_cast<size_t>(table_streams.size()), begin_index + batch_size);
2839
2
        std::unique_ptr<Transaction> txn;
2840
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2841
2
        if (err != TxnErrorCode::TXN_OK) {
2842
0
            LOG_WARNING("failed to create transaction for partition stream offset cleanup")
2843
0
                    .tag("instance_id", instance_id_)
2844
0
                    .tag("partition_id", partition_id)
2845
0
                    .tag("err", err);
2846
0
            return -1;
2847
0
        }
2848
4
        for (size_t i = begin_index; i < end_index; ++i) {
2849
2
            const TableStreamIdentityPB& stream = table_streams.Get(i);
2850
2
            if (stream.base_db_id() != db_id || stream.base_table_id() != table_id ||
2851
2
                stream.stream_db_id() <= 0 || stream.stream_id() <= 0) {
2852
0
                LOG_WARNING("invalid table stream binding in recycle partition")
2853
0
                        .tag("instance_id", instance_id_)
2854
0
                        .tag("partition_id", partition_id)
2855
0
                        .tag("stream_id", stream.stream_id());
2856
0
                return -1;
2857
0
            }
2858
2
            txn->remove(table_stream_offset_key({instance_id_, stream.base_db_id(),
2859
2
                                                 stream.base_table_id(), stream.stream_db_id(),
2860
2
                                                 stream.stream_id(), partition_id}));
2861
2
            versioned_remove_all(
2862
2
                    txn.get(), versioned::table_stream_offset_key(
2863
2
                                       {instance_id_, stream.base_db_id(), stream.base_table_id(),
2864
2
                                        stream.stream_db_id(), stream.stream_id(), partition_id}));
2865
2
        }
2866
2
        err = txn->commit();
2867
2
        if (err != TxnErrorCode::TXN_OK) {
2868
0
            LOG_WARNING("failed to commit partition stream offset cleanup")
2869
0
                    .tag("instance_id", instance_id_)
2870
0
                    .tag("partition_id", partition_id)
2871
0
                    .tag("err", err);
2872
0
            return -1;
2873
0
        }
2874
2
        metrics_context.total_recycled_num += end_index - begin_index;
2875
2
        metrics_context.report();
2876
2
    }
2877
10
    return 0;
2878
10
}
2879
2880
19
int InstanceRecycler::recycle_indexes() {
2881
19
    const std::string task_name = "recycle_indexes";
2882
19
    int64_t num_scanned = 0;
2883
19
    int64_t num_expired = 0;
2884
19
    int64_t num_recycled = 0;
2885
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2886
2887
19
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2888
19
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2889
19
    std::string index_key0;
2890
19
    std::string index_key1;
2891
19
    recycle_index_key(index_key_info0, &index_key0);
2892
19
    recycle_index_key(index_key_info1, &index_key1);
2893
2894
19
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2895
2896
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2897
19
    register_recycle_task(task_name, start_time);
2898
2899
19
    DORIS_CLOUD_DEFER {
2900
19
        unregister_recycle_task(task_name);
2901
19
        int64_t cost =
2902
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2903
19
        metrics_context.finish_report();
2904
19
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2905
19
                .tag("instance_id", instance_id_)
2906
19
                .tag("num_scanned", num_scanned)
2907
19
                .tag("num_expired", num_expired)
2908
19
                .tag("num_recycled", num_recycled);
2909
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2899
3
    DORIS_CLOUD_DEFER {
2900
3
        unregister_recycle_task(task_name);
2901
3
        int64_t cost =
2902
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2903
3
        metrics_context.finish_report();
2904
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2905
3
                .tag("instance_id", instance_id_)
2906
3
                .tag("num_scanned", num_scanned)
2907
3
                .tag("num_expired", num_expired)
2908
3
                .tag("num_recycled", num_recycled);
2909
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2899
16
    DORIS_CLOUD_DEFER {
2900
16
        unregister_recycle_task(task_name);
2901
16
        int64_t cost =
2902
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2903
16
        metrics_context.finish_report();
2904
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2905
16
                .tag("instance_id", instance_id_)
2906
16
                .tag("num_scanned", num_scanned)
2907
16
                .tag("num_expired", num_expired)
2908
16
                .tag("num_recycled", num_recycled);
2909
16
    };
2910
2911
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2912
2913
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2914
19
    std::vector<std::string_view> index_keys;
2915
19
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2916
13
        ++num_scanned;
2917
13
        RecycleIndexPB index_pb;
2918
13
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2919
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2920
0
            return -1;
2921
0
        }
2922
13
        int64_t current_time = ::time(nullptr);
2923
13
        if (current_time <
2924
13
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2925
0
            return 0;
2926
0
        }
2927
13
        ++num_expired;
2928
        // decode index_id
2929
13
        auto k1 = k;
2930
13
        k1.remove_prefix(1);
2931
13
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2932
13
        decode_key(&k1, &out);
2933
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2934
13
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2935
13
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2936
13
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2937
13
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2938
        // Change state to RECYCLING
2939
13
        std::unique_ptr<Transaction> txn;
2940
13
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2941
13
        if (err != TxnErrorCode::TXN_OK) {
2942
0
            LOG_WARNING("failed to create txn").tag("err", err);
2943
0
            return -1;
2944
0
        }
2945
13
        std::string val;
2946
13
        err = txn->get(k, &val);
2947
13
        if (err ==
2948
13
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2949
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2950
0
            return 0;
2951
0
        }
2952
13
        if (err != TxnErrorCode::TXN_OK) {
2953
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2954
0
            return -1;
2955
0
        }
2956
13
        index_pb.Clear();
2957
13
        if (!index_pb.ParseFromString(val)) {
2958
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2959
0
            return -1;
2960
0
        }
2961
13
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2962
12
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2963
12
            txn->put(k, index_pb.SerializeAsString());
2964
12
            err = txn->commit();
2965
12
            if (err != TxnErrorCode::TXN_OK) {
2966
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2967
0
                return -1;
2968
0
            }
2969
12
        }
2970
13
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
2971
3
            if (recycle_stream(index_id, index_pb, k) != 0) {
2972
0
                LOG_WARNING("failed to recycle table stream")
2973
0
                        .tag("instance_id", instance_id_)
2974
0
                        .tag("stream_id", index_id);
2975
0
                return -1;
2976
0
            }
2977
3
            metrics_context.total_recycled_num = ++num_recycled;
2978
3
            metrics_context.report();
2979
3
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2980
3
            return 0;
2981
3
        }
2982
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2983
1
            LOG_WARNING("failed to recycle tablets under index")
2984
1
                    .tag("table_id", index_pb.table_id())
2985
1
                    .tag("instance_id", instance_id_)
2986
1
                    .tag("index_id", index_id);
2987
1
            return -1;
2988
1
        }
2989
2990
9
        if (index_pb.has_db_id()) {
2991
            // Recycle the versioned keys
2992
3
            std::unique_ptr<Transaction> txn;
2993
3
            err = txn_kv_->create_txn(&txn);
2994
3
            if (err != TxnErrorCode::TXN_OK) {
2995
0
                LOG_WARNING("failed to create txn").tag("err", err);
2996
0
                return -1;
2997
0
            }
2998
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2999
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
3000
3
            std::string index_inverted_key = versioned::index_inverted_key(
3001
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
3002
3
            versioned_remove_all(txn.get(), meta_key);
3003
3
            txn->remove(index_key);
3004
3
            txn->remove(index_inverted_key);
3005
3
            err = txn->commit();
3006
3
            if (err != TxnErrorCode::TXN_OK) {
3007
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3008
0
                return -1;
3009
0
            }
3010
3
        }
3011
3012
9
        metrics_context.total_recycled_num = ++num_recycled;
3013
9
        metrics_context.report();
3014
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3015
9
        index_keys.push_back(k);
3016
9
        return 0;
3017
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2915
4
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2916
4
        ++num_scanned;
2917
4
        RecycleIndexPB index_pb;
2918
4
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2919
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2920
0
            return -1;
2921
0
        }
2922
4
        int64_t current_time = ::time(nullptr);
2923
4
        if (current_time <
2924
4
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2925
0
            return 0;
2926
0
        }
2927
4
        ++num_expired;
2928
        // decode index_id
2929
4
        auto k1 = k;
2930
4
        k1.remove_prefix(1);
2931
4
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2932
4
        decode_key(&k1, &out);
2933
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2934
4
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2935
4
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2936
4
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2937
4
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2938
        // Change state to RECYCLING
2939
4
        std::unique_ptr<Transaction> txn;
2940
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2941
4
        if (err != TxnErrorCode::TXN_OK) {
2942
0
            LOG_WARNING("failed to create txn").tag("err", err);
2943
0
            return -1;
2944
0
        }
2945
4
        std::string val;
2946
4
        err = txn->get(k, &val);
2947
4
        if (err ==
2948
4
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2949
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2950
0
            return 0;
2951
0
        }
2952
4
        if (err != TxnErrorCode::TXN_OK) {
2953
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2954
0
            return -1;
2955
0
        }
2956
4
        index_pb.Clear();
2957
4
        if (!index_pb.ParseFromString(val)) {
2958
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2959
0
            return -1;
2960
0
        }
2961
4
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2962
3
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2963
3
            txn->put(k, index_pb.SerializeAsString());
2964
3
            err = txn->commit();
2965
3
            if (err != TxnErrorCode::TXN_OK) {
2966
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2967
0
                return -1;
2968
0
            }
2969
3
        }
2970
4
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
2971
2
            if (recycle_stream(index_id, index_pb, k) != 0) {
2972
0
                LOG_WARNING("failed to recycle table stream")
2973
0
                        .tag("instance_id", instance_id_)
2974
0
                        .tag("stream_id", index_id);
2975
0
                return -1;
2976
0
            }
2977
2
            metrics_context.total_recycled_num = ++num_recycled;
2978
2
            metrics_context.report();
2979
2
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2980
2
            return 0;
2981
2
        }
2982
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2983
1
            LOG_WARNING("failed to recycle tablets under index")
2984
1
                    .tag("table_id", index_pb.table_id())
2985
1
                    .tag("instance_id", instance_id_)
2986
1
                    .tag("index_id", index_id);
2987
1
            return -1;
2988
1
        }
2989
2990
1
        if (index_pb.has_db_id()) {
2991
            // Recycle the versioned keys
2992
1
            std::unique_ptr<Transaction> txn;
2993
1
            err = txn_kv_->create_txn(&txn);
2994
1
            if (err != TxnErrorCode::TXN_OK) {
2995
0
                LOG_WARNING("failed to create txn").tag("err", err);
2996
0
                return -1;
2997
0
            }
2998
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2999
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
3000
1
            std::string index_inverted_key = versioned::index_inverted_key(
3001
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
3002
1
            versioned_remove_all(txn.get(), meta_key);
3003
1
            txn->remove(index_key);
3004
1
            txn->remove(index_inverted_key);
3005
1
            err = txn->commit();
3006
1
            if (err != TxnErrorCode::TXN_OK) {
3007
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3008
0
                return -1;
3009
0
            }
3010
1
        }
3011
3012
1
        metrics_context.total_recycled_num = ++num_recycled;
3013
1
        metrics_context.report();
3014
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3015
1
        index_keys.push_back(k);
3016
1
        return 0;
3017
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2915
9
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2916
9
        ++num_scanned;
2917
9
        RecycleIndexPB index_pb;
2918
9
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2919
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2920
0
            return -1;
2921
0
        }
2922
9
        int64_t current_time = ::time(nullptr);
2923
9
        if (current_time <
2924
9
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2925
0
            return 0;
2926
0
        }
2927
9
        ++num_expired;
2928
        // decode index_id
2929
9
        auto k1 = k;
2930
9
        k1.remove_prefix(1);
2931
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2932
9
        decode_key(&k1, &out);
2933
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2934
9
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2935
9
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2936
9
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2937
9
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2938
        // Change state to RECYCLING
2939
9
        std::unique_ptr<Transaction> txn;
2940
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2941
9
        if (err != TxnErrorCode::TXN_OK) {
2942
0
            LOG_WARNING("failed to create txn").tag("err", err);
2943
0
            return -1;
2944
0
        }
2945
9
        std::string val;
2946
9
        err = txn->get(k, &val);
2947
9
        if (err ==
2948
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2949
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2950
0
            return 0;
2951
0
        }
2952
9
        if (err != TxnErrorCode::TXN_OK) {
2953
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2954
0
            return -1;
2955
0
        }
2956
9
        index_pb.Clear();
2957
9
        if (!index_pb.ParseFromString(val)) {
2958
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2959
0
            return -1;
2960
0
        }
2961
9
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2962
9
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2963
9
            txn->put(k, index_pb.SerializeAsString());
2964
9
            err = txn->commit();
2965
9
            if (err != TxnErrorCode::TXN_OK) {
2966
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2967
0
                return -1;
2968
0
            }
2969
9
        }
2970
9
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
2971
1
            if (recycle_stream(index_id, index_pb, k) != 0) {
2972
0
                LOG_WARNING("failed to recycle table stream")
2973
0
                        .tag("instance_id", instance_id_)
2974
0
                        .tag("stream_id", index_id);
2975
0
                return -1;
2976
0
            }
2977
1
            metrics_context.total_recycled_num = ++num_recycled;
2978
1
            metrics_context.report();
2979
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2980
1
            return 0;
2981
1
        }
2982
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2983
0
            LOG_WARNING("failed to recycle tablets under index")
2984
0
                    .tag("table_id", index_pb.table_id())
2985
0
                    .tag("instance_id", instance_id_)
2986
0
                    .tag("index_id", index_id);
2987
0
            return -1;
2988
0
        }
2989
2990
8
        if (index_pb.has_db_id()) {
2991
            // Recycle the versioned keys
2992
2
            std::unique_ptr<Transaction> txn;
2993
2
            err = txn_kv_->create_txn(&txn);
2994
2
            if (err != TxnErrorCode::TXN_OK) {
2995
0
                LOG_WARNING("failed to create txn").tag("err", err);
2996
0
                return -1;
2997
0
            }
2998
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2999
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
3000
2
            std::string index_inverted_key = versioned::index_inverted_key(
3001
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
3002
2
            versioned_remove_all(txn.get(), meta_key);
3003
2
            txn->remove(index_key);
3004
2
            txn->remove(index_inverted_key);
3005
2
            err = txn->commit();
3006
2
            if (err != TxnErrorCode::TXN_OK) {
3007
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3008
0
                return -1;
3009
0
            }
3010
2
        }
3011
3012
8
        metrics_context.total_recycled_num = ++num_recycled;
3013
8
        metrics_context.report();
3014
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3015
8
        index_keys.push_back(k);
3016
8
        return 0;
3017
8
    };
3018
3019
19
    auto loop_done = [&index_keys, this]() -> int {
3020
8
        if (index_keys.empty()) return 0;
3021
5
        DORIS_CLOUD_DEFER {
3022
5
            index_keys.clear();
3023
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3021
1
        DORIS_CLOUD_DEFER {
3022
1
            index_keys.clear();
3023
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3021
4
        DORIS_CLOUD_DEFER {
3022
4
            index_keys.clear();
3023
4
        };
3024
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
3025
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
3026
0
            return -1;
3027
0
        }
3028
5
        return 0;
3029
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
3019
3
    auto loop_done = [&index_keys, this]() -> int {
3020
3
        if (index_keys.empty()) return 0;
3021
1
        DORIS_CLOUD_DEFER {
3022
1
            index_keys.clear();
3023
1
        };
3024
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
3025
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
3026
0
            return -1;
3027
0
        }
3028
1
        return 0;
3029
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
3019
5
    auto loop_done = [&index_keys, this]() -> int {
3020
5
        if (index_keys.empty()) return 0;
3021
4
        DORIS_CLOUD_DEFER {
3022
4
            index_keys.clear();
3023
4
        };
3024
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
3025
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
3026
0
            return -1;
3027
0
        }
3028
4
        return 0;
3029
4
    };
3030
3031
19
    if (config::enable_recycler_stats_metrics) {
3032
0
        scan_and_statistics_indexes();
3033
0
    }
3034
    // recycle_func and loop_done for scan and recycle
3035
19
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
3036
19
}
3037
3038
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
3039
8.25k
                             int64_t tablet_id) {
3040
8.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
3041
3042
8.25k
    std::unique_ptr<Transaction> txn;
3043
8.25k
    TxnErrorCode err = txn_kv->create_txn(&txn);
3044
8.25k
    if (err != TxnErrorCode::TXN_OK) {
3045
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
3046
0
                     << " tablet_id=" << tablet_id << " err=" << err;
3047
0
        return false;
3048
0
    }
3049
3050
8.25k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
3051
8.25k
    std::string tablet_idx_val;
3052
8.25k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
3053
8.25k
    if (TxnErrorCode::TXN_OK != err) {
3054
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
3055
0
                     << " tablet_id=" << tablet_id << " err=" << err
3056
0
                     << " key=" << hex(tablet_idx_key);
3057
0
        return false;
3058
0
    }
3059
3060
8.25k
    TabletIndexPB tablet_idx_pb;
3061
8.25k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
3062
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
3063
0
                     << " tablet_id=" << tablet_id;
3064
0
        return false;
3065
0
    }
3066
3067
8.25k
    if (!tablet_idx_pb.has_db_id()) {
3068
        // In the previous version, the db_id was not set in the index_pb.
3069
        // If updating to the version which enable txn lazy commit, the db_id will be set.
3070
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
3071
0
                  << " instance_id=" << instance_id
3072
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
3073
0
        return true;
3074
0
    }
3075
3076
8.25k
    std::string ver_val;
3077
8.25k
    std::string ver_key =
3078
8.25k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
3079
8.25k
                                   tablet_idx_pb.partition_id()});
3080
8.25k
    err = txn->get(ver_key, &ver_val);
3081
3082
8.25k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
3083
214
        LOG(INFO) << ""
3084
214
                     "partition version not found, instance_id="
3085
214
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
3086
214
                  << " table_id=" << tablet_idx_pb.table_id()
3087
214
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
3088
214
                  << " key=" << hex(ver_key);
3089
214
        return true;
3090
214
    }
3091
3092
8.03k
    if (TxnErrorCode::TXN_OK != err) {
3093
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
3094
0
                     << " db_id=" << tablet_idx_pb.db_id()
3095
0
                     << " table_id=" << tablet_idx_pb.table_id()
3096
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
3097
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
3098
0
        return false;
3099
0
    }
3100
3101
8.03k
    VersionPB version_pb;
3102
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
3103
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
3104
0
                     << " db_id=" << tablet_idx_pb.db_id()
3105
0
                     << " table_id=" << tablet_idx_pb.table_id()
3106
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
3107
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
3108
0
        return false;
3109
0
    }
3110
3111
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
3112
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
3113
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
3114
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
3115
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
3116
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
3117
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
3118
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
3119
4.00k
                     << " key=" << hex(ver_key);
3120
4.00k
        return false;
3121
4.00k
    }
3122
4.03k
    return true;
3123
8.03k
}
3124
3125
17
int InstanceRecycler::recycle_partitions() {
3126
17
    const std::string task_name = "recycle_partitions";
3127
17
    int64_t num_scanned = 0;
3128
17
    int64_t num_expired = 0;
3129
17
    int64_t num_recycled = 0;
3130
17
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
3131
3132
17
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
3133
17
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
3134
17
    std::string part_key0;
3135
17
    std::string part_key1;
3136
17
    recycle_partition_key(part_key_info0, &part_key0);
3137
17
    recycle_partition_key(part_key_info1, &part_key1);
3138
3139
17
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
3140
3141
17
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
3142
17
    register_recycle_task(task_name, start_time);
3143
3144
17
    DORIS_CLOUD_DEFER {
3145
17
        unregister_recycle_task(task_name);
3146
17
        int64_t cost =
3147
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3148
17
        metrics_context.finish_report();
3149
17
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3150
17
                .tag("instance_id", instance_id_)
3151
17
                .tag("num_scanned", num_scanned)
3152
17
                .tag("num_expired", num_expired)
3153
17
                .tag("num_recycled", num_recycled);
3154
17
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
3144
2
    DORIS_CLOUD_DEFER {
3145
2
        unregister_recycle_task(task_name);
3146
2
        int64_t cost =
3147
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3148
2
        metrics_context.finish_report();
3149
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3150
2
                .tag("instance_id", instance_id_)
3151
2
                .tag("num_scanned", num_scanned)
3152
2
                .tag("num_expired", num_expired)
3153
2
                .tag("num_recycled", num_recycled);
3154
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
3144
15
    DORIS_CLOUD_DEFER {
3145
15
        unregister_recycle_task(task_name);
3146
15
        int64_t cost =
3147
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3148
15
        metrics_context.finish_report();
3149
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3150
15
                .tag("instance_id", instance_id_)
3151
15
                .tag("num_scanned", num_scanned)
3152
15
                .tag("num_expired", num_expired)
3153
15
                .tag("num_recycled", num_recycled);
3154
15
    };
3155
3156
17
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
3157
3158
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
3159
17
    std::vector<std::string_view> partition_keys;
3160
17
    std::vector<std::string> partition_version_keys;
3161
17
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3162
11
        ++num_scanned;
3163
11
        RecyclePartitionPB part_pb;
3164
11
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3165
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3166
0
            return -1;
3167
0
        }
3168
11
        int64_t current_time = ::time(nullptr);
3169
11
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3170
11
                                                            &earlest_ts)) { // not expired
3171
0
            return 0;
3172
0
        }
3173
11
        ++num_expired;
3174
        // decode partition_id
3175
11
        auto k1 = k;
3176
11
        k1.remove_prefix(1);
3177
11
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3178
11
        decode_key(&k1, &out);
3179
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3180
11
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3181
11
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3182
11
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3183
11
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3184
        // Change state to RECYCLING
3185
11
        std::unique_ptr<Transaction> txn;
3186
11
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3187
11
        if (err != TxnErrorCode::TXN_OK) {
3188
0
            LOG_WARNING("failed to create txn").tag("err", err);
3189
0
            return -1;
3190
0
        }
3191
11
        std::string val;
3192
11
        err = txn->get(k, &val);
3193
11
        if (err ==
3194
11
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3195
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3196
0
            return 0;
3197
0
        }
3198
11
        if (err != TxnErrorCode::TXN_OK) {
3199
0
            LOG_WARNING("failed to get kv");
3200
0
            return -1;
3201
0
        }
3202
11
        part_pb.Clear();
3203
11
        if (!part_pb.ParseFromString(val)) {
3204
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3205
0
            return -1;
3206
0
        }
3207
        // Partitions with PREPARED state MUST have no data
3208
11
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3209
10
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3210
10
            txn->put(k, part_pb.SerializeAsString());
3211
10
            err = txn->commit();
3212
10
            if (err != TxnErrorCode::TXN_OK) {
3213
0
                LOG_WARNING("failed to commit txn: {}", err);
3214
0
                return -1;
3215
0
            }
3216
10
        }
3217
3218
11
        int ret = 0;
3219
35
        for (int64_t index_id : part_pb.index_id()) {
3220
35
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3221
1
                LOG_WARNING("failed to recycle tablets under partition")
3222
1
                        .tag("table_id", part_pb.table_id())
3223
1
                        .tag("instance_id", instance_id_)
3224
1
                        .tag("index_id", index_id)
3225
1
                        .tag("partition_id", partition_id);
3226
1
                ret = -1;
3227
1
            }
3228
35
        }
3229
11
        if (ret == 0 && part_pb.has_db_id() &&
3230
11
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
3231
10
                                                   partition_id, part_pb.table_streams()) != 0) {
3232
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
3233
0
                    .tag("instance_id", instance_id_)
3234
0
                    .tag("table_id", part_pb.table_id())
3235
0
                    .tag("partition_id", partition_id);
3236
0
            ret = -1;
3237
0
        }
3238
11
        if (ret == 0 && part_pb.has_db_id()) {
3239
            // Recycle the versioned keys
3240
10
            std::unique_ptr<Transaction> txn;
3241
10
            err = txn_kv_->create_txn(&txn);
3242
10
            if (err != TxnErrorCode::TXN_OK) {
3243
0
                LOG_WARNING("failed to create txn").tag("err", err);
3244
0
                return -1;
3245
0
            }
3246
10
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3247
10
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3248
10
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3249
10
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3250
10
            std::string partition_version_key =
3251
10
                    versioned::partition_version_key({instance_id_, partition_id});
3252
10
            versioned_remove_all(txn.get(), meta_key);
3253
10
            txn->remove(index_key);
3254
10
            txn->remove(inverted_index_key);
3255
10
            versioned_remove_all(txn.get(), partition_version_key);
3256
10
            err = txn->commit();
3257
10
            if (err != TxnErrorCode::TXN_OK) {
3258
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3259
0
                return -1;
3260
0
            }
3261
10
        }
3262
3263
11
        if (ret == 0) {
3264
10
            ++num_recycled;
3265
10
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3266
10
            partition_keys.push_back(k);
3267
10
            if (part_pb.db_id() > 0) {
3268
10
                partition_version_keys.push_back(partition_version_key(
3269
10
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3270
10
            }
3271
10
            metrics_context.total_recycled_num = num_recycled;
3272
10
            metrics_context.report();
3273
10
        }
3274
11
        return ret;
3275
11
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3161
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3162
2
        ++num_scanned;
3163
2
        RecyclePartitionPB part_pb;
3164
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3165
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3166
0
            return -1;
3167
0
        }
3168
2
        int64_t current_time = ::time(nullptr);
3169
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3170
2
                                                            &earlest_ts)) { // not expired
3171
0
            return 0;
3172
0
        }
3173
2
        ++num_expired;
3174
        // decode partition_id
3175
2
        auto k1 = k;
3176
2
        k1.remove_prefix(1);
3177
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3178
2
        decode_key(&k1, &out);
3179
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3180
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3181
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3182
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3183
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3184
        // Change state to RECYCLING
3185
2
        std::unique_ptr<Transaction> txn;
3186
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3187
2
        if (err != TxnErrorCode::TXN_OK) {
3188
0
            LOG_WARNING("failed to create txn").tag("err", err);
3189
0
            return -1;
3190
0
        }
3191
2
        std::string val;
3192
2
        err = txn->get(k, &val);
3193
2
        if (err ==
3194
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3195
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3196
0
            return 0;
3197
0
        }
3198
2
        if (err != TxnErrorCode::TXN_OK) {
3199
0
            LOG_WARNING("failed to get kv");
3200
0
            return -1;
3201
0
        }
3202
2
        part_pb.Clear();
3203
2
        if (!part_pb.ParseFromString(val)) {
3204
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3205
0
            return -1;
3206
0
        }
3207
        // Partitions with PREPARED state MUST have no data
3208
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3209
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3210
1
            txn->put(k, part_pb.SerializeAsString());
3211
1
            err = txn->commit();
3212
1
            if (err != TxnErrorCode::TXN_OK) {
3213
0
                LOG_WARNING("failed to commit txn: {}", err);
3214
0
                return -1;
3215
0
            }
3216
1
        }
3217
3218
2
        int ret = 0;
3219
2
        for (int64_t index_id : part_pb.index_id()) {
3220
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3221
1
                LOG_WARNING("failed to recycle tablets under partition")
3222
1
                        .tag("table_id", part_pb.table_id())
3223
1
                        .tag("instance_id", instance_id_)
3224
1
                        .tag("index_id", index_id)
3225
1
                        .tag("partition_id", partition_id);
3226
1
                ret = -1;
3227
1
            }
3228
2
        }
3229
2
        if (ret == 0 && part_pb.has_db_id() &&
3230
2
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
3231
1
                                                   partition_id, part_pb.table_streams()) != 0) {
3232
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
3233
0
                    .tag("instance_id", instance_id_)
3234
0
                    .tag("table_id", part_pb.table_id())
3235
0
                    .tag("partition_id", partition_id);
3236
0
            ret = -1;
3237
0
        }
3238
2
        if (ret == 0 && part_pb.has_db_id()) {
3239
            // Recycle the versioned keys
3240
1
            std::unique_ptr<Transaction> txn;
3241
1
            err = txn_kv_->create_txn(&txn);
3242
1
            if (err != TxnErrorCode::TXN_OK) {
3243
0
                LOG_WARNING("failed to create txn").tag("err", err);
3244
0
                return -1;
3245
0
            }
3246
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3247
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3248
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3249
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3250
1
            std::string partition_version_key =
3251
1
                    versioned::partition_version_key({instance_id_, partition_id});
3252
1
            versioned_remove_all(txn.get(), meta_key);
3253
1
            txn->remove(index_key);
3254
1
            txn->remove(inverted_index_key);
3255
1
            versioned_remove_all(txn.get(), partition_version_key);
3256
1
            err = txn->commit();
3257
1
            if (err != TxnErrorCode::TXN_OK) {
3258
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3259
0
                return -1;
3260
0
            }
3261
1
        }
3262
3263
2
        if (ret == 0) {
3264
1
            ++num_recycled;
3265
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3266
1
            partition_keys.push_back(k);
3267
1
            if (part_pb.db_id() > 0) {
3268
1
                partition_version_keys.push_back(partition_version_key(
3269
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3270
1
            }
3271
1
            metrics_context.total_recycled_num = num_recycled;
3272
1
            metrics_context.report();
3273
1
        }
3274
2
        return ret;
3275
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3161
9
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3162
9
        ++num_scanned;
3163
9
        RecyclePartitionPB part_pb;
3164
9
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3165
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3166
0
            return -1;
3167
0
        }
3168
9
        int64_t current_time = ::time(nullptr);
3169
9
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3170
9
                                                            &earlest_ts)) { // not expired
3171
0
            return 0;
3172
0
        }
3173
9
        ++num_expired;
3174
        // decode partition_id
3175
9
        auto k1 = k;
3176
9
        k1.remove_prefix(1);
3177
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3178
9
        decode_key(&k1, &out);
3179
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3180
9
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3181
9
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3182
9
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3183
9
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3184
        // Change state to RECYCLING
3185
9
        std::unique_ptr<Transaction> txn;
3186
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3187
9
        if (err != TxnErrorCode::TXN_OK) {
3188
0
            LOG_WARNING("failed to create txn").tag("err", err);
3189
0
            return -1;
3190
0
        }
3191
9
        std::string val;
3192
9
        err = txn->get(k, &val);
3193
9
        if (err ==
3194
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3195
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3196
0
            return 0;
3197
0
        }
3198
9
        if (err != TxnErrorCode::TXN_OK) {
3199
0
            LOG_WARNING("failed to get kv");
3200
0
            return -1;
3201
0
        }
3202
9
        part_pb.Clear();
3203
9
        if (!part_pb.ParseFromString(val)) {
3204
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3205
0
            return -1;
3206
0
        }
3207
        // Partitions with PREPARED state MUST have no data
3208
9
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3209
9
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3210
9
            txn->put(k, part_pb.SerializeAsString());
3211
9
            err = txn->commit();
3212
9
            if (err != TxnErrorCode::TXN_OK) {
3213
0
                LOG_WARNING("failed to commit txn: {}", err);
3214
0
                return -1;
3215
0
            }
3216
9
        }
3217
3218
9
        int ret = 0;
3219
33
        for (int64_t index_id : part_pb.index_id()) {
3220
33
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3221
0
                LOG_WARNING("failed to recycle tablets under partition")
3222
0
                        .tag("table_id", part_pb.table_id())
3223
0
                        .tag("instance_id", instance_id_)
3224
0
                        .tag("index_id", index_id)
3225
0
                        .tag("partition_id", partition_id);
3226
0
                ret = -1;
3227
0
            }
3228
33
        }
3229
9
        if (ret == 0 && part_pb.has_db_id() &&
3230
9
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
3231
9
                                                   partition_id, part_pb.table_streams()) != 0) {
3232
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
3233
0
                    .tag("instance_id", instance_id_)
3234
0
                    .tag("table_id", part_pb.table_id())
3235
0
                    .tag("partition_id", partition_id);
3236
0
            ret = -1;
3237
0
        }
3238
9
        if (ret == 0 && part_pb.has_db_id()) {
3239
            // Recycle the versioned keys
3240
9
            std::unique_ptr<Transaction> txn;
3241
9
            err = txn_kv_->create_txn(&txn);
3242
9
            if (err != TxnErrorCode::TXN_OK) {
3243
0
                LOG_WARNING("failed to create txn").tag("err", err);
3244
0
                return -1;
3245
0
            }
3246
9
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3247
9
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3248
9
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3249
9
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3250
9
            std::string partition_version_key =
3251
9
                    versioned::partition_version_key({instance_id_, partition_id});
3252
9
            versioned_remove_all(txn.get(), meta_key);
3253
9
            txn->remove(index_key);
3254
9
            txn->remove(inverted_index_key);
3255
9
            versioned_remove_all(txn.get(), partition_version_key);
3256
9
            err = txn->commit();
3257
9
            if (err != TxnErrorCode::TXN_OK) {
3258
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3259
0
                return -1;
3260
0
            }
3261
9
        }
3262
3263
9
        if (ret == 0) {
3264
9
            ++num_recycled;
3265
9
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3266
9
            partition_keys.push_back(k);
3267
9
            if (part_pb.db_id() > 0) {
3268
9
                partition_version_keys.push_back(partition_version_key(
3269
9
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3270
9
            }
3271
9
            metrics_context.total_recycled_num = num_recycled;
3272
9
            metrics_context.report();
3273
9
        }
3274
9
        return ret;
3275
9
    };
3276
3277
17
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3278
7
        if (partition_keys.empty()) return 0;
3279
6
        DORIS_CLOUD_DEFER {
3280
6
            partition_keys.clear();
3281
6
            partition_version_keys.clear();
3282
6
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3279
1
        DORIS_CLOUD_DEFER {
3280
1
            partition_keys.clear();
3281
1
            partition_version_keys.clear();
3282
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3279
5
        DORIS_CLOUD_DEFER {
3280
5
            partition_keys.clear();
3281
5
            partition_version_keys.clear();
3282
5
        };
3283
6
        std::unique_ptr<Transaction> txn;
3284
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3285
6
        if (err != TxnErrorCode::TXN_OK) {
3286
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3287
0
            return -1;
3288
0
        }
3289
10
        for (auto& k : partition_keys) {
3290
10
            txn->remove(k);
3291
10
        }
3292
10
        for (auto& k : partition_version_keys) {
3293
10
            txn->remove(k);
3294
10
        }
3295
6
        err = txn->commit();
3296
6
        if (err != TxnErrorCode::TXN_OK) {
3297
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3298
0
                         << " err=" << err;
3299
0
            return -1;
3300
0
        }
3301
6
        return 0;
3302
6
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3277
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3278
2
        if (partition_keys.empty()) return 0;
3279
1
        DORIS_CLOUD_DEFER {
3280
1
            partition_keys.clear();
3281
1
            partition_version_keys.clear();
3282
1
        };
3283
1
        std::unique_ptr<Transaction> txn;
3284
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3285
1
        if (err != TxnErrorCode::TXN_OK) {
3286
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3287
0
            return -1;
3288
0
        }
3289
1
        for (auto& k : partition_keys) {
3290
1
            txn->remove(k);
3291
1
        }
3292
1
        for (auto& k : partition_version_keys) {
3293
1
            txn->remove(k);
3294
1
        }
3295
1
        err = txn->commit();
3296
1
        if (err != TxnErrorCode::TXN_OK) {
3297
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3298
0
                         << " err=" << err;
3299
0
            return -1;
3300
0
        }
3301
1
        return 0;
3302
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3277
5
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3278
5
        if (partition_keys.empty()) return 0;
3279
5
        DORIS_CLOUD_DEFER {
3280
5
            partition_keys.clear();
3281
5
            partition_version_keys.clear();
3282
5
        };
3283
5
        std::unique_ptr<Transaction> txn;
3284
5
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3285
5
        if (err != TxnErrorCode::TXN_OK) {
3286
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3287
0
            return -1;
3288
0
        }
3289
9
        for (auto& k : partition_keys) {
3290
9
            txn->remove(k);
3291
9
        }
3292
9
        for (auto& k : partition_version_keys) {
3293
9
            txn->remove(k);
3294
9
        }
3295
5
        err = txn->commit();
3296
5
        if (err != TxnErrorCode::TXN_OK) {
3297
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3298
0
                         << " err=" << err;
3299
0
            return -1;
3300
0
        }
3301
5
        return 0;
3302
5
    };
3303
3304
17
    if (config::enable_recycler_stats_metrics) {
3305
0
        scan_and_statistics_partitions();
3306
0
    }
3307
    // recycle_func and loop_done for scan and recycle
3308
17
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
3309
17
}
3310
3311
14
int InstanceRecycler::recycle_versions() {
3312
14
    if (should_recycle_versioned_keys()) {
3313
2
        return recycle_orphan_partitions();
3314
2
    }
3315
3316
12
    int64_t num_scanned = 0;
3317
12
    int64_t num_recycled = 0;
3318
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
3319
3320
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
3321
3322
12
    auto start_time = steady_clock::now();
3323
3324
12
    DORIS_CLOUD_DEFER {
3325
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3326
12
        metrics_context.finish_report();
3327
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3328
12
                .tag("instance_id", instance_id_)
3329
12
                .tag("num_scanned", num_scanned)
3330
12
                .tag("num_recycled", num_recycled);
3331
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
3324
12
    DORIS_CLOUD_DEFER {
3325
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3326
12
        metrics_context.finish_report();
3327
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3328
12
                .tag("instance_id", instance_id_)
3329
12
                .tag("num_scanned", num_scanned)
3330
12
                .tag("num_recycled", num_recycled);
3331
12
    };
3332
3333
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
3334
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
3335
12
    int64_t last_scanned_table_id = 0;
3336
12
    bool is_recycled = false; // Is last scanned kv recycled
3337
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
3338
12
                         &metrics_context, this](std::string_view k, std::string_view) {
3339
2
        ++num_scanned;
3340
2
        auto k1 = k;
3341
2
        k1.remove_prefix(1);
3342
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3343
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3344
2
        decode_key(&k1, &out);
3345
2
        DCHECK_EQ(out.size(), 6) << k;
3346
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3347
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3348
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3349
0
            return 0;
3350
0
        }
3351
2
        last_scanned_table_id = table_id;
3352
2
        is_recycled = false;
3353
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3354
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3355
2
        std::unique_ptr<Transaction> txn;
3356
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3357
2
        if (err != TxnErrorCode::TXN_OK) {
3358
0
            return -1;
3359
0
        }
3360
2
        std::unique_ptr<RangeGetIterator> iter;
3361
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3362
2
        if (err != TxnErrorCode::TXN_OK) {
3363
0
            return -1;
3364
0
        }
3365
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3366
1
            return 0;
3367
1
        }
3368
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3369
        // 1. Remove all partition version kvs of this table
3370
1
        auto partition_version_key_begin =
3371
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3372
1
        auto partition_version_key_end =
3373
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3374
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3375
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3376
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3377
1
                     << " table_id=" << table_id;
3378
        // 2. Remove the table version kv of this table
3379
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3380
1
        txn->remove(tbl_version_key);
3381
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3382
        // 3. Remove mow delete bitmap update lock and tablet job lock
3383
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3384
1
        txn->remove(lock_key);
3385
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3386
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3387
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3388
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3389
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3390
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3391
1
                     << " table_id=" << table_id;
3392
1
        err = txn->commit();
3393
1
        if (err != TxnErrorCode::TXN_OK) {
3394
0
            return -1;
3395
0
        }
3396
1
        metrics_context.total_recycled_num = ++num_recycled;
3397
1
        metrics_context.report();
3398
1
        is_recycled = true;
3399
1
        return 0;
3400
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3338
2
                         &metrics_context, this](std::string_view k, std::string_view) {
3339
2
        ++num_scanned;
3340
2
        auto k1 = k;
3341
2
        k1.remove_prefix(1);
3342
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3343
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3344
2
        decode_key(&k1, &out);
3345
2
        DCHECK_EQ(out.size(), 6) << k;
3346
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3347
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3348
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3349
0
            return 0;
3350
0
        }
3351
2
        last_scanned_table_id = table_id;
3352
2
        is_recycled = false;
3353
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3354
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3355
2
        std::unique_ptr<Transaction> txn;
3356
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3357
2
        if (err != TxnErrorCode::TXN_OK) {
3358
0
            return -1;
3359
0
        }
3360
2
        std::unique_ptr<RangeGetIterator> iter;
3361
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3362
2
        if (err != TxnErrorCode::TXN_OK) {
3363
0
            return -1;
3364
0
        }
3365
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3366
1
            return 0;
3367
1
        }
3368
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3369
        // 1. Remove all partition version kvs of this table
3370
1
        auto partition_version_key_begin =
3371
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3372
1
        auto partition_version_key_end =
3373
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3374
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3375
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3376
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3377
1
                     << " table_id=" << table_id;
3378
        // 2. Remove the table version kv of this table
3379
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3380
1
        txn->remove(tbl_version_key);
3381
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3382
        // 3. Remove mow delete bitmap update lock and tablet job lock
3383
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3384
1
        txn->remove(lock_key);
3385
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3386
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3387
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3388
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3389
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3390
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3391
1
                     << " table_id=" << table_id;
3392
1
        err = txn->commit();
3393
1
        if (err != TxnErrorCode::TXN_OK) {
3394
0
            return -1;
3395
0
        }
3396
1
        metrics_context.total_recycled_num = ++num_recycled;
3397
1
        metrics_context.report();
3398
1
        is_recycled = true;
3399
1
        return 0;
3400
1
    };
3401
3402
12
    if (config::enable_recycler_stats_metrics) {
3403
0
        scan_and_statistics_versions();
3404
0
    }
3405
    // recycle_func and loop_done for scan and recycle
3406
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
3407
14
}
3408
3409
3
int InstanceRecycler::recycle_orphan_partitions() {
3410
3
    int64_t num_scanned = 0;
3411
3
    int64_t num_recycled = 0;
3412
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
3413
3414
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
3415
3
            .tag("instance_id", instance_id_);
3416
3417
3
    auto start_time = steady_clock::now();
3418
3419
3
    DORIS_CLOUD_DEFER {
3420
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3421
3
        metrics_context.finish_report();
3422
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3423
3
                .tag("instance_id", instance_id_)
3424
3
                .tag("num_scanned", num_scanned)
3425
3
                .tag("num_recycled", num_recycled);
3426
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
3419
3
    DORIS_CLOUD_DEFER {
3420
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3421
3
        metrics_context.finish_report();
3422
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3423
3
                .tag("instance_id", instance_id_)
3424
3
                .tag("num_scanned", num_scanned)
3425
3
                .tag("num_recycled", num_recycled);
3426
3
    };
3427
3428
3
    bool is_empty_table = false;        // whether the table has no indexes
3429
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
3430
3
    int64_t current_table_id = 0;       // current scanning table id
3431
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
3432
3
                         &current_table_id, &is_table_kvs_recycled,
3433
3
                         this](std::string_view k, std::string_view) {
3434
2
        ++num_scanned;
3435
3436
2
        std::string_view k1(k);
3437
2
        int64_t db_id, table_id, partition_id;
3438
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3439
2
                                                            &partition_id)) {
3440
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3441
0
            return -1;
3442
2
        } else if (table_id != current_table_id) {
3443
2
            current_table_id = table_id;
3444
2
            is_table_kvs_recycled = false;
3445
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3446
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3447
2
            if (err != TxnErrorCode::TXN_OK) {
3448
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3449
0
                             << " table_id=" << table_id << " err=" << err;
3450
0
                return -1;
3451
0
            }
3452
2
        }
3453
3454
2
        if (!is_empty_table) {
3455
            // table is not empty, skip recycle
3456
1
            return 0;
3457
1
        }
3458
3459
1
        std::unique_ptr<Transaction> txn;
3460
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3461
1
        if (err != TxnErrorCode::TXN_OK) {
3462
0
            return -1;
3463
0
        }
3464
3465
        // 1. Remove all partition related kvs
3466
1
        std::string partition_meta_key =
3467
1
                versioned::meta_partition_key({instance_id_, partition_id});
3468
1
        std::string partition_index_key =
3469
1
                versioned::partition_index_key({instance_id_, partition_id});
3470
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3471
1
                {instance_id_, db_id, table_id, partition_id});
3472
1
        std::string partition_version_key =
3473
1
                versioned::partition_version_key({instance_id_, partition_id});
3474
1
        txn->remove(partition_index_key);
3475
1
        txn->remove(partition_inverted_key);
3476
1
        versioned_remove_all(txn.get(), partition_meta_key);
3477
1
        versioned_remove_all(txn.get(), partition_version_key);
3478
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3479
1
                     << " table_id=" << table_id << " db_id=" << db_id
3480
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3481
1
                     << " partition_version_key=" << hex(partition_version_key);
3482
3483
1
        if (!is_table_kvs_recycled) {
3484
1
            is_table_kvs_recycled = true;
3485
3486
            // 2. Remove the table version kv of this table
3487
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3488
1
            versioned_remove_all(txn.get(), table_version_key);
3489
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3490
            // 3. Remove mow delete bitmap update lock and tablet job lock
3491
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3492
1
            txn->remove(lock_key);
3493
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3494
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3495
1
            std::string tablet_job_key_end =
3496
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3497
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3498
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3499
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3500
1
                         << " table_id=" << table_id;
3501
1
        }
3502
3503
1
        err = txn->commit();
3504
1
        if (err != TxnErrorCode::TXN_OK) {
3505
0
            return -1;
3506
0
        }
3507
1
        metrics_context.total_recycled_num = ++num_recycled;
3508
1
        metrics_context.report();
3509
1
        return 0;
3510
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
3433
2
                         this](std::string_view k, std::string_view) {
3434
2
        ++num_scanned;
3435
3436
2
        std::string_view k1(k);
3437
2
        int64_t db_id, table_id, partition_id;
3438
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3439
2
                                                            &partition_id)) {
3440
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3441
0
            return -1;
3442
2
        } else if (table_id != current_table_id) {
3443
2
            current_table_id = table_id;
3444
2
            is_table_kvs_recycled = false;
3445
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3446
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3447
2
            if (err != TxnErrorCode::TXN_OK) {
3448
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3449
0
                             << " table_id=" << table_id << " err=" << err;
3450
0
                return -1;
3451
0
            }
3452
2
        }
3453
3454
2
        if (!is_empty_table) {
3455
            // table is not empty, skip recycle
3456
1
            return 0;
3457
1
        }
3458
3459
1
        std::unique_ptr<Transaction> txn;
3460
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3461
1
        if (err != TxnErrorCode::TXN_OK) {
3462
0
            return -1;
3463
0
        }
3464
3465
        // 1. Remove all partition related kvs
3466
1
        std::string partition_meta_key =
3467
1
                versioned::meta_partition_key({instance_id_, partition_id});
3468
1
        std::string partition_index_key =
3469
1
                versioned::partition_index_key({instance_id_, partition_id});
3470
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3471
1
                {instance_id_, db_id, table_id, partition_id});
3472
1
        std::string partition_version_key =
3473
1
                versioned::partition_version_key({instance_id_, partition_id});
3474
1
        txn->remove(partition_index_key);
3475
1
        txn->remove(partition_inverted_key);
3476
1
        versioned_remove_all(txn.get(), partition_meta_key);
3477
1
        versioned_remove_all(txn.get(), partition_version_key);
3478
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3479
1
                     << " table_id=" << table_id << " db_id=" << db_id
3480
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3481
1
                     << " partition_version_key=" << hex(partition_version_key);
3482
3483
1
        if (!is_table_kvs_recycled) {
3484
1
            is_table_kvs_recycled = true;
3485
3486
            // 2. Remove the table version kv of this table
3487
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3488
1
            versioned_remove_all(txn.get(), table_version_key);
3489
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3490
            // 3. Remove mow delete bitmap update lock and tablet job lock
3491
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3492
1
            txn->remove(lock_key);
3493
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3494
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3495
1
            std::string tablet_job_key_end =
3496
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3497
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3498
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3499
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3500
1
                         << " table_id=" << table_id;
3501
1
        }
3502
3503
1
        err = txn->commit();
3504
1
        if (err != TxnErrorCode::TXN_OK) {
3505
0
            return -1;
3506
0
        }
3507
1
        metrics_context.total_recycled_num = ++num_recycled;
3508
1
        metrics_context.report();
3509
1
        return 0;
3510
1
    };
3511
3512
    // recycle_func and loop_done for scan and recycle
3513
3
    return scan_and_recycle(
3514
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
3515
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
3516
3
            std::move(recycle_func));
3517
3
}
3518
3519
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
3520
                                      RecyclerMetricsContext& metrics_context,
3521
54
                                      int64_t partition_id) {
3522
54
    bool is_multi_version =
3523
54
            instance_info_.has_multi_version_status() &&
3524
54
            instance_info_.multi_version_status() != MultiVersionStatus::MULTI_VERSION_DISABLED;
3525
54
    int64_t num_scanned = 0;
3526
54
    std::atomic_long num_recycled = 0;
3527
3528
54
    std::string tablet_key_begin, tablet_key_end;
3529
54
    std::string stats_key_begin, stats_key_end;
3530
54
    std::string job_key_begin, job_key_end;
3531
3532
54
    std::string tablet_belongs;
3533
54
    if (partition_id > 0) {
3534
        // recycle tablets in a partition belonging to the index
3535
35
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
3536
35
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
3537
35
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
3538
35
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
3539
35
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
3540
35
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
3541
35
        tablet_belongs = "partition";
3542
35
    } else {
3543
        // recycle tablets in the index
3544
19
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
3545
19
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
3546
19
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
3547
19
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
3548
19
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
3549
19
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
3550
19
        tablet_belongs = "index";
3551
19
    }
3552
3553
54
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
3554
54
            .tag("table_id", table_id)
3555
54
            .tag("index_id", index_id)
3556
54
            .tag("partition_id", partition_id);
3557
3558
54
    auto start_time = steady_clock::now();
3559
3560
54
    DORIS_CLOUD_DEFER {
3561
54
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3562
54
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3563
54
                .tag("instance_id", instance_id_)
3564
54
                .tag("table_id", table_id)
3565
54
                .tag("index_id", index_id)
3566
54
                .tag("partition_id", partition_id)
3567
54
                .tag("num_scanned", num_scanned)
3568
54
                .tag("num_recycled", num_recycled);
3569
54
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3560
4
    DORIS_CLOUD_DEFER {
3561
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3562
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3563
4
                .tag("instance_id", instance_id_)
3564
4
                .tag("table_id", table_id)
3565
4
                .tag("index_id", index_id)
3566
4
                .tag("partition_id", partition_id)
3567
4
                .tag("num_scanned", num_scanned)
3568
4
                .tag("num_recycled", num_recycled);
3569
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3560
50
    DORIS_CLOUD_DEFER {
3561
50
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3562
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3563
50
                .tag("instance_id", instance_id_)
3564
50
                .tag("table_id", table_id)
3565
50
                .tag("index_id", index_id)
3566
50
                .tag("partition_id", partition_id)
3567
50
                .tag("num_scanned", num_scanned)
3568
50
                .tag("num_recycled", num_recycled);
3569
50
    };
3570
3571
    // The tablet key and id which have been recycled.
3572
54
    struct TabletInfo {
3573
54
        std::string_view tablet_meta_key;
3574
54
        int64_t tablet_id;
3575
54
    };
3576
54
    SyncExecutor<TabletInfo> sync_executor(
3577
54
            _thread_pool_group.recycle_tablet_pool,
3578
54
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
3579
54
                        index_id, partition_id),
3580
4.24k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3580
4.00k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3580
241
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
3581
3582
    // Elements in `tablets_info` has the same lifetime as `it` in `scan_and_recycle`
3583
54
    std::vector<std::string> init_rs_keys;
3584
54
    bool has_failure = false;
3585
8.25k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3586
8.25k
        ++num_scanned;
3587
8.25k
        doris::TabletMetaCloudPB tablet_meta_pb;
3588
8.25k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3589
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3590
0
            has_failure = true;
3591
0
            return -1;
3592
0
        }
3593
8.25k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3594
3595
8.25k
        if (config::enable_recycler_check_lazy_txn_finished &&
3596
8.25k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3597
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3598
4.00k
            has_failure = true;
3599
4.00k
            return -1;
3600
4.00k
        }
3601
3602
8.25k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3603
4.25k
        sync_executor.add(
3604
4.25k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3605
4.25k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3606
2
                        LOG_WARNING("failed to recycle tablet")
3607
2
                                .tag("instance_id", instance_id_)
3608
2
                                .tag("tablet_id", tid);
3609
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3610
2
                    }
3611
4.25k
                    ++num_recycled;
3612
4.25k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3613
4.25k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3614
4.25k
                });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3604
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3605
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3606
0
                        LOG_WARNING("failed to recycle tablet")
3607
0
                                .tag("instance_id", instance_id_)
3608
0
                                .tag("tablet_id", tid);
3609
0
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3610
0
                    }
3611
4.00k
                    ++num_recycled;
3612
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3613
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3614
4.00k
                });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3604
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3605
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3606
2
                        LOG_WARNING("failed to recycle tablet")
3607
2
                                .tag("instance_id", instance_id_)
3608
2
                                .tag("tablet_id", tid);
3609
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3610
2
                    }
3611
248
                    ++num_recycled;
3612
248
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3613
248
                    return {.tablet_meta_key = k, .tablet_id = tid};
3614
250
                });
3615
4.25k
        return 0;
3616
4.25k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3585
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3586
8.00k
        ++num_scanned;
3587
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
3588
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3589
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3590
0
            has_failure = true;
3591
0
            return -1;
3592
0
        }
3593
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3594
3595
8.00k
        if (config::enable_recycler_check_lazy_txn_finished &&
3596
8.00k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3597
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3598
4.00k
            has_failure = true;
3599
4.00k
            return -1;
3600
4.00k
        }
3601
3602
8.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3603
4.00k
        sync_executor.add(
3604
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3605
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3606
4.00k
                        LOG_WARNING("failed to recycle tablet")
3607
4.00k
                                .tag("instance_id", instance_id_)
3608
4.00k
                                .tag("tablet_id", tid);
3609
4.00k
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3610
4.00k
                    }
3611
4.00k
                    ++num_recycled;
3612
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3613
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3614
4.00k
                });
3615
4.00k
        return 0;
3616
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3585
251
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3586
251
        ++num_scanned;
3587
251
        doris::TabletMetaCloudPB tablet_meta_pb;
3588
251
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3589
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3590
0
            has_failure = true;
3591
0
            return -1;
3592
0
        }
3593
251
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3594
3595
251
        if (config::enable_recycler_check_lazy_txn_finished &&
3596
251
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3597
1
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3598
1
            has_failure = true;
3599
1
            return -1;
3600
1
        }
3601
3602
251
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3603
250
        sync_executor.add(
3604
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3605
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3606
250
                        LOG_WARNING("failed to recycle tablet")
3607
250
                                .tag("instance_id", instance_id_)
3608
250
                                .tag("tablet_id", tid);
3609
250
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3610
250
                    }
3611
250
                    ++num_recycled;
3612
250
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3613
250
                    return {.tablet_meta_key = k, .tablet_id = tid};
3614
250
                });
3615
250
        return 0;
3616
250
    };
3617
3618
54
    auto loop_done = [&, this]() -> int {
3619
52
        int ret = 0;
3620
52
        bool finished = true;
3621
52
        bool has_empty_key = false;
3622
52
        DORIS_CLOUD_DEFER {
3623
52
            init_rs_keys.clear();
3624
52
            has_failure = false;
3625
52
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3622
4
        DORIS_CLOUD_DEFER {
3623
4
            init_rs_keys.clear();
3624
4
            has_failure = false;
3625
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3622
48
        DORIS_CLOUD_DEFER {
3623
48
            init_rs_keys.clear();
3624
48
            has_failure = false;
3625
48
        };
3626
52
        auto tablets_info = sync_executor.when_all(&finished);
3627
52
        if (!finished) {
3628
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3629
1
            return -1;
3630
1
        }
3631
3632
51
        size_t size_before_erase = tablets_info.size();
3633
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
3633
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
3633
249
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3634
51
        if (tablets_info.empty()) {
3635
2
            return size_before_erase == 0 ? 0 : -1;
3636
49
        } else if (size_before_erase != tablets_info.size()) {
3637
1
            has_empty_key = true;
3638
1
        }
3639
3640
49
        ret = has_empty_key ? -1 : 0;
3641
        // sort the vector using key's order
3642
49.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3643
49.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3644
49.4k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3642
48.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3643
48.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3644
48.4k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3642
958
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3643
958
            return prev.tablet_meta_key < last.tablet_meta_key;
3644
958
        });
3645
49
        std::unique_ptr<Transaction> txn;
3646
49
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3647
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3648
0
            return -1;
3649
0
        }
3650
49
        std::string tablet_key_end;
3651
49
        if (!tablets_info.empty()) {
3652
49
            if (!has_empty_key && !has_failure) {
3653
47
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3654
47
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3655
47
            } else {
3656
8
                for (auto& tablet_info : tablets_info) {
3657
8
                    txn->remove(tablet_info.tablet_meta_key);
3658
8
                }
3659
2
            }
3660
49
        }
3661
49
        if (is_multi_version) {
3662
6
            for (auto& tablet_info : tablets_info) {
3663
                // Remove all versions of tablet compact stats for recycled tablet
3664
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3665
6
                LOG_INFO("remove versioned tablet compact stats key")
3666
6
                        .tag("compact_stats_key", hex(k));
3667
6
                versioned_remove_all(txn.get(), k);
3668
6
            }
3669
6
            for (auto& tablet_info : tablets_info) {
3670
                // Remove all versions of tablet load stats for recycled tablet
3671
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3672
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3673
6
                versioned_remove_all(txn.get(), k);
3674
6
            }
3675
6
            for (auto& tablet_info : tablets_info) {
3676
                // Remove all versions of meta tablet for recycled tablet
3677
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3678
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3679
6
                versioned_remove_all(txn.get(), k);
3680
6
            }
3681
5
        }
3682
4.25k
        for (auto& tablet_info : tablets_info) {
3683
4.25k
            std::string k;
3684
4.25k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3685
4.25k
            txn->remove(k);
3686
4.25k
        }
3687
4.25k
        for (auto& tablet_info : tablets_info) {
3688
4.25k
            std::string k;
3689
4.25k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3690
4.25k
            txn->remove(k);
3691
4.25k
        }
3692
49
        for (auto& k : init_rs_keys) {
3693
0
            txn->remove(k);
3694
0
        }
3695
49
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3696
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3697
0
                         << ", err=" << err;
3698
0
            return -1;
3699
0
        }
3700
49
        return ret;
3701
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3618
4
    auto loop_done = [&, this]() -> int {
3619
4
        int ret = 0;
3620
4
        bool finished = true;
3621
4
        bool has_empty_key = false;
3622
4
        DORIS_CLOUD_DEFER {
3623
4
            init_rs_keys.clear();
3624
4
            has_failure = false;
3625
4
        };
3626
4
        auto tablets_info = sync_executor.when_all(&finished);
3627
4
        if (!finished) {
3628
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3629
0
            return -1;
3630
0
        }
3631
3632
4
        size_t size_before_erase = tablets_info.size();
3633
4
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3634
4
        if (tablets_info.empty()) {
3635
2
            return size_before_erase == 0 ? 0 : -1;
3636
2
        } else if (size_before_erase != tablets_info.size()) {
3637
0
            has_empty_key = true;
3638
0
        }
3639
3640
2
        ret = has_empty_key ? -1 : 0;
3641
        // sort the vector using key's order
3642
2
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3643
2
            return prev.tablet_meta_key < last.tablet_meta_key;
3644
2
        });
3645
2
        std::unique_ptr<Transaction> txn;
3646
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3647
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3648
0
            return -1;
3649
0
        }
3650
2
        std::string tablet_key_end;
3651
2
        if (!tablets_info.empty()) {
3652
2
            if (!has_empty_key && !has_failure) {
3653
2
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3654
2
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3655
2
            } else {
3656
0
                for (auto& tablet_info : tablets_info) {
3657
0
                    txn->remove(tablet_info.tablet_meta_key);
3658
0
                }
3659
0
            }
3660
2
        }
3661
2
        if (is_multi_version) {
3662
0
            for (auto& tablet_info : tablets_info) {
3663
                // Remove all versions of tablet compact stats for recycled tablet
3664
0
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3665
0
                LOG_INFO("remove versioned tablet compact stats key")
3666
0
                        .tag("compact_stats_key", hex(k));
3667
0
                versioned_remove_all(txn.get(), k);
3668
0
            }
3669
0
            for (auto& tablet_info : tablets_info) {
3670
                // Remove all versions of tablet load stats for recycled tablet
3671
0
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3672
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3673
0
                versioned_remove_all(txn.get(), k);
3674
0
            }
3675
0
            for (auto& tablet_info : tablets_info) {
3676
                // Remove all versions of meta tablet for recycled tablet
3677
0
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3678
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3679
0
                versioned_remove_all(txn.get(), k);
3680
0
            }
3681
0
        }
3682
4.00k
        for (auto& tablet_info : tablets_info) {
3683
4.00k
            std::string k;
3684
4.00k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3685
4.00k
            txn->remove(k);
3686
4.00k
        }
3687
4.00k
        for (auto& tablet_info : tablets_info) {
3688
4.00k
            std::string k;
3689
4.00k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3690
4.00k
            txn->remove(k);
3691
4.00k
        }
3692
2
        for (auto& k : init_rs_keys) {
3693
0
            txn->remove(k);
3694
0
        }
3695
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3696
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3697
0
                         << ", err=" << err;
3698
0
            return -1;
3699
0
        }
3700
2
        return ret;
3701
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3618
48
    auto loop_done = [&, this]() -> int {
3619
48
        int ret = 0;
3620
48
        bool finished = true;
3621
48
        bool has_empty_key = false;
3622
48
        DORIS_CLOUD_DEFER {
3623
48
            init_rs_keys.clear();
3624
48
            has_failure = false;
3625
48
        };
3626
48
        auto tablets_info = sync_executor.when_all(&finished);
3627
48
        if (!finished) {
3628
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3629
1
            return -1;
3630
1
        }
3631
3632
47
        size_t size_before_erase = tablets_info.size();
3633
47
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3634
47
        if (tablets_info.empty()) {
3635
0
            return size_before_erase == 0 ? 0 : -1;
3636
47
        } else if (size_before_erase != tablets_info.size()) {
3637
1
            has_empty_key = true;
3638
1
        }
3639
3640
47
        ret = has_empty_key ? -1 : 0;
3641
        // sort the vector using key's order
3642
47
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3643
47
            return prev.tablet_meta_key < last.tablet_meta_key;
3644
47
        });
3645
47
        std::unique_ptr<Transaction> txn;
3646
47
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3647
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3648
0
            return -1;
3649
0
        }
3650
47
        std::string tablet_key_end;
3651
47
        if (!tablets_info.empty()) {
3652
47
            if (!has_empty_key && !has_failure) {
3653
45
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3654
45
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3655
45
            } else {
3656
8
                for (auto& tablet_info : tablets_info) {
3657
8
                    txn->remove(tablet_info.tablet_meta_key);
3658
8
                }
3659
2
            }
3660
47
        }
3661
47
        if (is_multi_version) {
3662
6
            for (auto& tablet_info : tablets_info) {
3663
                // Remove all versions of tablet compact stats for recycled tablet
3664
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3665
6
                LOG_INFO("remove versioned tablet compact stats key")
3666
6
                        .tag("compact_stats_key", hex(k));
3667
6
                versioned_remove_all(txn.get(), k);
3668
6
            }
3669
6
            for (auto& tablet_info : tablets_info) {
3670
                // Remove all versions of tablet load stats for recycled tablet
3671
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3672
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3673
6
                versioned_remove_all(txn.get(), k);
3674
6
            }
3675
6
            for (auto& tablet_info : tablets_info) {
3676
                // Remove all versions of meta tablet for recycled tablet
3677
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3678
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3679
6
                versioned_remove_all(txn.get(), k);
3680
6
            }
3681
5
        }
3682
248
        for (auto& tablet_info : tablets_info) {
3683
248
            std::string k;
3684
248
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3685
248
            txn->remove(k);
3686
248
        }
3687
248
        for (auto& tablet_info : tablets_info) {
3688
248
            std::string k;
3689
248
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3690
248
            txn->remove(k);
3691
248
        }
3692
47
        for (auto& k : init_rs_keys) {
3693
0
            txn->remove(k);
3694
0
        }
3695
47
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3696
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3697
0
                         << ", err=" << err;
3698
0
            return -1;
3699
0
        }
3700
47
        return ret;
3701
47
    };
3702
3703
54
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
3704
54
                               std::move(loop_done));
3705
54
    if (ret != 0) {
3706
5
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
3707
5
        return ret;
3708
5
    }
3709
3710
    // directly remove tablet stats and tablet jobs of these dropped index or partition
3711
49
    std::unique_ptr<Transaction> txn;
3712
49
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3713
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
3714
0
        return -1;
3715
0
    }
3716
49
    txn->remove(stats_key_begin, stats_key_end);
3717
49
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
3718
49
                 << " end=" << hex(stats_key_end);
3719
49
    txn->remove(job_key_begin, job_key_end);
3720
49
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
3721
49
    std::string schema_key_begin, schema_key_end;
3722
49
    std::string schema_dict_key;
3723
49
    std::string versioned_schema_key_begin, versioned_schema_key_end;
3724
49
    if (partition_id <= 0) {
3725
        // Delete schema kv of this index
3726
15
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
3727
15
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
3728
15
        txn->remove(schema_key_begin, schema_key_end);
3729
15
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
3730
15
                     << " end=" << hex(schema_key_end);
3731
15
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
3732
15
        txn->remove(schema_dict_key);
3733
15
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
3734
15
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
3735
15
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
3736
15
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
3737
15
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
3738
15
                     << " end=" << hex(versioned_schema_key_end);
3739
15
    }
3740
3741
49
    TxnErrorCode err = txn->commit();
3742
49
    if (err != TxnErrorCode::TXN_OK) {
3743
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
3744
0
                     << " err=" << err;
3745
0
        return -1;
3746
0
    }
3747
3748
49
    return ret;
3749
49
}
3750
3751
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
3752
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
3753
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
3754
5.61k
    if (num_segments <= 0) return 0;
3755
3756
5.61k
    std::vector<std::string> file_paths;
3757
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
3758
0
        return -1;
3759
0
    }
3760
3761
    // Process inverted indexes
3762
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
3763
5.61k
    InvertedIndexStorageFormatPB index_format = rs_meta_pb.has_inverted_index_storage_format()
3764
5.61k
                                                        ? rs_meta_pb.inverted_index_storage_format()
3765
5.61k
                                                        : InvertedIndexStorageFormatPB::V1;
3766
5.61k
    bool delete_rowset_data_by_prefix = false;
3767
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3768
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3769
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3770
0
        delete_rowset_data_by_prefix = true;
3771
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
3772
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
3773
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3774
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3775
10.0k
            }
3776
10.0k
        }
3777
4.80k
        if (!rs_meta_pb.has_inverted_index_storage_format() &&
3778
4.80k
            rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
3779
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
3780
2.00k
        }
3781
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
3782
        // schema version and index id are not found, delete rowset data by prefix directly.
3783
0
        delete_rowset_data_by_prefix = true;
3784
809
    } else {
3785
        // otherwise, try to get schema kv
3786
809
        InvertedIndexInfo index_info;
3787
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
3788
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
3789
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3790
809
                                 &inverted_index_get_ret);
3791
809
        if (inverted_index_get_ret == 0) {
3792
809
            if (!rs_meta_pb.has_inverted_index_storage_format()) {
3793
809
                index_format = index_info.first;
3794
809
            }
3795
809
            index_ids = index_info.second;
3796
809
        } else if (inverted_index_get_ret == 1) {
3797
            // 1. Schema kv not found means tablet has been recycled
3798
            // Maybe some tablet recycle failed by some bugs
3799
            // We need to delete again to double check
3800
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3801
            // because we are uncertain about the inverted index information.
3802
            // If there are inverted indexes, some data might not be deleted,
3803
            // but this is acceptable as we have made our best effort to delete the data.
3804
0
            LOG_INFO(
3805
0
                    "delete rowset data schema kv not found, need to delete again to double "
3806
0
                    "check")
3807
0
                    .tag("instance_id", instance_id_)
3808
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3809
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
3810
            // Currently index_ids is guaranteed to be empty,
3811
            // but we clear it again here as a safeguard against future code changes
3812
            // that might cause index_ids to no longer be empty
3813
0
            index_format = InvertedIndexStorageFormatPB::V2;
3814
0
            index_ids.clear();
3815
0
        } else {
3816
            // failed to get schema kv, delete rowset data by prefix directly.
3817
0
            delete_rowset_data_by_prefix = true;
3818
0
        }
3819
809
    }
3820
3821
5.61k
    if (delete_rowset_data_by_prefix) {
3822
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
3823
0
                                  rs_meta_pb.rowset_id_v2());
3824
0
    }
3825
3826
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
3827
5.61k
    if (it == accessor_map_.end()) {
3828
1.60k
        LOG_WARNING("instance has no such resource id")
3829
1.60k
                .tag("instance_id", instance_id_)
3830
1.60k
                .tag("resource_id", rs_meta_pb.resource_id());
3831
1.60k
        return -1;
3832
1.60k
    }
3833
4.01k
    auto& accessor = it->second;
3834
3835
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
3836
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
3837
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
3838
20.0k
        auto segment_id = rowset_segment_id(rs_meta_pb, i);
3839
20.0k
        add_file_to_delete_if_not_packed(rs_meta_pb, segment_path(tablet_id, rowset_id, segment_id),
3840
20.0k
                                         &file_paths);
3841
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
3842
40.0k
            for (const auto& index_id : index_ids) {
3843
40.0k
                add_file_to_delete_if_not_packed(
3844
40.0k
                        rs_meta_pb,
3845
40.0k
                        inverted_index_path_v1(tablet_id, rowset_id, segment_id, index_id.first,
3846
40.0k
                                               index_id.second),
3847
40.0k
                        &file_paths);
3848
40.0k
            }
3849
20.0k
        } else if (!index_ids.empty()) {
3850
2
            add_file_to_delete_if_not_packed(
3851
2
                    rs_meta_pb, inverted_index_path_v2(tablet_id, rowset_id, segment_id),
3852
2
                    &file_paths);
3853
2
        }
3854
20.0k
    }
3855
3856
    // Process delete bitmap - check where it's stored.
3857
4.01k
    DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3858
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3859
4.01k
                                                       &delete_bitmap_storage_type) != 0) {
3860
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3861
0
                .tag("instance_id", instance_id_)
3862
0
                .tag("tablet_id", tablet_id)
3863
0
                .tag("rowset_id", rowset_id);
3864
0
        return -1;
3865
0
    }
3866
4.01k
    if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3867
2.00k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3868
2.00k
    }
3869
    // TODO(AlexYue): seems could do do batch
3870
4.01k
    return accessor->delete_files(file_paths);
3871
4.01k
}
3872
3873
62.6k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3874
62.6k
    LOG_INFO("begin process_packed_file_location_index")
3875
62.6k
            .tag("instance_id", instance_id_)
3876
62.6k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3877
62.6k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3878
62.6k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3879
62.6k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3880
62.6k
    if (index_map.empty()) {
3881
62.6k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3882
62.6k
                .tag("instance_id", instance_id_)
3883
62.6k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3884
62.6k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3885
62.6k
        return 0;
3886
62.6k
    }
3887
3888
13
    struct PackedSmallFileInfo {
3889
13
        std::string small_file_path;
3890
13
    };
3891
13
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3892
13
    packed_file_updates.reserve(index_map.size());
3893
27
    for (const auto& [small_path, index_pb] : index_map) {
3894
27
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3895
0
            continue;
3896
0
        }
3897
27
        packed_file_updates[index_pb.packed_file_path()].push_back(
3898
27
                PackedSmallFileInfo {small_path});
3899
27
    }
3900
13
    if (packed_file_updates.empty()) {
3901
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3902
0
                .tag("instance_id", instance_id_)
3903
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3904
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3905
0
                .tag("index_map_size", index_map.size());
3906
0
        return 0;
3907
0
    }
3908
3909
13
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3910
13
    int ret = 0;
3911
24
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3912
24
        if (small_files.empty()) {
3913
0
            continue;
3914
0
        }
3915
3916
24
        bool success = false;
3917
24
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3918
24
            std::unique_ptr<Transaction> txn;
3919
24
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3920
24
            if (err != TxnErrorCode::TXN_OK) {
3921
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3922
0
                        .tag("instance_id", instance_id_)
3923
0
                        .tag("packed_file_path", packed_file_path)
3924
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3925
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3926
0
                        .tag("err", err);
3927
0
                ret = -1;
3928
0
                break;
3929
0
            }
3930
3931
24
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3932
24
            std::string packed_val;
3933
24
            err = txn->get(packed_key, &packed_val);
3934
24
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3935
0
                LOG_WARNING("packed file info not found when recycling rowset")
3936
0
                        .tag("instance_id", instance_id_)
3937
0
                        .tag("packed_file_path", packed_file_path)
3938
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3939
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3940
0
                        .tag("key", hex(packed_key))
3941
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3942
                // Skip this packed file entry and continue with others
3943
0
                success = true;
3944
0
                break;
3945
0
            }
3946
24
            if (err != TxnErrorCode::TXN_OK) {
3947
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
3948
0
                        .tag("instance_id", instance_id_)
3949
0
                        .tag("packed_file_path", packed_file_path)
3950
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3951
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3952
0
                        .tag("err", err);
3953
0
                ret = -1;
3954
0
                break;
3955
0
            }
3956
3957
24
            cloud::PackedFileInfoPB packed_info;
3958
24
            if (!packed_info.ParseFromString(packed_val)) {
3959
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
3960
0
                        .tag("instance_id", instance_id_)
3961
0
                        .tag("packed_file_path", packed_file_path)
3962
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3963
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3964
0
                ret = -1;
3965
0
                break;
3966
0
            }
3967
3968
24
            LOG_INFO("packed file update check")
3969
24
                    .tag("instance_id", instance_id_)
3970
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3971
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3972
24
                    .tag("merged_file_path", packed_file_path)
3973
24
                    .tag("requested_small_files", small_files.size())
3974
24
                    .tag("merge_entries", packed_info.slices_size());
3975
3976
24
            auto* small_file_entries = packed_info.mutable_slices();
3977
24
            int64_t changed_files = 0;
3978
24
            int64_t missing_entries = 0;
3979
24
            int64_t already_deleted = 0;
3980
27
            for (const auto& small_file_info : small_files) {
3981
27
                bool found = false;
3982
87
                for (auto& small_file_entry : *small_file_entries) {
3983
87
                    if (small_file_entry.path() == small_file_info.small_file_path) {
3984
27
                        if (!small_file_entry.deleted()) {
3985
27
                            small_file_entry.set_deleted(true);
3986
27
                            if (!small_file_entry.corrected()) {
3987
27
                                small_file_entry.set_corrected(true);
3988
27
                            }
3989
27
                            ++changed_files;
3990
27
                        } else {
3991
0
                            ++already_deleted;
3992
0
                        }
3993
27
                        found = true;
3994
27
                        break;
3995
27
                    }
3996
87
                }
3997
27
                if (!found) {
3998
0
                    ++missing_entries;
3999
0
                    LOG_WARNING("packed file info missing small file entry")
4000
0
                            .tag("instance_id", instance_id_)
4001
0
                            .tag("packed_file_path", packed_file_path)
4002
0
                            .tag("small_file_path", small_file_info.small_file_path)
4003
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4004
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
4005
0
                }
4006
27
            }
4007
4008
24
            if (changed_files == 0) {
4009
0
                LOG_INFO("skip merge file update: no merge entries changed")
4010
0
                        .tag("instance_id", instance_id_)
4011
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4012
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4013
0
                        .tag("merged_file_path", packed_file_path)
4014
0
                        .tag("missing_entries", missing_entries)
4015
0
                        .tag("already_deleted", already_deleted)
4016
0
                        .tag("requested_small_files", small_files.size())
4017
0
                        .tag("merge_entries", packed_info.slices_size());
4018
0
                success = true;
4019
0
                break;
4020
0
            }
4021
4022
            // Calculate remaining files
4023
24
            int64_t left_file_count = 0;
4024
24
            int64_t left_file_bytes = 0;
4025
141
            for (const auto& small_file_entry : packed_info.slices()) {
4026
141
                if (!small_file_entry.deleted()) {
4027
57
                    ++left_file_count;
4028
57
                    left_file_bytes += small_file_entry.size();
4029
57
                }
4030
141
            }
4031
24
            packed_info.set_remaining_slice_bytes(left_file_bytes);
4032
24
            packed_info.set_ref_cnt(left_file_count);
4033
24
            LOG_INFO("updated packed file reference info")
4034
24
                    .tag("instance_id", instance_id_)
4035
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4036
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
4037
24
                    .tag("packed_file_path", packed_file_path)
4038
24
                    .tag("ref_cnt", left_file_count)
4039
24
                    .tag("left_file_bytes", left_file_bytes);
4040
4041
24
            if (left_file_count == 0) {
4042
7
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
4043
7
            }
4044
4045
24
            std::string updated_val;
4046
24
            if (!packed_info.SerializeToString(&updated_val)) {
4047
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
4048
0
                        .tag("instance_id", instance_id_)
4049
0
                        .tag("packed_file_path", packed_file_path)
4050
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4051
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
4052
0
                ret = -1;
4053
0
                break;
4054
0
            }
4055
4056
24
            txn->put(packed_key, updated_val);
4057
24
            err = txn->commit();
4058
24
            if (err == TxnErrorCode::TXN_OK) {
4059
24
                success = true;
4060
24
                if (left_file_count == 0) {
4061
7
                    LOG_INFO("packed file ready to delete, deleting immediately")
4062
7
                            .tag("instance_id", instance_id_)
4063
7
                            .tag("packed_file_path", packed_file_path);
4064
7
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4065
0
                        ret = -1;
4066
0
                    }
4067
7
                }
4068
24
                break;
4069
24
            }
4070
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
4071
0
                if (attempt >= max_retry_times) {
4072
0
                    LOG_WARNING("packed file info update conflict after max retry")
4073
0
                            .tag("instance_id", instance_id_)
4074
0
                            .tag("packed_file_path", packed_file_path)
4075
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4076
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
4077
0
                            .tag("changed_files", changed_files)
4078
0
                            .tag("attempt", attempt);
4079
0
                    ret = -1;
4080
0
                    break;
4081
0
                }
4082
0
                LOG_WARNING("packed file info update conflict, retrying")
4083
0
                        .tag("instance_id", instance_id_)
4084
0
                        .tag("packed_file_path", packed_file_path)
4085
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4086
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4087
0
                        .tag("changed_files", changed_files)
4088
0
                        .tag("attempt", attempt);
4089
0
                sleep_for_packed_file_retry();
4090
0
                continue;
4091
0
            }
4092
4093
0
            LOG_WARNING("failed to commit packed file info update")
4094
0
                    .tag("instance_id", instance_id_)
4095
0
                    .tag("packed_file_path", packed_file_path)
4096
0
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4097
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
4098
0
                    .tag("err", err)
4099
0
                    .tag("changed_files", changed_files);
4100
0
            ret = -1;
4101
0
            break;
4102
0
        }
4103
4104
24
        if (!success) {
4105
0
            ret = -1;
4106
0
        }
4107
24
    }
4108
4109
13
    return ret;
4110
13
}
4111
4112
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(
4113
        int64_t tablet_id, const std::string& rowset_id,
4114
58.5k
        DeleteBitmapStorageType* out_storage_type) {
4115
58.5k
    if (out_storage_type) {
4116
58.5k
        *out_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4117
58.5k
    }
4118
4119
    // Get delete bitmap storage info from FDB
4120
58.5k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4121
58.5k
    std::unique_ptr<Transaction> txn;
4122
58.5k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
4123
58.5k
    if (err != TxnErrorCode::TXN_OK) {
4124
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
4125
0
                .tag("instance_id", instance_id_)
4126
0
                .tag("tablet_id", tablet_id)
4127
0
                .tag("rowset_id", rowset_id)
4128
0
                .tag("err", err);
4129
0
        return -1;
4130
0
    }
4131
4132
58.5k
    ValueBuf dbm_val;
4133
58.5k
    err = cloud::blob_get(txn.get(), dbm_key, &dbm_val);
4134
58.5k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4135
        // No delete bitmap for this rowset, nothing to do
4136
4.92k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
4137
4.92k
                .tag("instance_id", instance_id_)
4138
4.92k
                .tag("tablet_id", tablet_id)
4139
4.92k
                .tag("rowset_id", rowset_id);
4140
4.92k
        return 0;
4141
4.92k
    }
4142
53.5k
    if (err != TxnErrorCode::TXN_OK) {
4143
0
        LOG_WARNING("failed to get delete bitmap storage")
4144
0
                .tag("instance_id", instance_id_)
4145
0
                .tag("tablet_id", tablet_id)
4146
0
                .tag("rowset_id", rowset_id)
4147
0
                .tag("err", err);
4148
0
        return -1;
4149
0
    }
4150
4151
53.5k
    DeleteBitmapStoragePB storage;
4152
53.5k
    if (!dbm_val.to_pb(&storage)) {
4153
0
        LOG_WARNING("failed to parse delete bitmap storage")
4154
0
                .tag("instance_id", instance_id_)
4155
0
                .tag("tablet_id", tablet_id)
4156
0
                .tag("rowset_id", rowset_id);
4157
0
        return -1;
4158
0
    }
4159
4160
53.5k
    if (storage.store_in_fdb()) {
4161
0
        if (out_storage_type) {
4162
0
            *out_storage_type = DeleteBitmapStorageType::IN_FDB;
4163
0
        }
4164
0
        return 0;
4165
0
    }
4166
4167
    // Check if delete bitmap is stored in standalone file.
4168
53.5k
    if (!storage.has_packed_slice_location() ||
4169
53.5k
        storage.packed_slice_location().packed_file_path().empty()) {
4170
53.5k
        if (out_storage_type) {
4171
53.5k
            *out_storage_type = DeleteBitmapStorageType::STANDALONE_FILE;
4172
53.5k
        }
4173
53.5k
        return 0;
4174
53.5k
    }
4175
4176
18.4E
    if (out_storage_type) {
4177
0
        *out_storage_type = DeleteBitmapStorageType::PACKED_FILE;
4178
0
    }
4179
4180
18.4E
    const auto& packed_loc = storage.packed_slice_location();
4181
18.4E
    const std::string& packed_file_path = packed_loc.packed_file_path();
4182
4183
18.4E
    LOG_INFO("decrementing delete bitmap packed file ref count")
4184
18.4E
            .tag("instance_id", instance_id_)
4185
18.4E
            .tag("tablet_id", tablet_id)
4186
18.4E
            .tag("rowset_id", rowset_id)
4187
18.4E
            .tag("packed_file_path", packed_file_path);
4188
4189
18.4E
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
4190
18.4E
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4191
0
        std::unique_ptr<Transaction> update_txn;
4192
0
        err = txn_kv_->create_txn(&update_txn);
4193
0
        if (err != TxnErrorCode::TXN_OK) {
4194
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
4195
0
                    .tag("instance_id", instance_id_)
4196
0
                    .tag("tablet_id", tablet_id)
4197
0
                    .tag("rowset_id", rowset_id)
4198
0
                    .tag("err", err);
4199
0
            return -1;
4200
0
        }
4201
4202
0
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
4203
0
        std::string packed_val;
4204
0
        err = update_txn->get(packed_key, &packed_val);
4205
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4206
0
            LOG_WARNING("packed file info not found for delete bitmap")
4207
0
                    .tag("instance_id", instance_id_)
4208
0
                    .tag("tablet_id", tablet_id)
4209
0
                    .tag("rowset_id", rowset_id)
4210
0
                    .tag("packed_file_path", packed_file_path);
4211
0
            return 0;
4212
0
        }
4213
0
        if (err != TxnErrorCode::TXN_OK) {
4214
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
4215
0
                    .tag("instance_id", instance_id_)
4216
0
                    .tag("tablet_id", tablet_id)
4217
0
                    .tag("rowset_id", rowset_id)
4218
0
                    .tag("packed_file_path", packed_file_path)
4219
0
                    .tag("err", err);
4220
0
            return -1;
4221
0
        }
4222
4223
0
        cloud::PackedFileInfoPB packed_info;
4224
0
        if (!packed_info.ParseFromString(packed_val)) {
4225
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
4226
0
                    .tag("instance_id", instance_id_)
4227
0
                    .tag("tablet_id", tablet_id)
4228
0
                    .tag("rowset_id", rowset_id)
4229
0
                    .tag("packed_file_path", packed_file_path);
4230
0
            return -1;
4231
0
        }
4232
4233
        // Find and mark the small file entry as deleted
4234
        // Use tablet_id and rowset_id to match entry instead of path,
4235
        // because path format may vary with path_version (with or without shard prefix)
4236
0
        auto* entries = packed_info.mutable_slices();
4237
0
        bool found = false;
4238
0
        bool already_deleted = false;
4239
0
        for (auto& entry : *entries) {
4240
0
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
4241
0
                if (!entry.deleted()) {
4242
0
                    entry.set_deleted(true);
4243
0
                    if (!entry.corrected()) {
4244
0
                        entry.set_corrected(true);
4245
0
                    }
4246
0
                } else {
4247
0
                    already_deleted = true;
4248
0
                }
4249
0
                found = true;
4250
0
                break;
4251
0
            }
4252
0
        }
4253
4254
0
        if (!found) {
4255
0
            LOG_WARNING("delete bitmap entry not found in packed file")
4256
0
                    .tag("instance_id", instance_id_)
4257
0
                    .tag("tablet_id", tablet_id)
4258
0
                    .tag("rowset_id", rowset_id)
4259
0
                    .tag("packed_file_path", packed_file_path);
4260
0
            return 0;
4261
0
        }
4262
4263
0
        if (already_deleted) {
4264
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
4265
0
                    .tag("instance_id", instance_id_)
4266
0
                    .tag("tablet_id", tablet_id)
4267
0
                    .tag("rowset_id", rowset_id)
4268
0
                    .tag("packed_file_path", packed_file_path);
4269
0
            return 0;
4270
0
        }
4271
4272
        // Calculate remaining files
4273
0
        int64_t left_file_count = 0;
4274
0
        int64_t left_file_bytes = 0;
4275
0
        for (const auto& entry : packed_info.slices()) {
4276
0
            if (!entry.deleted()) {
4277
0
                ++left_file_count;
4278
0
                left_file_bytes += entry.size();
4279
0
            }
4280
0
        }
4281
0
        packed_info.set_remaining_slice_bytes(left_file_bytes);
4282
0
        packed_info.set_ref_cnt(left_file_count);
4283
4284
0
        if (left_file_count == 0) {
4285
0
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
4286
0
        }
4287
4288
0
        std::string updated_val;
4289
0
        if (!packed_info.SerializeToString(&updated_val)) {
4290
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
4291
0
                    .tag("instance_id", instance_id_)
4292
0
                    .tag("tablet_id", tablet_id)
4293
0
                    .tag("rowset_id", rowset_id)
4294
0
                    .tag("packed_file_path", packed_file_path);
4295
0
            return -1;
4296
0
        }
4297
4298
0
        update_txn->put(packed_key, updated_val);
4299
0
        err = update_txn->commit();
4300
0
        if (err == TxnErrorCode::TXN_OK) {
4301
0
            LOG_INFO("delete bitmap packed file ref count decremented")
4302
0
                    .tag("instance_id", instance_id_)
4303
0
                    .tag("tablet_id", tablet_id)
4304
0
                    .tag("rowset_id", rowset_id)
4305
0
                    .tag("packed_file_path", packed_file_path)
4306
0
                    .tag("left_file_count", left_file_count);
4307
0
            if (left_file_count == 0) {
4308
0
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4309
0
                    return -1;
4310
0
                }
4311
0
            }
4312
0
            return 0;
4313
0
        }
4314
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4315
0
            if (attempt >= max_retry_times) {
4316
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
4317
0
                        .tag("instance_id", instance_id_)
4318
0
                        .tag("tablet_id", tablet_id)
4319
0
                        .tag("rowset_id", rowset_id)
4320
0
                        .tag("packed_file_path", packed_file_path)
4321
0
                        .tag("attempt", attempt);
4322
0
                return -1;
4323
0
            }
4324
0
            sleep_for_packed_file_retry();
4325
0
            continue;
4326
0
        }
4327
4328
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
4329
0
                .tag("instance_id", instance_id_)
4330
0
                .tag("tablet_id", tablet_id)
4331
0
                .tag("rowset_id", rowset_id)
4332
0
                .tag("packed_file_path", packed_file_path)
4333
0
                .tag("err", err);
4334
0
        return -1;
4335
0
    }
4336
4337
18.4E
    return -1;
4338
18.4E
}
4339
4340
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
4341
                                                const std::string& packed_key,
4342
7
                                                const cloud::PackedFileInfoPB& packed_info) {
4343
7
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
4344
0
        LOG_WARNING("packed file missing resource id when recycling")
4345
0
                .tag("instance_id", instance_id_)
4346
0
                .tag("packed_file_path", packed_file_path);
4347
0
        return -1;
4348
0
    }
4349
4350
7
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
4351
7
    if (!accessor) {
4352
0
        LOG_WARNING("no accessor available to delete packed file")
4353
0
                .tag("instance_id", instance_id_)
4354
0
                .tag("packed_file_path", packed_file_path)
4355
0
                .tag("resource_id", packed_info.resource_id());
4356
0
        return -1;
4357
0
    }
4358
4359
7
    int del_ret = accessor->delete_file(packed_file_path);
4360
7
    if (del_ret != 0 && del_ret != 1) {
4361
0
        LOG_WARNING("failed to delete packed file")
4362
0
                .tag("instance_id", instance_id_)
4363
0
                .tag("packed_file_path", packed_file_path)
4364
0
                .tag("resource_id", resource_id)
4365
0
                .tag("ret", del_ret);
4366
0
        return -1;
4367
0
    }
4368
7
    if (del_ret == 1) {
4369
0
        LOG_INFO("packed file already removed")
4370
0
                .tag("instance_id", instance_id_)
4371
0
                .tag("packed_file_path", packed_file_path)
4372
0
                .tag("resource_id", resource_id);
4373
7
    } else {
4374
7
        LOG_INFO("deleted packed file")
4375
7
                .tag("instance_id", instance_id_)
4376
7
                .tag("packed_file_path", packed_file_path)
4377
7
                .tag("resource_id", resource_id);
4378
7
    }
4379
4380
7
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
4381
7
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4382
7
        std::unique_ptr<Transaction> del_txn;
4383
7
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
4384
7
        if (err != TxnErrorCode::TXN_OK) {
4385
0
            LOG_WARNING("failed to create txn when removing packed file kv")
4386
0
                    .tag("instance_id", instance_id_)
4387
0
                    .tag("packed_file_path", packed_file_path)
4388
0
                    .tag("attempt", attempt)
4389
0
                    .tag("err", err);
4390
0
            return -1;
4391
0
        }
4392
4393
7
        std::string latest_val;
4394
7
        err = del_txn->get(packed_key, &latest_val);
4395
7
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4396
0
            return 0;
4397
0
        }
4398
7
        if (err != TxnErrorCode::TXN_OK) {
4399
0
            LOG_WARNING("failed to re-read packed file kv before removal")
4400
0
                    .tag("instance_id", instance_id_)
4401
0
                    .tag("packed_file_path", packed_file_path)
4402
0
                    .tag("attempt", attempt)
4403
0
                    .tag("err", err);
4404
0
            return -1;
4405
0
        }
4406
4407
7
        cloud::PackedFileInfoPB latest_info;
4408
7
        if (!latest_info.ParseFromString(latest_val)) {
4409
0
            LOG_WARNING("failed to parse packed file info before removal")
4410
0
                    .tag("instance_id", instance_id_)
4411
0
                    .tag("packed_file_path", packed_file_path)
4412
0
                    .tag("attempt", attempt);
4413
0
            return -1;
4414
0
        }
4415
4416
7
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
4417
7
              latest_info.ref_cnt() == 0)) {
4418
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
4419
0
                    .tag("instance_id", instance_id_)
4420
0
                    .tag("packed_file_path", packed_file_path)
4421
0
                    .tag("attempt", attempt);
4422
0
            return 0;
4423
0
        }
4424
4425
7
        del_txn->remove(packed_key);
4426
7
        err = del_txn->commit();
4427
7
        if (err == TxnErrorCode::TXN_OK) {
4428
7
            LOG_INFO("removed packed file metadata")
4429
7
                    .tag("instance_id", instance_id_)
4430
7
                    .tag("packed_file_path", packed_file_path);
4431
7
            return 0;
4432
7
        }
4433
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4434
0
            if (attempt >= max_retry_times) {
4435
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
4436
0
                        .tag("instance_id", instance_id_)
4437
0
                        .tag("packed_file_path", packed_file_path)
4438
0
                        .tag("attempt", attempt);
4439
0
                return -1;
4440
0
            }
4441
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
4442
0
                    .tag("instance_id", instance_id_)
4443
0
                    .tag("packed_file_path", packed_file_path)
4444
0
                    .tag("attempt", attempt);
4445
0
            sleep_for_packed_file_retry();
4446
0
            continue;
4447
0
        }
4448
0
        LOG_WARNING("failed to remove packed file kv")
4449
0
                .tag("instance_id", instance_id_)
4450
0
                .tag("packed_file_path", packed_file_path)
4451
0
                .tag("attempt", attempt)
4452
0
                .tag("err", err);
4453
0
        return -1;
4454
0
    }
4455
0
    return -1;
4456
7
}
4457
4458
int InstanceRecycler::delete_rowset_data(
4459
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
4460
66
        RecyclerMetricsContext& metrics_context) {
4461
66
    int ret = 0;
4462
    // resource_id -> file_paths
4463
66
    std::map<std::string, std::vector<std::string>> resource_file_paths;
4464
    // (resource_id, tablet_id, rowset_id)
4465
66
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
4466
66
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
4467
4468
56.4k
    for (const auto& [_, rs] : rowsets) {
4469
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
4470
        // due to aborted schema change.
4471
56.4k
        if (is_formal_rowset) {
4472
3.19k
            std::lock_guard lock(recycled_tablets_mtx_);
4473
3.19k
            if (recycled_tablets_.count(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
4474
                // Tablet has been recycled and this rowset has no packed slices, so file data
4475
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
4476
                // slice info must still run to decrement packed file ref counts.
4477
0
                continue;
4478
0
            }
4479
3.19k
        }
4480
4481
56.4k
        int64_t num_segments = rs.num_segments();
4482
        // Check num_segments before accessor lookup, because empty rowsets
4483
        // (e.g. base compaction output of empty rowsets) may have no resource_id
4484
        // set. Skipping them early avoids a spurious "no such resource id" error
4485
        // that marks the entire batch as failed and prevents txn_remove from
4486
        // cleaning up recycle KV keys.
4487
56.4k
        if (num_segments <= 0) {
4488
0
            metrics_context.total_recycled_num++;
4489
0
            metrics_context.total_recycled_data_size += rs.total_disk_size();
4490
0
            continue;
4491
0
        }
4492
4493
56.4k
        auto it = accessor_map_.find(rs.resource_id());
4494
        // possible if the accessor is not initilized correctly
4495
56.4k
        if (it == accessor_map_.end()) [[unlikely]] {
4496
2.00k
            LOG_WARNING("instance has no such resource id")
4497
2.00k
                    .tag("instance_id", instance_id_)
4498
2.00k
                    .tag("resource_id", rs.resource_id());
4499
2.00k
            ret = -1;
4500
2.00k
            continue;
4501
2.00k
        }
4502
4503
54.4k
        auto& file_paths = resource_file_paths[rs.resource_id()];
4504
54.4k
        const auto& rowset_id = rs.rowset_id_v2();
4505
54.4k
        int64_t tablet_id = rs.tablet_id();
4506
54.4k
        LOG_INFO("recycle rowset merge index size")
4507
54.4k
                .tag("instance_id", instance_id_)
4508
54.4k
                .tag("tablet_id", tablet_id)
4509
54.4k
                .tag("rowset_id", rowset_id)
4510
54.4k
                .tag("merge_index_size", rs.packed_slice_locations_size());
4511
54.4k
        if (decrement_packed_file_ref_counts(rs) != 0) {
4512
0
            ret = -1;
4513
0
            continue;
4514
0
        }
4515
4516
        // Process delete bitmap - check where it's stored.
4517
54.4k
        DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4518
54.4k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
4519
54.4k
                                                           &delete_bitmap_storage_type) != 0) {
4520
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
4521
0
                    .tag("instance_id", instance_id_)
4522
0
                    .tag("tablet_id", tablet_id)
4523
0
                    .tag("rowset_id", rowset_id);
4524
0
            ret = -1;
4525
0
            continue;
4526
0
        }
4527
54.4k
        if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
4528
51.5k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
4529
51.5k
        }
4530
4531
        // Process inverted indexes
4532
54.4k
        std::vector<std::pair<int64_t, std::string>> index_ids;
4533
        // default format as v1.
4534
54.4k
        InvertedIndexStorageFormatPB index_format = rs.has_inverted_index_storage_format()
4535
54.4k
                                                            ? rs.inverted_index_storage_format()
4536
54.4k
                                                            : InvertedIndexStorageFormatPB::V1;
4537
54.4k
        int inverted_index_get_ret = 0;
4538
54.4k
        if (rs.has_tablet_schema()) {
4539
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
4540
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
4541
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
4542
53.5k
                }
4543
53.5k
            }
4544
26.8k
            if (!rs.has_inverted_index_storage_format() &&
4545
26.8k
                rs.tablet_schema().has_inverted_index_storage_format()) {
4546
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
4547
26.5k
            }
4548
27.6k
        } else {
4549
27.6k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
4550
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
4551
0
                                "instance_id="
4552
0
                             << instance_id_ << " tablet_id=" << tablet_id
4553
0
                             << " rowset_id=" << rowset_id;
4554
0
                ret = -1;
4555
0
                continue;
4556
0
            }
4557
27.6k
            InvertedIndexInfo index_info;
4558
27.6k
            inverted_index_get_ret =
4559
27.6k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
4560
27.6k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
4561
27.6k
                                     &inverted_index_get_ret);
4562
27.6k
            if (inverted_index_get_ret == 0) {
4563
27.1k
                if (!rs.has_inverted_index_storage_format()) {
4564
27.1k
                    index_format = index_info.first;
4565
27.1k
                }
4566
27.1k
                index_ids = index_info.second;
4567
27.1k
            } else if (inverted_index_get_ret == 1) {
4568
                // 1. Schema kv not found means tablet has been recycled
4569
                // Maybe some tablet recycle failed by some bugs
4570
                // We need to delete again to double check
4571
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
4572
                // because we are uncertain about the inverted index information.
4573
                // If there are inverted indexes, some data might not be deleted,
4574
                // but this is acceptable as we have made our best effort to delete the data.
4575
503
                LOG_INFO(
4576
503
                        "delete rowset data schema kv not found, need to delete again to "
4577
503
                        "double "
4578
503
                        "check")
4579
503
                        .tag("instance_id", instance_id_)
4580
503
                        .tag("tablet_id", tablet_id)
4581
503
                        .tag("rowset", rs.ShortDebugString());
4582
                // Currently index_ids is guaranteed to be empty,
4583
                // but we clear it again here as a safeguard against future code changes
4584
                // that might cause index_ids to no longer be empty
4585
503
                index_format = InvertedIndexStorageFormatPB::V2;
4586
503
                index_ids.clear();
4587
18.4E
            } else {
4588
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
4589
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4590
18.4E
                ret = -1;
4591
18.4E
                continue;
4592
18.4E
            }
4593
27.6k
        }
4594
54.4k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
4595
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
4596
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
4597
10
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
4598
10
            continue;
4599
10
        }
4600
324k
        for (int64_t i = 0; i < num_segments; ++i) {
4601
270k
            auto segment_id = rowset_segment_id(rs, i);
4602
270k
            add_file_to_delete_if_not_packed(rs, segment_path(tablet_id, rowset_id, segment_id),
4603
270k
                                             &file_paths);
4604
270k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
4605
537k
                for (const auto& index_id : index_ids) {
4606
537k
                    add_file_to_delete_if_not_packed(
4607
537k
                            rs,
4608
537k
                            inverted_index_path_v1(tablet_id, rowset_id, segment_id, index_id.first,
4609
537k
                                                   index_id.second),
4610
537k
                            &file_paths);
4611
537k
                }
4612
268k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
4613
                // try to recycle inverted index v2 when get_ret == 1
4614
                // we treat schema not found as if it has a v2 format inverted index
4615
                // to reduce chance of data leakage
4616
2.50k
                if (inverted_index_get_ret == 1) {
4617
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
4618
2.50k
                            .tag("instance_id", instance_id_)
4619
2.50k
                            .tag("inverted index v2 path",
4620
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, segment_id));
4621
2.50k
                }
4622
2.50k
                add_file_to_delete_if_not_packed(
4623
2.50k
                        rs, inverted_index_path_v2(tablet_id, rowset_id, segment_id), &file_paths);
4624
2.50k
            }
4625
270k
        }
4626
54.4k
    }
4627
4628
66
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
4629
66
                                                 "delete_rowset_data",
4630
66
                                                 [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clERKi
Line
Count
Source
4630
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
4630
57
                                                 [](const int& ret) { return ret != 0; });
4631
66
    for (auto& [resource_id, file_paths] : resource_file_paths) {
4632
53
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4633
53
            DCHECK(accessor_map_.count(*rid))
4634
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4635
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4636
53
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4637
53
                                     &accessor_map_);
4638
53
            if (!accessor_map_.contains(*rid)) {
4639
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4640
0
                        .tag("resource_id", resource_id)
4641
0
                        .tag("instance_id", instance_id_);
4642
0
                return -1;
4643
0
            }
4644
53
            auto& accessor = accessor_map_[*rid];
4645
53
            int ret = accessor->delete_files(*paths);
4646
53
            if (!ret) {
4647
                // deduplication of different files with the same rowset id
4648
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4649
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4650
53
                std::set<std::string> deleted_rowset_id;
4651
4652
53
                std::for_each(paths->begin(), paths->end(),
4653
53
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4654
862k
                               this](const std::string& path) {
4655
862k
                                  std::vector<std::string> str;
4656
862k
                                  butil::SplitString(path, '/', &str);
4657
862k
                                  std::string rowset_id;
4658
862k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4659
859k
                                      rowset_id = str.back().substr(0, pos);
4660
859k
                                  } else {
4661
3.00k
                                      if (path.find("packed_file/") != std::string::npos) {
4662
0
                                          return; // packed files do not have rowset_id encoded
4663
0
                                      }
4664
3.00k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4665
3.00k
                                      return;
4666
3.00k
                                  }
4667
859k
                                  auto rs_meta = rowsets.find(rowset_id);
4668
859k
                                  if (rs_meta != rowsets.end() &&
4669
859k
                                      !deleted_rowset_id.contains(rowset_id)) {
4670
54.4k
                                      deleted_rowset_id.emplace(rowset_id);
4671
54.4k
                                      metrics_context.total_recycled_data_size +=
4672
54.4k
                                              rs_meta->second.total_disk_size();
4673
54.4k
                                      segment_metrics_context_.total_recycled_num +=
4674
54.4k
                                              rs_meta->second.num_segments();
4675
54.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4676
54.4k
                                              rs_meta->second.total_disk_size();
4677
54.4k
                                      metrics_context.total_recycled_num++;
4678
54.4k
                                  }
4679
859k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clEvENKUlRSD_E_clESN_
Line
Count
Source
4654
7
                               this](const std::string& path) {
4655
7
                                  std::vector<std::string> str;
4656
7
                                  butil::SplitString(path, '/', &str);
4657
7
                                  std::string rowset_id;
4658
7
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4659
7
                                      rowset_id = str.back().substr(0, pos);
4660
7
                                  } else {
4661
0
                                      if (path.find("packed_file/") != std::string::npos) {
4662
0
                                          return; // packed files do not have rowset_id encoded
4663
0
                                      }
4664
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4665
0
                                      return;
4666
0
                                  }
4667
7
                                  auto rs_meta = rowsets.find(rowset_id);
4668
7
                                  if (rs_meta != rowsets.end() &&
4669
7
                                      !deleted_rowset_id.contains(rowset_id)) {
4670
7
                                      deleted_rowset_id.emplace(rowset_id);
4671
7
                                      metrics_context.total_recycled_data_size +=
4672
7
                                              rs_meta->second.total_disk_size();
4673
7
                                      segment_metrics_context_.total_recycled_num +=
4674
7
                                              rs_meta->second.num_segments();
4675
7
                                      segment_metrics_context_.total_recycled_data_size +=
4676
7
                                              rs_meta->second.total_disk_size();
4677
7
                                      metrics_context.total_recycled_num++;
4678
7
                                  }
4679
7
                              });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clEvENKUlRSD_E_clESN_
Line
Count
Source
4654
862k
                               this](const std::string& path) {
4655
862k
                                  std::vector<std::string> str;
4656
862k
                                  butil::SplitString(path, '/', &str);
4657
862k
                                  std::string rowset_id;
4658
862k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4659
859k
                                      rowset_id = str.back().substr(0, pos);
4660
859k
                                  } else {
4661
3.00k
                                      if (path.find("packed_file/") != std::string::npos) {
4662
0
                                          return; // packed files do not have rowset_id encoded
4663
0
                                      }
4664
3.00k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4665
3.00k
                                      return;
4666
3.00k
                                  }
4667
859k
                                  auto rs_meta = rowsets.find(rowset_id);
4668
859k
                                  if (rs_meta != rowsets.end() &&
4669
859k
                                      !deleted_rowset_id.contains(rowset_id)) {
4670
54.4k
                                      deleted_rowset_id.emplace(rowset_id);
4671
54.4k
                                      metrics_context.total_recycled_data_size +=
4672
54.4k
                                              rs_meta->second.total_disk_size();
4673
54.4k
                                      segment_metrics_context_.total_recycled_num +=
4674
54.4k
                                              rs_meta->second.num_segments();
4675
54.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4676
54.4k
                                              rs_meta->second.total_disk_size();
4677
54.4k
                                      metrics_context.total_recycled_num++;
4678
54.4k
                                  }
4679
859k
                              });
4680
53
            }
4681
53
            return ret;
4682
53
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clEv
Line
Count
Source
4632
6
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4633
6
            DCHECK(accessor_map_.count(*rid))
4634
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4635
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4636
6
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4637
6
                                     &accessor_map_);
4638
6
            if (!accessor_map_.contains(*rid)) {
4639
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4640
0
                        .tag("resource_id", resource_id)
4641
0
                        .tag("instance_id", instance_id_);
4642
0
                return -1;
4643
0
            }
4644
6
            auto& accessor = accessor_map_[*rid];
4645
6
            int ret = accessor->delete_files(*paths);
4646
6
            if (!ret) {
4647
                // deduplication of different files with the same rowset id
4648
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4649
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4650
6
                std::set<std::string> deleted_rowset_id;
4651
4652
6
                std::for_each(paths->begin(), paths->end(),
4653
6
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4654
6
                               this](const std::string& path) {
4655
6
                                  std::vector<std::string> str;
4656
6
                                  butil::SplitString(path, '/', &str);
4657
6
                                  std::string rowset_id;
4658
6
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4659
6
                                      rowset_id = str.back().substr(0, pos);
4660
6
                                  } else {
4661
6
                                      if (path.find("packed_file/") != std::string::npos) {
4662
6
                                          return; // packed files do not have rowset_id encoded
4663
6
                                      }
4664
6
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4665
6
                                      return;
4666
6
                                  }
4667
6
                                  auto rs_meta = rowsets.find(rowset_id);
4668
6
                                  if (rs_meta != rowsets.end() &&
4669
6
                                      !deleted_rowset_id.contains(rowset_id)) {
4670
6
                                      deleted_rowset_id.emplace(rowset_id);
4671
6
                                      metrics_context.total_recycled_data_size +=
4672
6
                                              rs_meta->second.total_disk_size();
4673
6
                                      segment_metrics_context_.total_recycled_num +=
4674
6
                                              rs_meta->second.num_segments();
4675
6
                                      segment_metrics_context_.total_recycled_data_size +=
4676
6
                                              rs_meta->second.total_disk_size();
4677
6
                                      metrics_context.total_recycled_num++;
4678
6
                                  }
4679
6
                              });
4680
6
            }
4681
6
            return ret;
4682
6
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clEv
Line
Count
Source
4632
47
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4633
47
            DCHECK(accessor_map_.count(*rid))
4634
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4635
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4636
47
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4637
47
                                     &accessor_map_);
4638
47
            if (!accessor_map_.contains(*rid)) {
4639
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4640
0
                        .tag("resource_id", resource_id)
4641
0
                        .tag("instance_id", instance_id_);
4642
0
                return -1;
4643
0
            }
4644
47
            auto& accessor = accessor_map_[*rid];
4645
47
            int ret = accessor->delete_files(*paths);
4646
47
            if (!ret) {
4647
                // deduplication of different files with the same rowset id
4648
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4649
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4650
47
                std::set<std::string> deleted_rowset_id;
4651
4652
47
                std::for_each(paths->begin(), paths->end(),
4653
47
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4654
47
                               this](const std::string& path) {
4655
47
                                  std::vector<std::string> str;
4656
47
                                  butil::SplitString(path, '/', &str);
4657
47
                                  std::string rowset_id;
4658
47
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4659
47
                                      rowset_id = str.back().substr(0, pos);
4660
47
                                  } else {
4661
47
                                      if (path.find("packed_file/") != std::string::npos) {
4662
47
                                          return; // packed files do not have rowset_id encoded
4663
47
                                      }
4664
47
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4665
47
                                      return;
4666
47
                                  }
4667
47
                                  auto rs_meta = rowsets.find(rowset_id);
4668
47
                                  if (rs_meta != rowsets.end() &&
4669
47
                                      !deleted_rowset_id.contains(rowset_id)) {
4670
47
                                      deleted_rowset_id.emplace(rowset_id);
4671
47
                                      metrics_context.total_recycled_data_size +=
4672
47
                                              rs_meta->second.total_disk_size();
4673
47
                                      segment_metrics_context_.total_recycled_num +=
4674
47
                                              rs_meta->second.num_segments();
4675
47
                                      segment_metrics_context_.total_recycled_data_size +=
4676
47
                                              rs_meta->second.total_disk_size();
4677
47
                                      metrics_context.total_recycled_num++;
4678
47
                                  }
4679
47
                              });
4680
47
            }
4681
47
            return ret;
4682
47
        });
4683
53
    }
4684
66
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
4685
10
        LOG_INFO(
4686
10
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
4687
10
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
4688
10
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
4689
10
        concurrent_delete_executor.add([&]() -> int {
4690
10
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4691
10
            if (!ret) {
4692
10
                auto rs = rowsets.at(rowset_id);
4693
10
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4694
10
                metrics_context.total_recycled_num++;
4695
10
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4696
10
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4697
10
            }
4698
10
            return ret;
4699
10
        });
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
4689
10
        concurrent_delete_executor.add([&]() -> int {
4690
10
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4691
10
            if (!ret) {
4692
10
                auto rs = rowsets.at(rowset_id);
4693
10
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4694
10
                metrics_context.total_recycled_num++;
4695
10
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4696
10
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4697
10
            }
4698
10
            return ret;
4699
10
        });
4700
10
    }
4701
4702
66
    bool finished = true;
4703
66
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4704
66
    for (int r : rets) {
4705
63
        if (r != 0) {
4706
0
            ret = -1;
4707
0
            break;
4708
0
        }
4709
63
    }
4710
66
    ret = finished ? ret : -1;
4711
66
    return ret;
4712
66
}
4713
4714
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
4715
3.58k
                                         const std::string& rowset_id) {
4716
3.58k
    auto it = accessor_map_.find(resource_id);
4717
3.58k
    if (it == accessor_map_.end()) {
4718
400
        LOG_WARNING("instance has no such resource id")
4719
400
                .tag("instance_id", instance_id_)
4720
400
                .tag("resource_id", resource_id)
4721
400
                .tag("tablet_id", tablet_id)
4722
400
                .tag("rowset_id", rowset_id);
4723
400
        return -1;
4724
400
    }
4725
3.18k
    auto& accessor = it->second;
4726
3.18k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
4727
3.58k
}
4728
4729
int InstanceRecycler::delete_versioned_delete_bitmap_kvs(int64_t tablet_id,
4730
55.5k
                                                         const std::string& rowset_id) {
4731
55.5k
    std::string dbm_start_key =
4732
55.5k
            versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4733
55.5k
    std::string dbm_end_key = dbm_start_key;
4734
55.5k
    encode_int64(INT64_MAX, &dbm_end_key);
4735
55.5k
    int ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4736
55.5k
    if (ret != 0) {
4737
0
        LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id=" << instance_id_
4738
0
                     << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4739
0
    }
4740
55.5k
    return ret;
4741
55.5k
}
4742
4743
51.2k
int InstanceRecycler::delete_delete_bitmap_kvs(int64_t tablet_id, const std::string& rowset_id) {
4744
51.2k
    std::string delete_bitmap_start =
4745
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
4746
51.2k
    std::string delete_bitmap_end =
4747
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
4748
51.2k
    int ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
4749
51.2k
    if (ret != 0) {
4750
0
        LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
4751
0
                     << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4752
0
    }
4753
51.2k
    return ret;
4754
51.2k
}
4755
4756
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
4757
4
    if (key.empty()) {
4758
0
        return false;
4759
0
    }
4760
4
    std::string_view key_view = key;
4761
4
    key_view.remove_prefix(1); // remove keyspace prefix
4762
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
4763
4
    if (decode_key(&key_view, &decoded) != 0) {
4764
0
        return false;
4765
0
    }
4766
4
    if (decoded.size() < 4) {
4767
0
        return false;
4768
0
    }
4769
4
    try {
4770
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
4771
4
    } catch (const std::bad_variant_access&) {
4772
0
        return false;
4773
0
    }
4774
4
    return true;
4775
4
}
4776
4777
14
int InstanceRecycler::recycle_packed_files() {
4778
14
    const std::string task_name = "recycle_packed_files";
4779
14
    auto start_tp = steady_clock::now();
4780
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
4781
14
    int ret = 0;
4782
14
    PackedFileRecycleStats stats;
4783
4784
14
    register_recycle_task(task_name, start_time);
4785
14
    DORIS_CLOUD_DEFER {
4786
14
        unregister_recycle_task(task_name);
4787
14
        int64_t cost =
4788
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4789
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4790
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4791
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4792
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4793
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4794
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4795
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4796
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4797
14
                                                             stats.bytes_object_deleted);
4798
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4799
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4800
14
                .tag("instance_id", instance_id_)
4801
14
                .tag("num_scanned", stats.num_scanned)
4802
14
                .tag("num_corrected", stats.num_corrected)
4803
14
                .tag("num_deleted", stats.num_deleted)
4804
14
                .tag("num_failed", stats.num_failed)
4805
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4806
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4807
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4808
14
                .tag("bytes_deleted", stats.bytes_deleted)
4809
14
                .tag("ret", ret);
4810
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
4785
14
    DORIS_CLOUD_DEFER {
4786
14
        unregister_recycle_task(task_name);
4787
14
        int64_t cost =
4788
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4789
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4790
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4791
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4792
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4793
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4794
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4795
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4796
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4797
14
                                                             stats.bytes_object_deleted);
4798
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4799
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4800
14
                .tag("instance_id", instance_id_)
4801
14
                .tag("num_scanned", stats.num_scanned)
4802
14
                .tag("num_corrected", stats.num_corrected)
4803
14
                .tag("num_deleted", stats.num_deleted)
4804
14
                .tag("num_failed", stats.num_failed)
4805
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4806
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4807
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4808
14
                .tag("bytes_deleted", stats.bytes_deleted)
4809
14
                .tag("ret", ret);
4810
14
    };
4811
4812
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4813
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4814
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4815
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
4812
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4813
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4814
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4815
4
    };
4816
4817
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
4818
4819
14
    std::string begin = packed_file_key({instance_id_, ""});
4820
14
    std::string end = packed_file_key({instance_id_, "\xff"});
4821
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
4822
0
        ret = -1;
4823
0
    }
4824
4825
14
    return ret;
4826
14
}
4827
4828
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
4829
                                                  RecyclerMetricsContext& metrics_context,
4830
0
                                                  int64_t partition_id, bool is_empty_tablet) {
4831
0
    std::string tablet_key_begin, tablet_key_end;
4832
4833
0
    if (partition_id > 0) {
4834
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
4835
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
4836
0
    } else {
4837
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
4838
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
4839
0
    }
4840
    // for calculate the total num or bytes of recyled objects
4841
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
4842
0
                                                          std::string_view v) -> int {
4843
0
        doris::TabletMetaCloudPB tablet_meta_pb;
4844
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
4845
0
            return 0;
4846
0
        }
4847
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
4848
4849
0
        if (config::enable_recycler_check_lazy_txn_finished &&
4850
0
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
4851
0
            return 0;
4852
0
        }
4853
4854
0
        if (!is_empty_tablet) {
4855
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
4856
0
                return 0;
4857
0
            }
4858
0
            tablet_metrics_context_.total_need_recycle_num++;
4859
0
        }
4860
0
        return 0;
4861
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_
4862
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
4863
0
    metrics_context.report(true);
4864
0
    tablet_metrics_context_.report(true);
4865
0
    segment_metrics_context_.report(true);
4866
0
    return ret;
4867
0
}
4868
4869
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
4870
0
                                                 RecyclerMetricsContext& metrics_context) {
4871
0
    int ret = 0;
4872
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
4873
0
    std::unique_ptr<Transaction> txn;
4874
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4875
0
        LOG_WARNING("failed to recycle tablet ")
4876
0
                .tag("tablet id", tablet_id)
4877
0
                .tag("instance_id", instance_id_)
4878
0
                .tag("reason", "failed to create txn");
4879
0
        ret = -1;
4880
0
    }
4881
0
    GetRowsetResponse resp;
4882
0
    std::string msg;
4883
0
    MetaServiceCode code = MetaServiceCode::OK;
4884
    // get rowsets in tablet
4885
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4886
0
                        tablet_id, code, msg, &resp);
4887
0
    if (code != MetaServiceCode::OK) {
4888
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4889
0
                .tag("tablet id", tablet_id)
4890
0
                .tag("msg", msg)
4891
0
                .tag("code", code)
4892
0
                .tag("instance id", instance_id_);
4893
0
        ret = -1;
4894
0
    }
4895
0
    for (const auto& rs_meta : resp.rowset_meta()) {
4896
        /*
4897
        * For compatibility, we skip the loop for [0-1] here.
4898
        * The purpose of this loop is to delete object files,
4899
        * and since [0-1] only has meta and doesn't have object files,
4900
        * skipping it doesn't affect system correctness.
4901
        *
4902
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
4903
        * would return error -1 directly, causing the recycle operation to fail.
4904
        *
4905
        * [0-1] doesn't have resource id is a bug.
4906
        * In the future, we will fix this problem, after that,
4907
        * we can remove this if statement.
4908
        *
4909
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
4910
        */
4911
4912
0
        if (rs_meta.end_version() == 1) {
4913
            // Assert that [0-1] has no resource_id to make sure
4914
            // this if statement will not be forgetted to remove
4915
            // when the resource id bug is fixed
4916
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4917
0
            continue;
4918
0
        }
4919
0
        if (!rs_meta.has_resource_id()) {
4920
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4921
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4922
0
                    .tag("instance_id", instance_id_)
4923
0
                    .tag("tablet_id", tablet_id);
4924
0
            continue;
4925
0
        }
4926
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4927
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4928
        // possible if the accessor is not initilized correctly
4929
0
        if (it == accessor_map_.end()) [[unlikely]] {
4930
0
            LOG_WARNING(
4931
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4932
0
                    "recycle process")
4933
0
                    .tag("tablet id", tablet_id)
4934
0
                    .tag("instance_id", instance_id_)
4935
0
                    .tag("resource_id", rs_meta.resource_id())
4936
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4937
0
            continue;
4938
0
        }
4939
4940
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
4941
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4942
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4943
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
4944
0
    }
4945
0
    return ret;
4946
0
}
4947
4948
4.26k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
4949
4.26k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
4950
4.26k
            .tag("instance_id", instance_id_)
4951
4.26k
            .tag("tablet_id", tablet_id);
4952
4953
4.26k
    if (should_recycle_versioned_keys()) {
4954
14
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
4955
14
        if (ret != 0) {
4956
0
            return ret;
4957
0
        }
4958
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
4959
        // during the recycle_versioned_tablet process.
4960
        //
4961
        // .. And remove restore job rowsets of this tablet too
4962
14
    }
4963
4964
4.26k
    int ret = 0;
4965
4.26k
    auto start_time = steady_clock::now();
4966
4967
4.26k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4968
4969
    // collect resource ids
4970
260
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4971
260
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4972
260
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4973
260
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4974
260
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
4975
260
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
4976
4977
260
    std::set<std::string> resource_ids;
4978
260
    int64_t recycle_rowsets_number = 0;
4979
260
    int64_t recycle_segments_number = 0;
4980
260
    int64_t recycle_rowsets_data_size = 0;
4981
260
    int64_t recycle_rowsets_index_size = 0;
4982
260
    int64_t recycle_restore_job_rowsets_number = 0;
4983
260
    int64_t recycle_restore_job_segments_number = 0;
4984
260
    int64_t recycle_restore_job_rowsets_data_size = 0;
4985
260
    int64_t recycle_restore_job_rowsets_index_size = 0;
4986
260
    int64_t max_rowset_version = 0;
4987
260
    int64_t min_rowset_creation_time = INT64_MAX;
4988
260
    int64_t max_rowset_creation_time = 0;
4989
260
    int64_t min_rowset_expiration_time = INT64_MAX;
4990
260
    int64_t max_rowset_expiration_time = 0;
4991
4992
260
    DORIS_CLOUD_DEFER {
4993
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4994
260
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4995
260
                .tag("instance_id", instance_id_)
4996
260
                .tag("tablet_id", tablet_id)
4997
260
                .tag("recycle rowsets number", recycle_rowsets_number)
4998
260
                .tag("recycle segments number", recycle_segments_number)
4999
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5000
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5001
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
5002
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
5003
260
                .tag("all restore job rowsets recycle data size",
5004
260
                     recycle_restore_job_rowsets_data_size)
5005
260
                .tag("all restore job rowsets recycle index size",
5006
260
                     recycle_restore_job_rowsets_index_size)
5007
260
                .tag("max rowset version", max_rowset_version)
5008
260
                .tag("min rowset creation time", min_rowset_creation_time)
5009
260
                .tag("max rowset creation time", max_rowset_creation_time)
5010
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
5011
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
5012
260
                .tag("task type", metrics_context.operation_type)
5013
260
                .tag("ret", ret);
5014
260
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4992
260
    DORIS_CLOUD_DEFER {
4993
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4994
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4995
260
                .tag("instance_id", instance_id_)
4996
260
                .tag("tablet_id", tablet_id)
4997
260
                .tag("recycle rowsets number", recycle_rowsets_number)
4998
260
                .tag("recycle segments number", recycle_segments_number)
4999
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5000
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5001
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
5002
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
5003
260
                .tag("all restore job rowsets recycle data size",
5004
260
                     recycle_restore_job_rowsets_data_size)
5005
260
                .tag("all restore job rowsets recycle index size",
5006
260
                     recycle_restore_job_rowsets_index_size)
5007
260
                .tag("max rowset version", max_rowset_version)
5008
260
                .tag("min rowset creation time", min_rowset_creation_time)
5009
260
                .tag("max rowset creation time", max_rowset_creation_time)
5010
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
5011
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
5012
260
                .tag("task type", metrics_context.operation_type)
5013
260
                .tag("ret", ret);
5014
260
    };
5015
5016
260
    std::unique_ptr<Transaction> txn;
5017
260
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5018
0
        LOG_WARNING("failed to recycle tablet ")
5019
0
                .tag("tablet id", tablet_id)
5020
0
                .tag("instance_id", instance_id_)
5021
0
                .tag("reason", "failed to create txn");
5022
0
        ret = -1;
5023
0
    }
5024
260
    GetRowsetResponse resp;
5025
260
    std::string msg;
5026
260
    MetaServiceCode code = MetaServiceCode::OK;
5027
    // get rowsets in tablet
5028
260
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
5029
260
                        tablet_id, code, msg, &resp);
5030
260
    if (code != MetaServiceCode::OK) {
5031
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5032
0
                .tag("tablet id", tablet_id)
5033
0
                .tag("msg", msg)
5034
0
                .tag("code", code)
5035
0
                .tag("instance id", instance_id_);
5036
0
        ret = -1;
5037
0
    }
5038
260
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
5039
5040
2.55k
    for (const auto& rs_meta : resp.rowset_meta()) {
5041
2.55k
        if (!rs_meta.has_resource_id() || rs_meta.resource_id().empty()) {
5042
3
            if (rs_meta.num_segments() <= 0) {
5043
2
                LOG_INFO("rowset meta has no segments and no resource id, skip this rowset")
5044
2
                        .tag("rs_meta", rs_meta.ShortDebugString())
5045
2
                        .tag("instance_id", instance_id_)
5046
2
                        .tag("tablet_id", tablet_id);
5047
2
                recycle_rowsets_number += 1;
5048
2
                continue;
5049
2
            }
5050
1
            LOG_WARNING("rowset meta has a missing or empty resource id, impossible!")
5051
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
5052
1
                    .tag("instance_id", instance_id_)
5053
1
                    .tag("tablet_id", tablet_id);
5054
1
            return -1;
5055
3
        }
5056
18.4E
        DCHECK(rs_meta.has_resource_id() && !rs_meta.resource_id().empty())
5057
18.4E
                << "rs_meta" << rs_meta.ShortDebugString();
5058
2.54k
        auto it = accessor_map_.find(rs_meta.resource_id());
5059
        // possible if the accessor is not initilized correctly
5060
2.54k
        if (it == accessor_map_.end()) [[unlikely]] {
5061
1
            LOG_WARNING(
5062
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5063
1
                    "recycle process")
5064
1
                    .tag("tablet id", tablet_id)
5065
1
                    .tag("instance_id", instance_id_)
5066
1
                    .tag("resource_id", rs_meta.resource_id())
5067
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5068
1
            return -1;
5069
1
        }
5070
2.54k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5071
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
5072
0
                    .tag("instance_id", instance_id_)
5073
0
                    .tag("tablet_id", tablet_id)
5074
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5075
0
            return -1;
5076
0
        }
5077
2.54k
        recycle_rowsets_number += 1;
5078
2.54k
        recycle_segments_number += rs_meta.num_segments();
5079
2.54k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5080
2.54k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5081
2.54k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5082
2.54k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5083
2.54k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5084
2.54k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5085
2.54k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5086
2.54k
        resource_ids.emplace(rs_meta.resource_id());
5087
2.54k
    }
5088
5089
    // get restore job rowset in tablet
5090
258
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
5091
258
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
5092
258
    if (code != MetaServiceCode::OK) {
5093
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
5094
0
                .tag("tablet id", tablet_id)
5095
0
                .tag("msg", msg)
5096
0
                .tag("code", code)
5097
0
                .tag("instance id", instance_id_);
5098
0
        return -1;
5099
0
    }
5100
5101
258
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
5102
0
        if (!rs_meta.has_resource_id()) {
5103
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
5104
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
5105
0
                    .tag("instance_id", instance_id_)
5106
0
                    .tag("tablet_id", tablet_id);
5107
0
            return -1;
5108
0
        }
5109
5110
0
        auto it = accessor_map_.find(rs_meta.resource_id());
5111
        // possible if the accessor is not initilized correctly
5112
0
        if (it == accessor_map_.end()) [[unlikely]] {
5113
0
            LOG_WARNING(
5114
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5115
0
                    "recycle process")
5116
0
                    .tag("tablet id", tablet_id)
5117
0
                    .tag("instance_id", instance_id_)
5118
0
                    .tag("resource_id", rs_meta.resource_id())
5119
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5120
0
            return -1;
5121
0
        }
5122
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5123
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
5124
0
                    .tag("instance_id", instance_id_)
5125
0
                    .tag("tablet_id", tablet_id)
5126
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5127
0
            return -1;
5128
0
        }
5129
0
        recycle_restore_job_rowsets_number += 1;
5130
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
5131
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
5132
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
5133
0
        resource_ids.emplace(rs_meta.resource_id());
5134
0
    }
5135
5136
258
    LOG_INFO("recycle tablet start to delete object")
5137
258
            .tag("instance id", instance_id_)
5138
258
            .tag("tablet id", tablet_id)
5139
258
            .tag("recycle tablet resource ids are",
5140
258
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
5141
258
                                 [](std::string rs_id, const auto& it) {
5142
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5143
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
5141
217
                                 [](std::string rs_id, const auto& it) {
5142
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5143
217
                                 }));
5144
5145
258
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
5146
258
            _thread_pool_group.s3_producer_pool,
5147
258
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5148
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
5148
208
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
5149
5150
    // delete all rowset data in this tablet
5151
    // ATTN: there may be data leak if not all accessor initilized successfully
5152
    //       partial data deleted if the tablet is stored cross-storage vault
5153
    //       vault id is not attached to TabletMeta...
5154
258
    for (const auto& resource_id : resource_ids) {
5155
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
5156
217
        concurrent_delete_executor.add(
5157
217
                [&, rs_id = resource_id,
5158
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5159
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5160
217
                    if (res != 0) {
5161
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5162
3
                                     << " path=" << accessor_ptr->uri()
5163
3
                                     << " task type=" << metrics_context.operation_type;
5164
3
                        return std::make_pair(-1, rs_id);
5165
3
                    }
5166
214
                    return std::make_pair(0, rs_id);
5167
217
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
5158
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5159
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5160
217
                    if (res != 0) {
5161
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5162
3
                                     << " path=" << accessor_ptr->uri()
5163
3
                                     << " task type=" << metrics_context.operation_type;
5164
3
                        return std::make_pair(-1, rs_id);
5165
3
                    }
5166
214
                    return std::make_pair(0, rs_id);
5167
217
                });
5168
217
    }
5169
5170
258
    bool finished = true;
5171
258
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
5172
258
    for (auto& r : rets) {
5173
217
        if (r.first != 0) {
5174
3
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
5175
3
            ret = -1;
5176
3
        }
5177
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
5178
217
    }
5179
258
    ret = finished ? ret : -1;
5180
5181
258
    if (ret != 0) { // failed recycle tablet data
5182
3
        LOG_WARNING("ret!=0")
5183
3
                .tag("finished", finished)
5184
3
                .tag("ret", ret)
5185
3
                .tag("instance_id", instance_id_)
5186
3
                .tag("tablet_id", tablet_id);
5187
3
        return ret;
5188
3
    }
5189
5190
255
    tablet_metrics_context_.total_recycled_data_size +=
5191
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5192
255
    tablet_metrics_context_.total_recycled_num += 1;
5193
255
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5194
255
    segment_metrics_context_.total_recycled_data_size +=
5195
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5196
255
    metrics_context.total_recycled_data_size +=
5197
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5198
255
    tablet_metrics_context_.report();
5199
255
    segment_metrics_context_.report();
5200
255
    metrics_context.report();
5201
5202
255
    txn.reset();
5203
255
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5204
0
        LOG_WARNING("failed to recycle tablet ")
5205
0
                .tag("tablet id", tablet_id)
5206
0
                .tag("instance_id", instance_id_)
5207
0
                .tag("reason", "failed to create txn");
5208
0
        ret = -1;
5209
0
    }
5210
    // delete all rowset kv in this tablet
5211
255
    txn->remove(rs_key0, rs_key1);
5212
255
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5213
255
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5214
5215
    // remove delete bitmap for MoW table
5216
255
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5217
255
    txn->remove(pending_key);
5218
255
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5219
255
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5220
255
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5221
5222
255
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5223
255
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5224
255
    txn->remove(dbm_start_key, dbm_end_key);
5225
255
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5226
255
              << " end=" << hex(dbm_end_key);
5227
5228
255
    TxnErrorCode err = txn->commit();
5229
255
    if (err != TxnErrorCode::TXN_OK) {
5230
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5231
0
        ret = -1;
5232
0
    }
5233
5234
255
    if (ret == 0) {
5235
        // All object files under tablet have been deleted
5236
255
        std::lock_guard lock(recycled_tablets_mtx_);
5237
255
        recycled_tablets_.insert(tablet_id);
5238
255
    }
5239
5240
255
    return ret;
5241
258
}
5242
5243
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
5244
14
                                               RecyclerMetricsContext& metrics_context) {
5245
14
    int ret = 0;
5246
14
    auto start_time = steady_clock::now();
5247
5248
14
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
5249
5250
    // collect resource ids
5251
11
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
5252
11
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
5253
11
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
5254
11
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
5255
5256
11
    int64_t recycle_rowsets_number = 0;
5257
11
    int64_t recycle_segments_number = 0;
5258
11
    int64_t recycle_rowsets_data_size = 0;
5259
11
    int64_t recycle_rowsets_index_size = 0;
5260
11
    int64_t max_rowset_version = 0;
5261
11
    int64_t min_rowset_creation_time = INT64_MAX;
5262
11
    int64_t max_rowset_creation_time = 0;
5263
11
    int64_t min_rowset_expiration_time = INT64_MAX;
5264
11
    int64_t max_rowset_expiration_time = 0;
5265
5266
11
    DORIS_CLOUD_DEFER {
5267
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5268
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5269
11
                .tag("instance_id", instance_id_)
5270
11
                .tag("tablet_id", tablet_id)
5271
11
                .tag("recycle rowsets number", recycle_rowsets_number)
5272
11
                .tag("recycle segments number", recycle_segments_number)
5273
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5274
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5275
11
                .tag("max rowset version", max_rowset_version)
5276
11
                .tag("min rowset creation time", min_rowset_creation_time)
5277
11
                .tag("max rowset creation time", max_rowset_creation_time)
5278
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
5279
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
5280
11
                .tag("ret", ret);
5281
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
5266
11
    DORIS_CLOUD_DEFER {
5267
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5268
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5269
11
                .tag("instance_id", instance_id_)
5270
11
                .tag("tablet_id", tablet_id)
5271
11
                .tag("recycle rowsets number", recycle_rowsets_number)
5272
11
                .tag("recycle segments number", recycle_segments_number)
5273
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5274
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5275
11
                .tag("max rowset version", max_rowset_version)
5276
11
                .tag("min rowset creation time", min_rowset_creation_time)
5277
11
                .tag("max rowset creation time", max_rowset_creation_time)
5278
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
5279
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
5280
11
                .tag("ret", ret);
5281
11
    };
5282
5283
11
    std::unique_ptr<Transaction> txn;
5284
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5285
0
        LOG_WARNING("failed to recycle tablet ")
5286
0
                .tag("tablet id", tablet_id)
5287
0
                .tag("instance_id", instance_id_)
5288
0
                .tag("reason", "failed to create txn");
5289
0
        ret = -1;
5290
0
    }
5291
5292
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
5293
    // by the related operation logs.
5294
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
5295
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
5296
11
    MetaReader meta_reader(instance_id_);
5297
11
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
5298
11
    if (err == TxnErrorCode::TXN_OK) {
5299
11
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
5300
11
    }
5301
11
    if (err != TxnErrorCode::TXN_OK) {
5302
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5303
0
                .tag("tablet id", tablet_id)
5304
0
                .tag("err", err)
5305
0
                .tag("instance id", instance_id_);
5306
0
        ret = -1;
5307
0
    }
5308
5309
11
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
5310
11
             load_rowset_metas.size(), compact_rowset_metas.size())
5311
11
            .tag("instance_id", instance_id_)
5312
11
            .tag("tablet_id", tablet_id);
5313
5314
11
    SyncExecutor<int> concurrent_delete_executor(
5315
11
            _thread_pool_group.s3_producer_pool,
5316
11
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5317
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
5318
5319
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5320
60
        recycle_rowsets_number += 1;
5321
60
        recycle_segments_number += rs_meta.num_segments();
5322
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5323
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5324
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5325
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5326
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5327
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5328
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5329
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
5319
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5320
60
        recycle_rowsets_number += 1;
5321
60
        recycle_segments_number += rs_meta.num_segments();
5322
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5323
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5324
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5325
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5326
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5327
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5328
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5329
60
    };
5330
5331
11
    std::vector<RowsetDeleteTask> all_tasks;
5332
60
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
5333
60
        update_rowset_stats(rs_meta);
5334
        // Version 0-1 rowset has no resource_id and no actual data files,
5335
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5336
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5337
60
        RowsetDeleteTask task;
5338
60
        task.rowset_meta = rs_meta;
5339
60
        task.versioned_rowset_key =
5340
60
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
5341
60
        task.non_versioned_rowset_key =
5342
60
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5343
60
        task.versionstamp = versionstamp;
5344
60
        all_tasks.push_back(std::move(task));
5345
60
    }
5346
5347
11
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
5348
0
        update_rowset_stats(rs_meta);
5349
        // Version 0-1 rowset has no resource_id and no actual data files,
5350
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5351
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5352
0
        RowsetDeleteTask task;
5353
0
        task.rowset_meta = rs_meta;
5354
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
5355
0
                {instance_id_, tablet_id, rs_meta.end_version()});
5356
0
        task.non_versioned_rowset_key =
5357
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5358
0
        task.versionstamp = versionstamp;
5359
0
        all_tasks.push_back(std::move(task));
5360
0
    }
5361
5362
11
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
5363
0
        RecycleRowsetPB recycle_rowset;
5364
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
5365
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5366
0
            return -1;
5367
0
        }
5368
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
5369
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
5370
                // in old version, keep this key-value pair and it needs to be checked manually
5371
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5372
0
                return -1;
5373
0
            }
5374
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
5375
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5376
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5377
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
5378
0
                return -1;
5379
0
            }
5380
            // decode rowset_id
5381
0
            auto k1 = k;
5382
0
            k1.remove_prefix(1);
5383
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5384
0
            decode_key(&k1, &out);
5385
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5386
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5387
0
            LOG_INFO("delete old-version rowset data")
5388
0
                    .tag("instance_id", instance_id_)
5389
0
                    .tag("tablet_id", tablet_id)
5390
0
                    .tag("rowset_id", rowset_id);
5391
5392
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
5393
            // so we must use prefix deletion directly instead of batch delete.
5394
0
            concurrent_delete_executor.add(
5395
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
5396
                        // delete by prefix, the recycle rowset key will be deleted by range later.
5397
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
5398
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
5399
0
        } else {
5400
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
5401
            // Version 0-1 rowset has no resource_id and no actual data files,
5402
            // but still needs ref_count key cleanup, so we add it to all_tasks.
5403
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
5404
0
            RowsetDeleteTask task;
5405
0
            task.rowset_meta = rowset_meta;
5406
0
            task.recycle_rowset_key = k;
5407
0
            all_tasks.push_back(std::move(task));
5408
0
        }
5409
0
        return 0;
5410
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_
5411
5412
11
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
5413
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
5414
0
                .tag("tablet id", tablet_id)
5415
0
                .tag("instance_id", instance_id_)
5416
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
5417
0
        ret = -1;
5418
0
    }
5419
5420
    // Phase 1: Classify tasks by ref_count
5421
11
    std::vector<RowsetDeleteTask> batch_delete_tasks;
5422
60
    for (auto& task : all_tasks) {
5423
60
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
5424
60
        if (classify_ret < 0) {
5425
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
5426
0
                    .tag("instance_id", instance_id_)
5427
0
                    .tag("tablet_id", tablet_id)
5428
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5429
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
5430
0
                return recycle_rowset_meta_and_data(t);
5431
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
5432
0
        }
5433
60
    }
5434
5435
11
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
5436
5437
11
    LOG_INFO("batch delete plan created")
5438
11
            .tag("instance_id", instance_id_)
5439
11
            .tag("tablet_id", tablet_id)
5440
11
            .tag("plan_count", batch_delete_tasks.size());
5441
5442
    // Phase 2: Execute batch delete using existing delete_rowset_data
5443
11
    if (!batch_delete_tasks.empty()) {
5444
10
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
5445
49
        for (const auto& task : batch_delete_tasks) {
5446
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
5447
49
            if (task.rowset_meta.resource_id().empty()) {
5448
10
                LOG_INFO("skip rowset with empty resource_id in batch delete")
5449
10
                        .tag("instance_id", instance_id_)
5450
10
                        .tag("tablet_id", tablet_id)
5451
10
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5452
10
                continue;
5453
10
            }
5454
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
5455
39
        }
5456
5457
        // Only call delete_rowset_data if there are rowsets with actual data to delete
5458
10
        bool delete_success = true;
5459
10
        if (!rowsets_to_delete.empty()) {
5460
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
5461
9
                                                         "batch_delete_versioned_tablet");
5462
9
            int delete_ret = delete_rowset_data(
5463
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
5464
9
            if (delete_ret != 0) {
5465
0
                LOG_WARNING("batch delete execution failed")
5466
0
                        .tag("instance_id", instance_id_)
5467
0
                        .tag("tablet_id", tablet_id);
5468
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
5469
0
                ret = -1;
5470
0
                delete_success = false;
5471
0
            }
5472
9
        }
5473
5474
        // Phase 3: Only cleanup metadata if data deletion succeeded.
5475
        // If deletion failed, keep recycle_rowset_key so next round will retry.
5476
10
        if (delete_success) {
5477
10
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
5478
10
            if (cleanup_ret != 0) {
5479
0
                LOG_WARNING("batch delete cleanup failed")
5480
0
                        .tag("instance_id", instance_id_)
5481
0
                        .tag("tablet_id", tablet_id);
5482
0
                ret = -1;
5483
0
            }
5484
10
        }
5485
10
    }
5486
5487
    // Always wait for fallback tasks to complete before returning
5488
11
    bool finished = true;
5489
11
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
5490
11
    for (int r : rets) {
5491
0
        if (r != 0) {
5492
0
            ret = -1;
5493
0
        }
5494
0
    }
5495
5496
11
    ret = finished ? ret : -1;
5497
5498
11
    if (ret != 0) { // failed recycle tablet data
5499
0
        LOG_WARNING("recycle versioned tablet failed")
5500
0
                .tag("finished", finished)
5501
0
                .tag("ret", ret)
5502
0
                .tag("instance_id", instance_id_)
5503
0
                .tag("tablet_id", tablet_id);
5504
0
        return ret;
5505
0
    }
5506
5507
11
    tablet_metrics_context_.total_recycled_data_size +=
5508
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5509
11
    tablet_metrics_context_.total_recycled_num += 1;
5510
11
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5511
11
    segment_metrics_context_.total_recycled_data_size +=
5512
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5513
11
    metrics_context.total_recycled_data_size +=
5514
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5515
11
    tablet_metrics_context_.report();
5516
11
    segment_metrics_context_.report();
5517
11
    metrics_context.report();
5518
5519
11
    txn.reset();
5520
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5521
0
        LOG_WARNING("failed to recycle tablet ")
5522
0
                .tag("tablet id", tablet_id)
5523
0
                .tag("instance_id", instance_id_)
5524
0
                .tag("reason", "failed to create txn");
5525
0
        ret = -1;
5526
0
    }
5527
    // delete all rowset kv in this tablet
5528
11
    txn->remove(rs_key0, rs_key1);
5529
11
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5530
5531
    // remove delete bitmap for MoW table
5532
11
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5533
11
    txn->remove(pending_key);
5534
11
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5535
11
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5536
11
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5537
5538
11
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5539
11
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5540
11
    txn->remove(dbm_start_key, dbm_end_key);
5541
11
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5542
11
              << " end=" << hex(dbm_end_key);
5543
5544
11
    std::string versioned_idx_key = versioned::tablet_index_key({instance_id_, tablet_id});
5545
11
    std::string tablet_index_val;
5546
11
    err = txn->get(versioned_idx_key, &tablet_index_val);
5547
11
    if (err != TxnErrorCode::TXN_KEY_NOT_FOUND && err != TxnErrorCode::TXN_OK) {
5548
0
        LOG_WARNING("failed to get tablet index kv")
5549
0
                .tag("instance_id", instance_id_)
5550
0
                .tag("tablet_id", tablet_id)
5551
0
                .tag("err", err);
5552
0
        ret = -1;
5553
11
    } else if (err == TxnErrorCode::TXN_OK) {
5554
        // If the tablet index kv exists, we need to delete it
5555
10
        TabletIndexPB tablet_index_pb;
5556
10
        if (!tablet_index_pb.ParseFromString(tablet_index_val)) {
5557
0
            LOG_WARNING("failed to parse tablet index pb")
5558
0
                    .tag("instance_id", instance_id_)
5559
0
                    .tag("tablet_id", tablet_id);
5560
0
            ret = -1;
5561
10
        } else {
5562
10
            std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
5563
10
                    {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
5564
10
                     tablet_index_pb.index_id(), tablet_index_pb.partition_id(), tablet_id});
5565
10
            txn->remove(versioned_inverted_idx_key);
5566
10
            txn->remove(versioned_idx_key);
5567
10
        }
5568
10
    }
5569
5570
11
    err = txn->commit();
5571
11
    if (err != TxnErrorCode::TXN_OK) {
5572
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5573
0
        ret = -1;
5574
0
    }
5575
5576
11
    if (ret == 0) {
5577
        // All object files under tablet have been deleted
5578
11
        std::lock_guard lock(recycled_tablets_mtx_);
5579
11
        recycled_tablets_.insert(tablet_id);
5580
11
    }
5581
5582
11
    return ret;
5583
11
}
5584
5585
87
int InstanceRecycler::recycle_rowsets() {
5586
87
    if (should_recycle_versioned_keys()) {
5587
5
        return recycle_versioned_rowsets();
5588
5
    }
5589
5590
82
    const std::string task_name = "recycle_rowsets";
5591
82
    int64_t num_scanned = 0;
5592
82
    int64_t num_expired = 0;
5593
82
    int64_t num_prepare = 0;
5594
82
    int64_t num_compacted = 0;
5595
82
    int64_t num_empty_rowset = 0;
5596
82
    size_t total_rowset_key_size = 0;
5597
82
    size_t total_rowset_value_size = 0;
5598
82
    size_t expired_rowset_size = 0;
5599
82
    std::atomic_long num_recycled = 0;
5600
82
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5601
5602
82
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5603
82
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5604
82
    std::string recyc_rs_key0;
5605
82
    std::string recyc_rs_key1;
5606
82
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5607
82
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5608
5609
82
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5610
5611
82
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5612
82
    register_recycle_task(task_name, start_time);
5613
5614
82
    DORIS_CLOUD_DEFER {
5615
82
        unregister_recycle_task(task_name);
5616
82
        int64_t cost =
5617
82
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5618
82
        metrics_context.finish_report();
5619
82
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5620
82
                .tag("instance_id", instance_id_)
5621
82
                .tag("num_scanned", num_scanned)
5622
82
                .tag("num_expired", num_expired)
5623
82
                .tag("num_recycled", num_recycled)
5624
82
                .tag("num_recycled.prepare", num_prepare)
5625
82
                .tag("num_recycled.compacted", num_compacted)
5626
82
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5627
82
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5628
82
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5629
82
                .tag("expired_rowset_meta_size", expired_rowset_size);
5630
82
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5614
7
    DORIS_CLOUD_DEFER {
5615
7
        unregister_recycle_task(task_name);
5616
7
        int64_t cost =
5617
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5618
7
        metrics_context.finish_report();
5619
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5620
7
                .tag("instance_id", instance_id_)
5621
7
                .tag("num_scanned", num_scanned)
5622
7
                .tag("num_expired", num_expired)
5623
7
                .tag("num_recycled", num_recycled)
5624
7
                .tag("num_recycled.prepare", num_prepare)
5625
7
                .tag("num_recycled.compacted", num_compacted)
5626
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5627
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5628
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5629
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
5630
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5614
75
    DORIS_CLOUD_DEFER {
5615
75
        unregister_recycle_task(task_name);
5616
75
        int64_t cost =
5617
75
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5618
75
        metrics_context.finish_report();
5619
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5620
75
                .tag("instance_id", instance_id_)
5621
75
                .tag("num_scanned", num_scanned)
5622
75
                .tag("num_expired", num_expired)
5623
75
                .tag("num_recycled", num_recycled)
5624
75
                .tag("num_recycled.prepare", num_prepare)
5625
75
                .tag("num_recycled.compacted", num_compacted)
5626
75
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5627
75
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5628
75
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5629
75
                .tag("expired_rowset_meta_size", expired_rowset_size);
5630
75
    };
5631
5632
82
    struct RecycleRowsetEntry {
5633
82
        std::string key;
5634
82
        doris::RowsetMetaCloudPB meta;
5635
82
    };
5636
82
    struct RecycleRowsetDeleteJob {
5637
82
        std::vector<std::string> keys;
5638
82
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
5639
82
    };
5640
    // Store the scanned recycle key with rowset meta. The scanned key is the actual KV key to delete.
5641
82
    std::vector<RecycleRowsetEntry> rowsets;
5642
82
    int64_t current_tablet_id = -1;
5643
82
    int64_t recycled_rowset_count_for_current_tablet = 0;
5644
82
    bool current_tablet_skip_logged = false;
5645
82
    std::string next_scan_begin;
5646
82
    const int64_t rowset_batch_size_per_tablet =
5647
82
            std::max(1, config::recycle_rowsets_per_tablet_batch_size);
5648
82
    const int64_t delete_rowset_batch_size =
5649
82
            std::min(500000, config::recycle_rowsets_delete_batch_size);
5650
4.33k
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5651
4.33k
        if (current_tablet_id != tablet_id) {
5652
48
            current_tablet_id = tablet_id;
5653
48
            recycled_rowset_count_for_current_tablet = 0;
5654
48
            current_tablet_skip_logged = false;
5655
48
        }
5656
4.33k
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5657
7
            if (!current_tablet_skip_logged) {
5658
7
                LOG_INFO(
5659
7
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5660
7
                        .tag("instance_id", instance_id_)
5661
7
                        .tag("tablet_id", tablet_id)
5662
7
                        .tag("limit", rowset_batch_size_per_tablet);
5663
7
                current_tablet_skip_logged = true;
5664
7
            }
5665
7
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5666
7
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5667
7
            return false;
5668
7
        }
5669
4.32k
        ++recycled_rowset_count_for_current_tablet;
5670
4.32k
        return true;
5671
4.33k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_6clEl
Line
Count
Source
5650
7
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5651
7
        if (current_tablet_id != tablet_id) {
5652
7
            current_tablet_id = tablet_id;
5653
7
            recycled_rowset_count_for_current_tablet = 0;
5654
7
            current_tablet_skip_logged = false;
5655
7
        }
5656
7
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5657
0
            if (!current_tablet_skip_logged) {
5658
0
                LOG_INFO(
5659
0
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5660
0
                        .tag("instance_id", instance_id_)
5661
0
                        .tag("tablet_id", tablet_id)
5662
0
                        .tag("limit", rowset_batch_size_per_tablet);
5663
0
                current_tablet_skip_logged = true;
5664
0
            }
5665
0
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5666
0
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5667
0
            return false;
5668
0
        }
5669
7
        ++recycled_rowset_count_for_current_tablet;
5670
7
        return true;
5671
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_6clEl
Line
Count
Source
5650
4.32k
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5651
4.32k
        if (current_tablet_id != tablet_id) {
5652
41
            current_tablet_id = tablet_id;
5653
41
            recycled_rowset_count_for_current_tablet = 0;
5654
41
            current_tablet_skip_logged = false;
5655
41
        }
5656
4.32k
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5657
7
            if (!current_tablet_skip_logged) {
5658
7
                LOG_INFO(
5659
7
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5660
7
                        .tag("instance_id", instance_id_)
5661
7
                        .tag("tablet_id", tablet_id)
5662
7
                        .tag("limit", rowset_batch_size_per_tablet);
5663
7
                current_tablet_skip_logged = true;
5664
7
            }
5665
7
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5666
7
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5667
7
            return false;
5668
7
        }
5669
4.32k
        ++recycled_rowset_count_for_current_tablet;
5670
4.32k
        return true;
5671
4.32k
    };
5672
4.33k
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5673
4.33k
        if (next_scan_begin.empty()) {
5674
4.32k
            return false;
5675
4.32k
        }
5676
7
        *begin = std::move(next_scan_begin);
5677
7
        next_scan_begin.clear();
5678
7
        return true;
5679
4.33k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clEPNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5672
7
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5673
7
        if (next_scan_begin.empty()) {
5674
7
            return false;
5675
7
        }
5676
0
        *begin = std::move(next_scan_begin);
5677
0
        next_scan_begin.clear();
5678
0
        return true;
5679
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clEPNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5672
4.32k
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5673
4.32k
        if (next_scan_begin.empty()) {
5674
4.32k
            return false;
5675
4.32k
        }
5676
7
        *begin = std::move(next_scan_begin);
5677
7
        next_scan_begin.clear();
5678
7
        return true;
5679
4.32k
    };
5680
5681
82
    std::vector<std::string> rowset_keys_to_mark_recycled;
5682
82
    std::vector<std::string> rowset_keys_to_abort_job;
5683
5684
82
    std::mutex async_recycled_rowset_keys_mutex;
5685
82
    std::vector<std::string> async_recycled_rowset_keys;
5686
82
    std::vector<std::string> rowset_keys_without_data;
5687
82
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5688
82
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5689
82
    worker_pool->start();
5690
82
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5691
903
                                            int64_t tablet_id, const std::string& rowset_id) {
5692
        // Try to delete rowset data in background thread
5693
903
        int ret = worker_pool->submit_with_timeout(
5694
903
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5695
829
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5696
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5697
0
                        return;
5698
0
                    }
5699
829
                    std::vector<std::string> keys;
5700
829
                    {
5701
829
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5702
829
                        async_recycled_rowset_keys.push_back(std::move(key));
5703
829
                        if (async_recycled_rowset_keys.size() > 100) {
5704
5
                            keys.swap(async_recycled_rowset_keys);
5705
5
                        }
5706
829
                    }
5707
829
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5708
829
                    if (keys.empty()) return;
5709
5
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5710
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5711
0
                                     << instance_id_;
5712
5
                    } else {
5713
5
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5714
5
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5715
5
                                           num_recycled, start_time);
5716
5
                    }
5717
5
                },
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
5694
1
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5695
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5696
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5697
0
                        return;
5698
0
                    }
5699
1
                    std::vector<std::string> keys;
5700
1
                    {
5701
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5702
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5703
1
                        if (async_recycled_rowset_keys.size() > 100) {
5704
0
                            keys.swap(async_recycled_rowset_keys);
5705
0
                        }
5706
1
                    }
5707
1
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5708
1
                    if (keys.empty()) return;
5709
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5710
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5711
0
                                     << instance_id_;
5712
0
                    } else {
5713
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5714
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5715
0
                                           num_recycled, start_time);
5716
0
                    }
5717
0
                },
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
5694
828
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5695
828
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5696
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5697
0
                        return;
5698
0
                    }
5699
828
                    std::vector<std::string> keys;
5700
828
                    {
5701
828
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5702
828
                        async_recycled_rowset_keys.push_back(std::move(key));
5703
828
                        if (async_recycled_rowset_keys.size() > 100) {
5704
5
                            keys.swap(async_recycled_rowset_keys);
5705
5
                        }
5706
828
                    }
5707
828
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5708
828
                    if (keys.empty()) return;
5709
5
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5710
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5711
0
                                     << instance_id_;
5712
5
                    } else {
5713
5
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5714
5
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5715
5
                                           num_recycled, start_time);
5716
5
                    }
5717
5
                },
5718
903
                0);
5719
903
        if (ret == 0) return 0;
5720
        // Submit task failed, delete rowset data in current thread
5721
74
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5722
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5723
0
            return -1;
5724
0
        }
5725
74
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5726
0
            return -1;
5727
0
        }
5728
74
        rowset_keys_without_data.push_back(std::move(key));
5729
74
        return 0;
5730
74
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
5691
1
                                            int64_t tablet_id, const std::string& rowset_id) {
5692
        // Try to delete rowset data in background thread
5693
1
        int ret = worker_pool->submit_with_timeout(
5694
1
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5695
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5696
1
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5697
1
                        return;
5698
1
                    }
5699
1
                    std::vector<std::string> keys;
5700
1
                    {
5701
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5702
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5703
1
                        if (async_recycled_rowset_keys.size() > 100) {
5704
1
                            keys.swap(async_recycled_rowset_keys);
5705
1
                        }
5706
1
                    }
5707
1
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5708
1
                    if (keys.empty()) return;
5709
1
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5710
1
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5711
1
                                     << instance_id_;
5712
1
                    } else {
5713
1
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5714
1
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5715
1
                                           num_recycled, start_time);
5716
1
                    }
5717
1
                },
5718
1
                0);
5719
1
        if (ret == 0) return 0;
5720
        // Submit task failed, delete rowset data in current thread
5721
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5722
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5723
0
            return -1;
5724
0
        }
5725
0
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5726
0
            return -1;
5727
0
        }
5728
0
        rowset_keys_without_data.push_back(std::move(key));
5729
0
        return 0;
5730
0
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
5691
902
                                            int64_t tablet_id, const std::string& rowset_id) {
5692
        // Try to delete rowset data in background thread
5693
902
        int ret = worker_pool->submit_with_timeout(
5694
902
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5695
902
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5696
902
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5697
902
                        return;
5698
902
                    }
5699
902
                    std::vector<std::string> keys;
5700
902
                    {
5701
902
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5702
902
                        async_recycled_rowset_keys.push_back(std::move(key));
5703
902
                        if (async_recycled_rowset_keys.size() > 100) {
5704
902
                            keys.swap(async_recycled_rowset_keys);
5705
902
                        }
5706
902
                    }
5707
902
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5708
902
                    if (keys.empty()) return;
5709
902
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5710
902
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5711
902
                                     << instance_id_;
5712
902
                    } else {
5713
902
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5714
902
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5715
902
                                           num_recycled, start_time);
5716
902
                    }
5717
902
                },
5718
902
                0);
5719
902
        if (ret == 0) return 0;
5720
        // Submit task failed, delete rowset data in current thread
5721
74
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5722
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5723
0
            return -1;
5724
0
        }
5725
74
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5726
0
            return -1;
5727
0
        }
5728
74
        rowset_keys_without_data.push_back(std::move(key));
5729
74
        return 0;
5730
74
    };
5731
5732
82
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5733
5734
4.33k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5735
4.33k
        ++num_scanned;
5736
4.33k
        total_rowset_key_size += k.size();
5737
4.33k
        total_rowset_value_size += v.size();
5738
4.33k
        RecycleRowsetPB rowset;
5739
4.33k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5740
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5741
0
            return -1;
5742
0
        }
5743
5744
4.33k
        int64_t current_time = ::time(nullptr);
5745
4.33k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5746
5747
4.33k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5748
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5749
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5750
4.33k
        if (current_time < expiration) { // not expired
5751
0
            return 0;
5752
0
        }
5753
4.33k
        ++num_expired;
5754
4.33k
        expired_rowset_size += v.size();
5755
5756
4.33k
        int64_t tablet_id =
5757
4.33k
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5758
4.33k
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5759
7
            return 0;
5760
7
        }
5761
5762
4.32k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5763
252
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5764
                // in old version, keep this key-value pair and it needs to be checked manually
5765
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5766
0
                return -1;
5767
0
            }
5768
252
            if (rowset.resource_id().empty()) [[unlikely]] {
5769
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5770
2
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5771
2
                          << hex(k) << " value=" << proto_to_json(rowset);
5772
2
                rowset_keys_without_data.emplace_back(k);
5773
2
                return 0;
5774
2
            }
5775
            // decode rowset_id
5776
250
            auto k1 = k;
5777
250
            k1.remove_prefix(1);
5778
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5779
250
            decode_key(&k1, &out);
5780
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5781
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5782
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5783
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5784
250
                      << " task_type=" << metrics_context.operation_type;
5785
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5786
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5787
0
                return -1;
5788
0
            }
5789
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5790
250
            metrics_context.total_recycled_num++;
5791
250
            segment_metrics_context_.total_recycled_data_size +=
5792
250
                    rowset.rowset_meta().total_disk_size();
5793
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5794
250
            return 0;
5795
250
        }
5796
4.07k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5797
5798
        // TODO(plat1ko): check rowset not referenced
5799
4.07k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5800
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5801
0
                LOG_INFO("recycle rowset that has empty resource id");
5802
0
            } else {
5803
                // other situations, keep this key-value pair and it needs to be checked manually
5804
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5805
0
                return -1;
5806
0
            }
5807
0
        }
5808
4.07k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5809
4.07k
                  << " tablet_id=" << rowset_meta->tablet_id()
5810
4.07k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5811
4.07k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5812
4.07k
                  << "] txn_id=" << rowset_meta->txn_id()
5813
4.07k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5814
4.07k
                  << " rowset_meta_size=" << v.size()
5815
4.07k
                  << " creation_time=" << rowset_meta->creation_time()
5816
4.07k
                  << " task_type=" << metrics_context.operation_type;
5817
4.07k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5818
938
            if (config::enable_mark_delete_rowset_before_recycle) {
5819
23
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5820
13
                    rowset_keys_to_mark_recycled.emplace_back(k);
5821
13
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5822
13
                                 "kv "
5823
13
                                 "at next turn, instance_id="
5824
13
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5825
13
                              << " version=[" << rowset_meta->start_version() << '-'
5826
13
                              << rowset_meta->end_version() << "]";
5827
13
                    return 0;
5828
13
                }
5829
23
            }
5830
5831
925
            num_prepare += 1;
5832
925
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5833
925
                rowset_meta->end_version() != 1) {
5834
273
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5835
272
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5836
272
                                 "instance_id="
5837
272
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5838
272
                              << " version=[" << rowset_meta->start_version() << '-'
5839
272
                              << rowset_meta->end_version() << "]";
5840
272
                    rowset_keys_to_abort_job.emplace_back(k);
5841
272
                    return 0;
5842
272
                }
5843
273
            }
5844
653
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5845
653
                                             rowset_meta->tablet_id(),
5846
653
                                             rowset_meta->rowset_id_v2()) != 0) {
5847
0
                return -1;
5848
0
            }
5849
3.13k
        } else {
5850
3.13k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5851
3.13k
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
5852
3.13k
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
5853
3.13k
            } else {
5854
3
                ++num_empty_rowset;
5855
3
                rowset_keys_without_data.emplace_back(k);
5856
3
            }
5857
3.13k
        }
5858
3.79k
        return 0;
5859
4.07k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5734
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5735
7
        ++num_scanned;
5736
7
        total_rowset_key_size += k.size();
5737
7
        total_rowset_value_size += v.size();
5738
7
        RecycleRowsetPB rowset;
5739
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5740
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5741
0
            return -1;
5742
0
        }
5743
5744
7
        int64_t current_time = ::time(nullptr);
5745
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5746
5747
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5748
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5749
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5750
7
        if (current_time < expiration) { // not expired
5751
0
            return 0;
5752
0
        }
5753
7
        ++num_expired;
5754
7
        expired_rowset_size += v.size();
5755
5756
7
        int64_t tablet_id =
5757
7
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5758
7
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5759
0
            return 0;
5760
0
        }
5761
5762
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5763
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5764
                // in old version, keep this key-value pair and it needs to be checked manually
5765
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5766
0
                return -1;
5767
0
            }
5768
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5769
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5770
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5771
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5772
0
                rowset_keys_without_data.emplace_back(k);
5773
0
                return 0;
5774
0
            }
5775
            // decode rowset_id
5776
0
            auto k1 = k;
5777
0
            k1.remove_prefix(1);
5778
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5779
0
            decode_key(&k1, &out);
5780
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5781
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5782
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5783
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5784
0
                      << " task_type=" << metrics_context.operation_type;
5785
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5786
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5787
0
                return -1;
5788
0
            }
5789
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5790
0
            metrics_context.total_recycled_num++;
5791
0
            segment_metrics_context_.total_recycled_data_size +=
5792
0
                    rowset.rowset_meta().total_disk_size();
5793
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5794
0
            return 0;
5795
0
        }
5796
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
5797
5798
        // TODO(plat1ko): check rowset not referenced
5799
7
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5800
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5801
0
                LOG_INFO("recycle rowset that has empty resource id");
5802
0
            } else {
5803
                // other situations, keep this key-value pair and it needs to be checked manually
5804
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5805
0
                return -1;
5806
0
            }
5807
0
        }
5808
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5809
7
                  << " tablet_id=" << rowset_meta->tablet_id()
5810
7
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5811
7
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5812
7
                  << "] txn_id=" << rowset_meta->txn_id()
5813
7
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5814
7
                  << " rowset_meta_size=" << v.size()
5815
7
                  << " creation_time=" << rowset_meta->creation_time()
5816
7
                  << " task_type=" << metrics_context.operation_type;
5817
7
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5818
7
            if (config::enable_mark_delete_rowset_before_recycle) {
5819
6
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5820
4
                    rowset_keys_to_mark_recycled.emplace_back(k);
5821
4
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5822
4
                                 "kv "
5823
4
                                 "at next turn, instance_id="
5824
4
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5825
4
                              << " version=[" << rowset_meta->start_version() << '-'
5826
4
                              << rowset_meta->end_version() << "]";
5827
4
                    return 0;
5828
4
                }
5829
6
            }
5830
5831
3
            num_prepare += 1;
5832
3
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5833
3
                rowset_meta->end_version() != 1) {
5834
2
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5835
2
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5836
2
                                 "instance_id="
5837
2
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5838
2
                              << " version=[" << rowset_meta->start_version() << '-'
5839
2
                              << rowset_meta->end_version() << "]";
5840
2
                    rowset_keys_to_abort_job.emplace_back(k);
5841
2
                    return 0;
5842
2
                }
5843
2
            }
5844
1
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5845
1
                                             rowset_meta->tablet_id(),
5846
1
                                             rowset_meta->rowset_id_v2()) != 0) {
5847
0
                return -1;
5848
0
            }
5849
1
        } else {
5850
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5851
0
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
5852
0
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
5853
0
            } else {
5854
0
                ++num_empty_rowset;
5855
0
                rowset_keys_without_data.emplace_back(k);
5856
0
            }
5857
0
        }
5858
1
        return 0;
5859
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5734
4.32k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5735
4.32k
        ++num_scanned;
5736
4.32k
        total_rowset_key_size += k.size();
5737
4.32k
        total_rowset_value_size += v.size();
5738
4.32k
        RecycleRowsetPB rowset;
5739
4.32k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5740
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5741
0
            return -1;
5742
0
        }
5743
5744
4.32k
        int64_t current_time = ::time(nullptr);
5745
4.32k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5746
5747
4.32k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5748
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5749
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5750
4.32k
        if (current_time < expiration) { // not expired
5751
0
            return 0;
5752
0
        }
5753
4.32k
        ++num_expired;
5754
4.32k
        expired_rowset_size += v.size();
5755
5756
4.32k
        int64_t tablet_id =
5757
4.32k
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5758
4.32k
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5759
7
            return 0;
5760
7
        }
5761
5762
4.32k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5763
252
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5764
                // in old version, keep this key-value pair and it needs to be checked manually
5765
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5766
0
                return -1;
5767
0
            }
5768
252
            if (rowset.resource_id().empty()) [[unlikely]] {
5769
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5770
2
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5771
2
                          << hex(k) << " value=" << proto_to_json(rowset);
5772
2
                rowset_keys_without_data.emplace_back(k);
5773
2
                return 0;
5774
2
            }
5775
            // decode rowset_id
5776
250
            auto k1 = k;
5777
250
            k1.remove_prefix(1);
5778
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5779
250
            decode_key(&k1, &out);
5780
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5781
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5782
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5783
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5784
250
                      << " task_type=" << metrics_context.operation_type;
5785
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5786
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5787
0
                return -1;
5788
0
            }
5789
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5790
250
            metrics_context.total_recycled_num++;
5791
250
            segment_metrics_context_.total_recycled_data_size +=
5792
250
                    rowset.rowset_meta().total_disk_size();
5793
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5794
250
            return 0;
5795
250
        }
5796
4.07k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5797
5798
        // TODO(plat1ko): check rowset not referenced
5799
4.07k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5800
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5801
0
                LOG_INFO("recycle rowset that has empty resource id");
5802
0
            } else {
5803
                // other situations, keep this key-value pair and it needs to be checked manually
5804
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5805
0
                return -1;
5806
0
            }
5807
0
        }
5808
4.07k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5809
4.07k
                  << " tablet_id=" << rowset_meta->tablet_id()
5810
4.07k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5811
4.07k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5812
4.07k
                  << "] txn_id=" << rowset_meta->txn_id()
5813
4.07k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5814
4.07k
                  << " rowset_meta_size=" << v.size()
5815
4.07k
                  << " creation_time=" << rowset_meta->creation_time()
5816
4.07k
                  << " task_type=" << metrics_context.operation_type;
5817
4.07k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5818
931
            if (config::enable_mark_delete_rowset_before_recycle) {
5819
17
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5820
9
                    rowset_keys_to_mark_recycled.emplace_back(k);
5821
9
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5822
9
                                 "kv "
5823
9
                                 "at next turn, instance_id="
5824
9
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5825
9
                              << " version=[" << rowset_meta->start_version() << '-'
5826
9
                              << rowset_meta->end_version() << "]";
5827
9
                    return 0;
5828
9
                }
5829
17
            }
5830
5831
922
            num_prepare += 1;
5832
922
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5833
922
                rowset_meta->end_version() != 1) {
5834
271
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5835
270
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5836
270
                                 "instance_id="
5837
270
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5838
270
                              << " version=[" << rowset_meta->start_version() << '-'
5839
270
                              << rowset_meta->end_version() << "]";
5840
270
                    rowset_keys_to_abort_job.emplace_back(k);
5841
270
                    return 0;
5842
270
                }
5843
271
            }
5844
652
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5845
652
                                             rowset_meta->tablet_id(),
5846
652
                                             rowset_meta->rowset_id_v2()) != 0) {
5847
0
                return -1;
5848
0
            }
5849
3.13k
        } else {
5850
3.13k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5851
3.13k
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
5852
3.13k
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
5853
3.13k
            } else {
5854
3
                ++num_empty_rowset;
5855
3
                rowset_keys_without_data.emplace_back(k);
5856
3
            }
5857
3.13k
        }
5858
3.79k
        return 0;
5859
4.07k
    };
5860
5861
82
    auto submit_delete_rowset_data_job = [&](std::vector<std::string> rowset_keys,
5862
82
                                             std::map<std::string, RowsetMetaCloudPB> rowsets) {
5863
23
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys),
5864
23
                             rowsets_to_delete = std::move(rowsets)]() {
5865
23
            if (!rowsets_to_delete.empty() &&
5866
23
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5867
18
                                   metrics_context) != 0) {
5868
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5869
0
                return;
5870
0
            }
5871
3.13k
            for (const auto& [_, rs] : rowsets_to_delete) {
5872
3.13k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5873
0
                    return;
5874
0
                }
5875
3.13k
            }
5876
23
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5877
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5878
0
                return;
5879
0
            }
5880
5881
23
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5882
23
        });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESt3mapIS9_NS_17RowsetMetaCloudPBESt4lessIS9_ESaISt4pairIKS9_SD_EEEENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESt3mapIS9_NS_17RowsetMetaCloudPBESt4lessIS9_ESaISt4pairIKS9_SD_EEEENKUlvE_clEv
Line
Count
Source
5864
23
                             rowsets_to_delete = std::move(rowsets)]() {
5865
23
            if (!rowsets_to_delete.empty() &&
5866
23
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5867
18
                                   metrics_context) != 0) {
5868
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5869
0
                return;
5870
0
            }
5871
3.13k
            for (const auto& [_, rs] : rowsets_to_delete) {
5872
3.13k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5873
0
                    return;
5874
0
                }
5875
3.13k
            }
5876
23
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5877
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5878
0
                return;
5879
0
            }
5880
5881
23
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5882
23
        });
5883
23
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESt3mapIS9_NS_17RowsetMetaCloudPBESt4lessIS9_ESaISt4pairIKS9_SD_EEE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESt3mapIS9_NS_17RowsetMetaCloudPBESt4lessIS9_ESaISt4pairIKS9_SD_EEE
Line
Count
Source
5862
23
                                             std::map<std::string, RowsetMetaCloudPB> rowsets) {
5863
23
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys),
5864
23
                             rowsets_to_delete = std::move(rowsets)]() {
5865
23
            if (!rowsets_to_delete.empty() &&
5866
23
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5867
23
                                   metrics_context) != 0) {
5868
23
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5869
23
                return;
5870
23
            }
5871
23
            for (const auto& [_, rs] : rowsets_to_delete) {
5872
23
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5873
23
                    return;
5874
23
                }
5875
23
            }
5876
23
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5877
23
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5878
23
                return;
5879
23
            }
5880
5881
23
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5882
23
        });
5883
23
    };
5884
5885
82
    bool scan_finished = false;
5886
144
    auto loop_done = [&]() -> int {
5887
144
        std::vector<std::string> mark_keys_to_process;
5888
144
        std::vector<std::string> abort_job_keys_to_process;
5889
144
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5890
144
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5891
144
        if (!mark_keys_to_process.empty()) {
5892
11
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5893
11
                    *worker_pool, std::move(mark_keys_to_process));
5894
11
        }
5895
144
        if (!abort_job_keys_to_process.empty()) {
5896
15
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5897
15
                                               &num_recycled);
5898
15
        }
5899
144
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
5900
62
            return 0;
5901
62
        }
5902
5903
82
        DORIS_CLOUD_DEFER {
5904
            // if return -1 in loop done, rowset info in memory is not cleared,
5905
            // it can lead to memory accumulation
5906
82
            rowset_keys_without_data.clear();
5907
82
            rowsets.clear();
5908
82
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clEvENKUlvE_clEv
Line
Count
Source
5903
7
        DORIS_CLOUD_DEFER {
5904
            // if return -1 in loop done, rowset info in memory is not cleared,
5905
            // it can lead to memory accumulation
5906
7
            rowset_keys_without_data.clear();
5907
7
            rowsets.clear();
5908
7
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clEvENKUlvE_clEv
Line
Count
Source
5903
75
        DORIS_CLOUD_DEFER {
5904
            // if return -1 in loop done, rowset info in memory is not cleared,
5905
            // it can lead to memory accumulation
5906
75
            rowset_keys_without_data.clear();
5907
75
            rowsets.clear();
5908
75
        };
5909
82
        std::random_device rd;
5910
82
        std::mt19937 g(rd());
5911
82
        std::ranges::shuffle(rowsets, g);
5912
5913
82
        std::vector<std::string> rowset_keys_to_delete;
5914
82
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
5915
        // rowset_id -> rowset_meta
5916
        // store rowset id and meta for statistics rs size when delete
5917
82
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5918
5919
82
        size_t rowsets_per_batch_size = 0;
5920
3.13k
        for (auto& rowset : rowsets) {
5921
3.13k
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
5922
3.13k
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
5923
3.13k
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
5924
3.12k
                continue;
5925
3.12k
            }
5926
5927
8
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5928
8
                                          std::move(rowsets_to_delete));
5929
8
            rowsets_per_batch_size = 0;
5930
8
            rowset_keys_to_delete.clear();
5931
8
            rowsets_to_delete.clear();
5932
8
        }
5933
5934
82
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
5935
10
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5936
10
                                          std::move(rowsets_to_delete));
5937
10
        }
5938
5939
87
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
5940
5
            auto begin = rowset_keys_without_data.begin() + i;
5941
5
            auto end = rowset_keys_without_data.begin() +
5942
5
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
5943
5
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
5944
5
                                                           std::make_move_iterator(end));
5945
5
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
5946
5
        }
5947
5948
82
        return 0;
5949
144
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clEv
Line
Count
Source
5886
14
    auto loop_done = [&]() -> int {
5887
14
        std::vector<std::string> mark_keys_to_process;
5888
14
        std::vector<std::string> abort_job_keys_to_process;
5889
14
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5890
14
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5891
14
        if (!mark_keys_to_process.empty()) {
5892
4
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5893
4
                    *worker_pool, std::move(mark_keys_to_process));
5894
4
        }
5895
14
        if (!abort_job_keys_to_process.empty()) {
5896
2
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5897
2
                                               &num_recycled);
5898
2
        }
5899
14
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
5900
7
            return 0;
5901
7
        }
5902
5903
7
        DORIS_CLOUD_DEFER {
5904
            // if return -1 in loop done, rowset info in memory is not cleared,
5905
            // it can lead to memory accumulation
5906
7
            rowset_keys_without_data.clear();
5907
7
            rowsets.clear();
5908
7
        };
5909
7
        std::random_device rd;
5910
7
        std::mt19937 g(rd());
5911
7
        std::ranges::shuffle(rowsets, g);
5912
5913
7
        std::vector<std::string> rowset_keys_to_delete;
5914
7
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
5915
        // rowset_id -> rowset_meta
5916
        // store rowset id and meta for statistics rs size when delete
5917
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5918
5919
7
        size_t rowsets_per_batch_size = 0;
5920
7
        for (auto& rowset : rowsets) {
5921
0
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
5922
0
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
5923
0
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
5924
0
                continue;
5925
0
            }
5926
5927
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5928
0
                                          std::move(rowsets_to_delete));
5929
0
            rowsets_per_batch_size = 0;
5930
0
            rowset_keys_to_delete.clear();
5931
0
            rowsets_to_delete.clear();
5932
0
        }
5933
5934
7
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
5935
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5936
0
                                          std::move(rowsets_to_delete));
5937
0
        }
5938
5939
7
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
5940
0
            auto begin = rowset_keys_without_data.begin() + i;
5941
0
            auto end = rowset_keys_without_data.begin() +
5942
0
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
5943
0
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
5944
0
                                                           std::make_move_iterator(end));
5945
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
5946
0
        }
5947
5948
7
        return 0;
5949
14
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clEv
Line
Count
Source
5886
130
    auto loop_done = [&]() -> int {
5887
130
        std::vector<std::string> mark_keys_to_process;
5888
130
        std::vector<std::string> abort_job_keys_to_process;
5889
130
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5890
130
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5891
130
        if (!mark_keys_to_process.empty()) {
5892
7
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5893
7
                    *worker_pool, std::move(mark_keys_to_process));
5894
7
        }
5895
130
        if (!abort_job_keys_to_process.empty()) {
5896
13
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5897
13
                                               &num_recycled);
5898
13
        }
5899
130
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
5900
55
            return 0;
5901
55
        }
5902
5903
75
        DORIS_CLOUD_DEFER {
5904
            // if return -1 in loop done, rowset info in memory is not cleared,
5905
            // it can lead to memory accumulation
5906
75
            rowset_keys_without_data.clear();
5907
75
            rowsets.clear();
5908
75
        };
5909
75
        std::random_device rd;
5910
75
        std::mt19937 g(rd());
5911
75
        std::ranges::shuffle(rowsets, g);
5912
5913
75
        std::vector<std::string> rowset_keys_to_delete;
5914
75
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
5915
        // rowset_id -> rowset_meta
5916
        // store rowset id and meta for statistics rs size when delete
5917
75
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5918
5919
75
        size_t rowsets_per_batch_size = 0;
5920
3.13k
        for (auto& rowset : rowsets) {
5921
3.13k
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
5922
3.13k
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
5923
3.13k
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
5924
3.12k
                continue;
5925
3.12k
            }
5926
5927
8
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5928
8
                                          std::move(rowsets_to_delete));
5929
8
            rowsets_per_batch_size = 0;
5930
8
            rowset_keys_to_delete.clear();
5931
8
            rowsets_to_delete.clear();
5932
8
        }
5933
5934
75
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
5935
10
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5936
10
                                          std::move(rowsets_to_delete));
5937
10
        }
5938
5939
80
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
5940
5
            auto begin = rowset_keys_without_data.begin() + i;
5941
5
            auto end = rowset_keys_without_data.begin() +
5942
5
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
5943
5
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
5944
5
                                                           std::make_move_iterator(end));
5945
5
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
5946
5
        }
5947
5948
75
        return 0;
5949
130
    };
5950
5951
82
    if (config::enable_recycler_stats_metrics) {
5952
0
        scan_and_statistics_rowsets();
5953
0
    }
5954
    // recycle_func and loop_done for scan and recycle
5955
82
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv), loop_done,
5956
82
                               std::move(next_scan_begin_getter));
5957
82
    scan_finished = true;
5958
    // if the size of rowsets is always less than delete_rowset_batch_size
5959
    // it need to submit the task directly
5960
    // else if the size of rowsets is greater than delete_rowset_batch_size,
5961
    // but there are residual, whether due to failed or unsuccessful cleanup, this behavior is idempotent
5962
82
    if (loop_done() != 0) {
5963
0
        ret = -1;
5964
0
    }
5965
5966
82
    worker_pool->stop();
5967
5968
82
    if (!async_recycled_rowset_keys.empty()) {
5969
6
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5970
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5971
0
            return -1;
5972
6
        } else {
5973
6
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5974
6
        }
5975
6
    }
5976
5977
    // Report final metrics after all concurrent tasks completed
5978
82
    segment_metrics_context_.report();
5979
82
    metrics_context.report();
5980
5981
82
    return ret;
5982
82
}
5983
5984
int InstanceRecycler::next_recycle_rowset_tablet_key(const std::string& instance_id,
5985
1
                                                     int64_t tablet_id, std::string* next_key) {
5986
1
    DCHECK(next_key != nullptr);
5987
1
    if (tablet_id == std::numeric_limits<int64_t>::max()) {
5988
0
        return -1;
5989
0
    }
5990
1
    *next_key = recycle_rowset_key({instance_id, tablet_id + 1, ""});
5991
1
    return 0;
5992
1
}
5993
5994
13
int InstanceRecycler::recycle_restore_jobs() {
5995
13
    const std::string task_name = "recycle_restore_jobs";
5996
13
    int64_t num_scanned = 0;
5997
13
    int64_t num_expired = 0;
5998
13
    int64_t num_recycled = 0;
5999
13
    int64_t num_aborted = 0;
6000
6001
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6002
6003
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
6004
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
6005
13
    std::string restore_job_key0;
6006
13
    std::string restore_job_key1;
6007
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
6008
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
6009
6010
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
6011
6012
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6013
13
    register_recycle_task(task_name, start_time);
6014
6015
13
    DORIS_CLOUD_DEFER {
6016
13
        unregister_recycle_task(task_name);
6017
13
        int64_t cost =
6018
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6019
13
        metrics_context.finish_report();
6020
6021
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
6022
13
                .tag("instance_id", instance_id_)
6023
13
                .tag("num_scanned", num_scanned)
6024
13
                .tag("num_expired", num_expired)
6025
13
                .tag("num_recycled", num_recycled)
6026
13
                .tag("num_aborted", num_aborted);
6027
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
6015
13
    DORIS_CLOUD_DEFER {
6016
13
        unregister_recycle_task(task_name);
6017
13
        int64_t cost =
6018
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6019
13
        metrics_context.finish_report();
6020
6021
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
6022
13
                .tag("instance_id", instance_id_)
6023
13
                .tag("num_scanned", num_scanned)
6024
13
                .tag("num_expired", num_expired)
6025
13
                .tag("num_recycled", num_recycled)
6026
13
                .tag("num_aborted", num_aborted);
6027
13
    };
6028
6029
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6030
6031
13
    std::vector<std::string_view> restore_job_keys;
6032
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
6033
41
        ++num_scanned;
6034
41
        RestoreJobCloudPB restore_job_pb;
6035
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
6036
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
6037
0
            return -1;
6038
0
        }
6039
41
        int64_t expiration =
6040
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
6041
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
6042
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
6043
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
6044
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
6045
0
                   << " state=" << restore_job_pb.state();
6046
41
        int64_t current_time = ::time(nullptr);
6047
41
        if (current_time < expiration) { // not expired
6048
0
            return 0;
6049
0
        }
6050
41
        ++num_expired;
6051
6052
41
        int64_t tablet_id = restore_job_pb.tablet_id();
6053
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
6054
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
6055
6056
41
        std::unique_ptr<Transaction> txn;
6057
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6058
41
        if (err != TxnErrorCode::TXN_OK) {
6059
0
            LOG_WARNING("failed to recycle restore job")
6060
0
                    .tag("err", err)
6061
0
                    .tag("tablet id", tablet_id)
6062
0
                    .tag("instance_id", instance_id_)
6063
0
                    .tag("reason", "failed to create txn");
6064
0
            return -1;
6065
0
        }
6066
6067
41
        std::string val;
6068
41
        err = txn->get(k, &val);
6069
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
6070
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
6071
0
            return 0;
6072
0
        }
6073
41
        if (err != TxnErrorCode::TXN_OK) {
6074
0
            LOG_WARNING("failed to get kv");
6075
0
            return -1;
6076
0
        }
6077
41
        restore_job_pb.Clear();
6078
41
        if (!restore_job_pb.ParseFromString(val)) {
6079
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
6080
0
            return -1;
6081
0
        }
6082
6083
        // PREPARED or COMMITTED, change state to DROPPED and return
6084
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
6085
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
6086
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
6087
0
            restore_job_pb.set_need_recycle_data(true);
6088
0
            txn->put(k, restore_job_pb.SerializeAsString());
6089
0
            err = txn->commit();
6090
0
            if (err != TxnErrorCode::TXN_OK) {
6091
0
                LOG_WARNING("failed to commit txn: {}", err);
6092
0
                return -1;
6093
0
            }
6094
0
            num_aborted++;
6095
0
            return 0;
6096
0
        }
6097
6098
        // Change state to RECYCLING
6099
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
6100
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
6101
21
            txn->put(k, restore_job_pb.SerializeAsString());
6102
21
            err = txn->commit();
6103
21
            if (err != TxnErrorCode::TXN_OK) {
6104
0
                LOG_WARNING("failed to commit txn: {}", err);
6105
0
                return -1;
6106
0
            }
6107
21
            return 0;
6108
21
        }
6109
6110
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
6111
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
6112
6113
        // Recycle all data associated with the restore job.
6114
        // This includes rowsets, segments, and related resources.
6115
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
6116
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
6117
0
            LOG_WARNING("failed to recycle tablet")
6118
0
                    .tag("tablet_id", tablet_id)
6119
0
                    .tag("instance_id", instance_id_);
6120
0
            return -1;
6121
0
        }
6122
6123
        // delete all restore job rowset kv
6124
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
6125
6126
20
        err = txn->commit();
6127
20
        if (err != TxnErrorCode::TXN_OK) {
6128
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
6129
0
                    .tag("err", err)
6130
0
                    .tag("tablet id", tablet_id)
6131
0
                    .tag("instance_id", instance_id_)
6132
0
                    .tag("reason", "failed to commit txn");
6133
0
            return -1;
6134
0
        }
6135
6136
20
        metrics_context.total_recycled_num = ++num_recycled;
6137
20
        metrics_context.report();
6138
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6139
20
        restore_job_keys.push_back(k);
6140
6141
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
6142
20
                  << " tablet_id=" << tablet_id;
6143
20
        return 0;
6144
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
6032
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
6033
41
        ++num_scanned;
6034
41
        RestoreJobCloudPB restore_job_pb;
6035
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
6036
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
6037
0
            return -1;
6038
0
        }
6039
41
        int64_t expiration =
6040
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
6041
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
6042
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
6043
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
6044
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
6045
0
                   << " state=" << restore_job_pb.state();
6046
41
        int64_t current_time = ::time(nullptr);
6047
41
        if (current_time < expiration) { // not expired
6048
0
            return 0;
6049
0
        }
6050
41
        ++num_expired;
6051
6052
41
        int64_t tablet_id = restore_job_pb.tablet_id();
6053
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
6054
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
6055
6056
41
        std::unique_ptr<Transaction> txn;
6057
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6058
41
        if (err != TxnErrorCode::TXN_OK) {
6059
0
            LOG_WARNING("failed to recycle restore job")
6060
0
                    .tag("err", err)
6061
0
                    .tag("tablet id", tablet_id)
6062
0
                    .tag("instance_id", instance_id_)
6063
0
                    .tag("reason", "failed to create txn");
6064
0
            return -1;
6065
0
        }
6066
6067
41
        std::string val;
6068
41
        err = txn->get(k, &val);
6069
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
6070
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
6071
0
            return 0;
6072
0
        }
6073
41
        if (err != TxnErrorCode::TXN_OK) {
6074
0
            LOG_WARNING("failed to get kv");
6075
0
            return -1;
6076
0
        }
6077
41
        restore_job_pb.Clear();
6078
41
        if (!restore_job_pb.ParseFromString(val)) {
6079
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
6080
0
            return -1;
6081
0
        }
6082
6083
        // PREPARED or COMMITTED, change state to DROPPED and return
6084
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
6085
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
6086
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
6087
0
            restore_job_pb.set_need_recycle_data(true);
6088
0
            txn->put(k, restore_job_pb.SerializeAsString());
6089
0
            err = txn->commit();
6090
0
            if (err != TxnErrorCode::TXN_OK) {
6091
0
                LOG_WARNING("failed to commit txn: {}", err);
6092
0
                return -1;
6093
0
            }
6094
0
            num_aborted++;
6095
0
            return 0;
6096
0
        }
6097
6098
        // Change state to RECYCLING
6099
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
6100
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
6101
21
            txn->put(k, restore_job_pb.SerializeAsString());
6102
21
            err = txn->commit();
6103
21
            if (err != TxnErrorCode::TXN_OK) {
6104
0
                LOG_WARNING("failed to commit txn: {}", err);
6105
0
                return -1;
6106
0
            }
6107
21
            return 0;
6108
21
        }
6109
6110
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
6111
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
6112
6113
        // Recycle all data associated with the restore job.
6114
        // This includes rowsets, segments, and related resources.
6115
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
6116
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
6117
0
            LOG_WARNING("failed to recycle tablet")
6118
0
                    .tag("tablet_id", tablet_id)
6119
0
                    .tag("instance_id", instance_id_);
6120
0
            return -1;
6121
0
        }
6122
6123
        // delete all restore job rowset kv
6124
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
6125
6126
20
        err = txn->commit();
6127
20
        if (err != TxnErrorCode::TXN_OK) {
6128
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
6129
0
                    .tag("err", err)
6130
0
                    .tag("tablet id", tablet_id)
6131
0
                    .tag("instance_id", instance_id_)
6132
0
                    .tag("reason", "failed to commit txn");
6133
0
            return -1;
6134
0
        }
6135
6136
20
        metrics_context.total_recycled_num = ++num_recycled;
6137
20
        metrics_context.report();
6138
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6139
20
        restore_job_keys.push_back(k);
6140
6141
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
6142
20
                  << " tablet_id=" << tablet_id;
6143
20
        return 0;
6144
20
    };
6145
6146
13
    auto loop_done = [&restore_job_keys, this]() -> int {
6147
3
        if (restore_job_keys.empty()) return 0;
6148
1
        DORIS_CLOUD_DEFER {
6149
1
            restore_job_keys.clear();
6150
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6148
1
        DORIS_CLOUD_DEFER {
6149
1
            restore_job_keys.clear();
6150
1
        };
6151
6152
1
        std::unique_ptr<Transaction> txn;
6153
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6154
1
        if (err != TxnErrorCode::TXN_OK) {
6155
0
            LOG_WARNING("failed to recycle restore job")
6156
0
                    .tag("err", err)
6157
0
                    .tag("instance_id", instance_id_)
6158
0
                    .tag("reason", "failed to create txn");
6159
0
            return -1;
6160
0
        }
6161
20
        for (auto& k : restore_job_keys) {
6162
20
            txn->remove(k);
6163
20
        }
6164
1
        err = txn->commit();
6165
1
        if (err != TxnErrorCode::TXN_OK) {
6166
0
            LOG_WARNING("failed to recycle restore job")
6167
0
                    .tag("err", err)
6168
0
                    .tag("instance_id", instance_id_)
6169
0
                    .tag("reason", "failed to commit txn");
6170
0
            return -1;
6171
0
        }
6172
1
        return 0;
6173
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
6146
3
    auto loop_done = [&restore_job_keys, this]() -> int {
6147
3
        if (restore_job_keys.empty()) return 0;
6148
1
        DORIS_CLOUD_DEFER {
6149
1
            restore_job_keys.clear();
6150
1
        };
6151
6152
1
        std::unique_ptr<Transaction> txn;
6153
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6154
1
        if (err != TxnErrorCode::TXN_OK) {
6155
0
            LOG_WARNING("failed to recycle restore job")
6156
0
                    .tag("err", err)
6157
0
                    .tag("instance_id", instance_id_)
6158
0
                    .tag("reason", "failed to create txn");
6159
0
            return -1;
6160
0
        }
6161
20
        for (auto& k : restore_job_keys) {
6162
20
            txn->remove(k);
6163
20
        }
6164
1
        err = txn->commit();
6165
1
        if (err != TxnErrorCode::TXN_OK) {
6166
0
            LOG_WARNING("failed to recycle restore job")
6167
0
                    .tag("err", err)
6168
0
                    .tag("instance_id", instance_id_)
6169
0
                    .tag("reason", "failed to commit txn");
6170
0
            return -1;
6171
0
        }
6172
1
        return 0;
6173
1
    };
6174
6175
13
    if (config::enable_recycler_stats_metrics) {
6176
0
        scan_and_statistics_restore_jobs();
6177
0
    }
6178
6179
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
6180
13
                            std::move(loop_done));
6181
13
}
6182
6183
11
int InstanceRecycler::recycle_versioned_rowsets() {
6184
11
    const std::string task_name = "recycle_rowsets";
6185
11
    int64_t num_scanned = 0;
6186
11
    int64_t num_expired = 0;
6187
11
    int64_t num_prepare = 0;
6188
11
    int64_t num_compacted = 0;
6189
11
    int64_t num_empty_rowset = 0;
6190
11
    size_t total_rowset_key_size = 0;
6191
11
    size_t total_rowset_value_size = 0;
6192
11
    size_t expired_rowset_size = 0;
6193
11
    std::atomic_long num_recycled = 0;
6194
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6195
6196
11
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
6197
11
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
6198
11
    std::string recyc_rs_key0;
6199
11
    std::string recyc_rs_key1;
6200
11
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
6201
11
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
6202
6203
11
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
6204
6205
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6206
11
    register_recycle_task(task_name, start_time);
6207
6208
11
    DORIS_CLOUD_DEFER {
6209
11
        unregister_recycle_task(task_name);
6210
11
        int64_t cost =
6211
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6212
11
        metrics_context.finish_report();
6213
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6214
11
                .tag("instance_id", instance_id_)
6215
11
                .tag("num_scanned", num_scanned)
6216
11
                .tag("num_expired", num_expired)
6217
11
                .tag("num_recycled", num_recycled)
6218
11
                .tag("num_recycled.prepare", num_prepare)
6219
11
                .tag("num_recycled.compacted", num_compacted)
6220
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6221
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6222
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6223
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6224
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
6208
11
    DORIS_CLOUD_DEFER {
6209
11
        unregister_recycle_task(task_name);
6210
11
        int64_t cost =
6211
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6212
11
        metrics_context.finish_report();
6213
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6214
11
                .tag("instance_id", instance_id_)
6215
11
                .tag("num_scanned", num_scanned)
6216
11
                .tag("num_expired", num_expired)
6217
11
                .tag("num_recycled", num_recycled)
6218
11
                .tag("num_recycled.prepare", num_prepare)
6219
11
                .tag("num_recycled.compacted", num_compacted)
6220
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6221
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6222
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6223
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6224
11
    };
6225
6226
11
    std::vector<std::string> orphan_rowset_keys;
6227
6228
    // Store keys of rowset recycled by background workers
6229
11
    std::mutex async_recycled_rowset_keys_mutex;
6230
11
    std::vector<std::string> async_recycled_rowset_keys;
6231
11
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6232
11
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
6233
11
    worker_pool->start();
6234
11
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
6235
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6236
        // Try to delete rowset data in background thread
6237
400
        int ret = worker_pool->submit_with_timeout(
6238
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6239
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6240
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6241
400
                        return;
6242
400
                    }
6243
                    // The async recycled rowsets are staled format or has not been used,
6244
                    // so we don't need to check the rowset ref count key.
6245
0
                    std::vector<std::string> keys;
6246
0
                    {
6247
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6248
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6249
0
                        if (async_recycled_rowset_keys.size() > 100) {
6250
0
                            keys.swap(async_recycled_rowset_keys);
6251
0
                        }
6252
0
                    }
6253
0
                    if (keys.empty()) return;
6254
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6255
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6256
0
                                     << instance_id_;
6257
0
                    } else {
6258
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6259
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6260
0
                                           num_recycled, start_time);
6261
0
                    }
6262
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
6238
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6239
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6240
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6241
400
                        return;
6242
400
                    }
6243
                    // The async recycled rowsets are staled format or has not been used,
6244
                    // so we don't need to check the rowset ref count key.
6245
0
                    std::vector<std::string> keys;
6246
0
                    {
6247
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6248
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6249
0
                        if (async_recycled_rowset_keys.size() > 100) {
6250
0
                            keys.swap(async_recycled_rowset_keys);
6251
0
                        }
6252
0
                    }
6253
0
                    if (keys.empty()) return;
6254
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6255
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6256
0
                                     << instance_id_;
6257
0
                    } else {
6258
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6259
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6260
0
                                           num_recycled, start_time);
6261
0
                    }
6262
0
                },
6263
400
                0);
6264
400
        if (ret == 0) return 0;
6265
        // Submit task failed, delete rowset data in current thread
6266
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6267
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6268
0
            return -1;
6269
0
        }
6270
0
        orphan_rowset_keys.push_back(std::move(key));
6271
0
        return 0;
6272
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
6235
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6236
        // Try to delete rowset data in background thread
6237
400
        int ret = worker_pool->submit_with_timeout(
6238
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6239
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6240
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6241
400
                        return;
6242
400
                    }
6243
                    // The async recycled rowsets are staled format or has not been used,
6244
                    // so we don't need to check the rowset ref count key.
6245
400
                    std::vector<std::string> keys;
6246
400
                    {
6247
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6248
400
                        async_recycled_rowset_keys.push_back(std::move(key));
6249
400
                        if (async_recycled_rowset_keys.size() > 100) {
6250
400
                            keys.swap(async_recycled_rowset_keys);
6251
400
                        }
6252
400
                    }
6253
400
                    if (keys.empty()) return;
6254
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6255
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6256
400
                                     << instance_id_;
6257
400
                    } else {
6258
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6259
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6260
400
                                           num_recycled, start_time);
6261
400
                    }
6262
400
                },
6263
400
                0);
6264
400
        if (ret == 0) return 0;
6265
        // Submit task failed, delete rowset data in current thread
6266
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6267
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6268
0
            return -1;
6269
0
        }
6270
0
        orphan_rowset_keys.push_back(std::move(key));
6271
0
        return 0;
6272
0
    };
6273
6274
11
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6275
6276
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6277
2.01k
        ++num_scanned;
6278
2.01k
        total_rowset_key_size += k.size();
6279
2.01k
        total_rowset_value_size += v.size();
6280
2.01k
        RecycleRowsetPB rowset;
6281
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6282
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6283
0
            return -1;
6284
0
        }
6285
6286
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6287
6288
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6289
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6290
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6291
2.01k
        int64_t current_time = ::time(nullptr);
6292
2.01k
        if (current_time < final_expiration) { // not expired
6293
0
            return 0;
6294
0
        }
6295
2.01k
        ++num_expired;
6296
2.01k
        expired_rowset_size += v.size();
6297
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6298
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6299
                // in old version, keep this key-value pair and it needs to be checked manually
6300
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6301
0
                return -1;
6302
0
            }
6303
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6304
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6305
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6306
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6307
0
                orphan_rowset_keys.emplace_back(k);
6308
0
                return -1;
6309
0
            }
6310
            // decode rowset_id
6311
0
            auto k1 = k;
6312
0
            k1.remove_prefix(1);
6313
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6314
0
            decode_key(&k1, &out);
6315
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6316
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6317
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6318
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6319
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6320
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6321
0
                return -1;
6322
0
            }
6323
0
            return 0;
6324
0
        }
6325
        // TODO(plat1ko): check rowset not referenced
6326
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6327
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6328
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6329
0
                LOG_INFO("recycle rowset that has empty resource id");
6330
0
            } else {
6331
                // other situations, keep this key-value pair and it needs to be checked manually
6332
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6333
0
                return -1;
6334
0
            }
6335
0
        }
6336
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6337
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6338
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6339
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6340
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6341
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6342
2.01k
                  << " rowset_meta_size=" << v.size()
6343
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6344
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6345
            // unable to calculate file path, can only be deleted by rowset id prefix
6346
400
            num_prepare += 1;
6347
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6348
400
                                             rowset_meta->tablet_id(),
6349
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6350
0
                return -1;
6351
0
            }
6352
1.61k
        } else {
6353
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6354
1.61k
            worker_pool->submit(
6355
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6356
                        // The load & compact rowset keys are recycled during recycling operation logs.
6357
1.61k
                        RowsetDeleteTask task;
6358
1.61k
                        task.rowset_meta = rowset_meta;
6359
1.61k
                        task.recycle_rowset_key = k;
6360
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6361
1.59k
                            return;
6362
1.59k
                        }
6363
14
                        num_compacted += is_compacted;
6364
14
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6365
14
                        if (rowset_meta.num_segments() == 0) {
6366
0
                            ++num_empty_rowset;
6367
0
                        }
6368
14
                    });
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
6355
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6356
                        // The load & compact rowset keys are recycled during recycling operation logs.
6357
1.61k
                        RowsetDeleteTask task;
6358
1.61k
                        task.rowset_meta = rowset_meta;
6359
1.61k
                        task.recycle_rowset_key = k;
6360
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6361
1.59k
                            return;
6362
1.59k
                        }
6363
14
                        num_compacted += is_compacted;
6364
14
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6365
14
                        if (rowset_meta.num_segments() == 0) {
6366
0
                            ++num_empty_rowset;
6367
0
                        }
6368
14
                    });
6369
1.61k
        }
6370
2.01k
        return 0;
6371
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
6276
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6277
2.01k
        ++num_scanned;
6278
2.01k
        total_rowset_key_size += k.size();
6279
2.01k
        total_rowset_value_size += v.size();
6280
2.01k
        RecycleRowsetPB rowset;
6281
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6282
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6283
0
            return -1;
6284
0
        }
6285
6286
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6287
6288
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6289
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6290
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6291
2.01k
        int64_t current_time = ::time(nullptr);
6292
2.01k
        if (current_time < final_expiration) { // not expired
6293
0
            return 0;
6294
0
        }
6295
2.01k
        ++num_expired;
6296
2.01k
        expired_rowset_size += v.size();
6297
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6298
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6299
                // in old version, keep this key-value pair and it needs to be checked manually
6300
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6301
0
                return -1;
6302
0
            }
6303
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6304
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6305
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6306
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6307
0
                orphan_rowset_keys.emplace_back(k);
6308
0
                return -1;
6309
0
            }
6310
            // decode rowset_id
6311
0
            auto k1 = k;
6312
0
            k1.remove_prefix(1);
6313
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6314
0
            decode_key(&k1, &out);
6315
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6316
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6317
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6318
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6319
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6320
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6321
0
                return -1;
6322
0
            }
6323
0
            return 0;
6324
0
        }
6325
        // TODO(plat1ko): check rowset not referenced
6326
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6327
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6328
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6329
0
                LOG_INFO("recycle rowset that has empty resource id");
6330
0
            } else {
6331
                // other situations, keep this key-value pair and it needs to be checked manually
6332
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6333
0
                return -1;
6334
0
            }
6335
0
        }
6336
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6337
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6338
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6339
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6340
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6341
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6342
2.01k
                  << " rowset_meta_size=" << v.size()
6343
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6344
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6345
            // unable to calculate file path, can only be deleted by rowset id prefix
6346
400
            num_prepare += 1;
6347
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6348
400
                                             rowset_meta->tablet_id(),
6349
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6350
0
                return -1;
6351
0
            }
6352
1.61k
        } else {
6353
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6354
1.61k
            worker_pool->submit(
6355
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6356
                        // The load & compact rowset keys are recycled during recycling operation logs.
6357
1.61k
                        RowsetDeleteTask task;
6358
1.61k
                        task.rowset_meta = rowset_meta;
6359
1.61k
                        task.recycle_rowset_key = k;
6360
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6361
1.61k
                            return;
6362
1.61k
                        }
6363
1.61k
                        num_compacted += is_compacted;
6364
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6365
1.61k
                        if (rowset_meta.num_segments() == 0) {
6366
1.61k
                            ++num_empty_rowset;
6367
1.61k
                        }
6368
1.61k
                    });
6369
1.61k
        }
6370
2.01k
        return 0;
6371
2.01k
    };
6372
6373
11
    if (config::enable_recycler_stats_metrics) {
6374
0
        scan_and_statistics_rowsets();
6375
0
    }
6376
6377
11
    auto loop_done = [&]() -> int {
6378
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6379
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6380
0
        }
6381
6
        orphan_rowset_keys.clear();
6382
6
        return 0;
6383
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
Line
Count
Source
6377
6
    auto loop_done = [&]() -> int {
6378
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6379
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6380
0
        }
6381
6
        orphan_rowset_keys.clear();
6382
6
        return 0;
6383
6
    };
6384
6385
    // recycle_func and loop_done for scan and recycle
6386
11
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
6387
11
                               std::move(loop_done));
6388
6389
11
    worker_pool->stop();
6390
6391
11
    if (!async_recycled_rowset_keys.empty()) {
6392
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
6393
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6394
0
            return -1;
6395
0
        } else {
6396
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
6397
0
        }
6398
0
    }
6399
6400
    // Report final metrics after all concurrent tasks completed
6401
11
    segment_metrics_context_.report();
6402
11
    metrics_context.report();
6403
6404
11
    return ret;
6405
11
}
6406
6407
1.61k
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task) {
6408
1.61k
    constexpr int MAX_RETRY = 10;
6409
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
6410
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
6411
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
6412
1.61k
    std::string_view reference_instance_id = instance_id_;
6413
1.61k
    if (rowset_meta.has_reference_instance_id()) {
6414
8
        reference_instance_id = rowset_meta.reference_instance_id();
6415
8
    }
6416
6417
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
6418
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
6419
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
6420
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
6421
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
6422
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
6423
1.61k
        std::unique_ptr<Transaction> txn;
6424
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6425
1.61k
        if (err != TxnErrorCode::TXN_OK) {
6426
0
            LOG_WARNING("failed to create txn").tag("err", err);
6427
0
            return -1;
6428
0
        }
6429
6430
1.61k
        std::string rowset_ref_count_key =
6431
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
6432
1.61k
        int64_t ref_count = 0;
6433
1.61k
        {
6434
1.61k
            std::string value;
6435
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
6436
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6437
                // This is the old version rowset, we could recycle it directly.
6438
1.60k
                ref_count = 1;
6439
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
6440
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
6441
0
                return -1;
6442
11
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
6443
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
6444
0
                return -1;
6445
0
            }
6446
1.61k
        }
6447
6448
1.61k
        if (ref_count == 1) {
6449
            // It would not be added since it is recycling.
6450
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
6451
1.60k
                LOG_WARNING("failed to delete rowset data");
6452
1.60k
                return -1;
6453
1.60k
            }
6454
6455
            // Reset the transaction to avoid timeout.
6456
10
            err = txn_kv_->create_txn(&txn);
6457
10
            if (err != TxnErrorCode::TXN_OK) {
6458
0
                LOG_WARNING("failed to create txn").tag("err", err);
6459
0
                return -1;
6460
0
            }
6461
10
            txn->remove(rowset_ref_count_key);
6462
10
            LOG_INFO("delete rowset data ref count key")
6463
10
                    .tag("txn_id", rowset_meta.txn_id())
6464
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6465
6466
10
            std::string dbm_start_key =
6467
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
6468
10
            std::string dbm_end_key = meta_delete_bitmap_key(
6469
10
                    {reference_instance_id, tablet_id, rowset_id,
6470
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
6471
10
            txn->remove(dbm_start_key, dbm_end_key);
6472
10
            LOG_INFO("remove delete bitmap kv")
6473
10
                    .tag("begin", hex(dbm_start_key))
6474
10
                    .tag("end", hex(dbm_end_key));
6475
6476
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
6477
10
                    {reference_instance_id, tablet_id, rowset_id});
6478
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
6479
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
6480
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
6481
10
            LOG_INFO("remove versioned delete bitmap kv")
6482
10
                    .tag("begin", hex(versioned_dbm_start_key))
6483
10
                    .tag("end", hex(versioned_dbm_end_key));
6484
10
        } else {
6485
            // Decrease the rowset ref count.
6486
            //
6487
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
6488
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
6489
3
            txn->atomic_add(rowset_ref_count_key, -1);
6490
3
            LOG_INFO("decrease rowset data ref count")
6491
3
                    .tag("txn_id", rowset_meta.txn_id())
6492
3
                    .tag("ref_count", ref_count - 1)
6493
3
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6494
3
        }
6495
6496
13
        if (!task.versioned_rowset_key.empty()) {
6497
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
6498
0
                                                          task.versionstamp);
6499
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
6500
0
        }
6501
6502
13
        if (!task.non_versioned_rowset_key.empty()) {
6503
0
            txn->remove(task.non_versioned_rowset_key);
6504
0
            LOG_INFO("remove non versioned rowset key")
6505
0
                    .tag("key", hex(task.non_versioned_rowset_key));
6506
0
        }
6507
6508
        // empty when recycle ref rowsets for deleted instance
6509
13
        if (!task.recycle_rowset_key.empty()) {
6510
13
            txn->remove(task.recycle_rowset_key);
6511
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
6512
13
        }
6513
6514
13
        err = txn->commit();
6515
13
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
6516
            // The rowset ref count key has been changed, we need to retry.
6517
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
6518
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
6519
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
6520
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6521
0
            continue;
6522
13
        } else if (err != TxnErrorCode::TXN_OK) {
6523
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
6524
0
            return -1;
6525
0
        }
6526
13
        LOG_INFO("recycle rowset meta and data success");
6527
13
        return 0;
6528
13
    }
6529
0
    LOG_WARNING("failed to recycle rowset meta and data after retry")
6530
0
            .tag("tablet_id", tablet_id)
6531
0
            .tag("rowset_id", rowset_id)
6532
0
            .tag("retry", MAX_RETRY);
6533
0
    return -1;
6534
1.61k
}
6535
6536
37
int InstanceRecycler::recycle_tmp_rowsets() {
6537
37
    const std::string task_name = "recycle_tmp_rowsets";
6538
37
    int64_t num_scanned = 0;
6539
37
    int64_t num_expired = 0;
6540
37
    std::atomic_long num_recycled = 0;
6541
37
    size_t expired_rowset_size = 0;
6542
37
    size_t total_rowset_key_size = 0;
6543
37
    size_t total_rowset_value_size = 0;
6544
37
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6545
6546
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
6547
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
6548
37
    std::string tmp_rs_key0;
6549
37
    std::string tmp_rs_key1;
6550
37
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
6551
37
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
6552
6553
37
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
6554
6555
37
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6556
37
    register_recycle_task(task_name, start_time);
6557
6558
37
    DORIS_CLOUD_DEFER {
6559
37
        unregister_recycle_task(task_name);
6560
37
        int64_t cost =
6561
37
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6562
37
        metrics_context.finish_report();
6563
37
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6564
37
                .tag("instance_id", instance_id_)
6565
37
                .tag("num_scanned", num_scanned)
6566
37
                .tag("num_expired", num_expired)
6567
37
                .tag("num_recycled", num_recycled)
6568
37
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6569
37
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6570
37
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6571
37
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6558
12
    DORIS_CLOUD_DEFER {
6559
12
        unregister_recycle_task(task_name);
6560
12
        int64_t cost =
6561
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6562
12
        metrics_context.finish_report();
6563
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6564
12
                .tag("instance_id", instance_id_)
6565
12
                .tag("num_scanned", num_scanned)
6566
12
                .tag("num_expired", num_expired)
6567
12
                .tag("num_recycled", num_recycled)
6568
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6569
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6570
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6571
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6558
25
    DORIS_CLOUD_DEFER {
6559
25
        unregister_recycle_task(task_name);
6560
25
        int64_t cost =
6561
25
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6562
25
        metrics_context.finish_report();
6563
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6564
25
                .tag("instance_id", instance_id_)
6565
25
                .tag("num_scanned", num_scanned)
6566
25
                .tag("num_expired", num_expired)
6567
25
                .tag("num_recycled", num_recycled)
6568
25
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6569
25
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6570
25
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6571
25
    };
6572
6573
    // Store direct-delete keys separately from keys whose related txn or job must be aborted.
6574
37
    std::vector<std::string> tmp_rowset_keys;
6575
37
    std::vector<std::string> tmp_rowset_ref_count_keys;
6576
37
    std::vector<std::string> tmp_rowset_keys_to_mark_recycled;
6577
37
    std::vector<std::string> tmp_rowset_keys_to_abort;
6578
6579
    // rowset_id -> rowset_meta
6580
    // store tmp_rowset id and meta for statistics rs size when delete
6581
37
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
6582
37
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6583
37
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
6584
37
    worker_pool->start();
6585
6586
37
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6587
6588
37
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &expired_rowset_size,
6589
37
                             &total_rowset_key_size, &total_rowset_value_size, &earlest_ts,
6590
37
                             &tmp_rowset_keys_to_mark_recycled, &tmp_rowset_keys_to_abort, this,
6591
37
                             &metrics_context, &tmp_rowsets, &tmp_rowset_ref_count_keys](
6592
53.2k
                                    std::string_view k, std::string_view v) -> int {
6593
53.2k
        ++num_scanned;
6594
53.2k
        total_rowset_key_size += k.size();
6595
53.2k
        total_rowset_value_size += v.size();
6596
53.2k
        doris::RowsetMetaCloudPB rowset;
6597
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6598
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6599
0
            return -1;
6600
0
        }
6601
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6602
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6603
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6604
0
                   << " txn_expiration=" << rowset.txn_expiration()
6605
0
                   << " rowset_creation_time=" << rowset.creation_time();
6606
53.2k
        int64_t current_time = ::time(nullptr);
6607
53.2k
        if (current_time < expiration) { // not expired
6608
0
            return 0;
6609
0
        }
6610
53.2k
        ++num_expired;
6611
53.2k
        expired_rowset_size += v.size();
6612
53.2k
        if (!rowset.has_resource_id()) {
6613
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6614
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6615
0
                return -1;
6616
0
            }
6617
            // might be a delete pred rowset
6618
0
            tmp_rowset_keys.emplace_back(k);
6619
0
            return 0;
6620
0
        }
6621
6622
        // TODO(plat1ko): check rowset not referenced
6623
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6624
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6625
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6626
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6627
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6628
53.2k
                  << " num_expired=" << num_expired
6629
53.2k
                  << " task_type=" << metrics_context.operation_type;
6630
6631
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6632
16
            if (need_mark_rowset_as_recycled(rowset)) {
6633
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6634
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6635
9
                             "at next turn, instance_id="
6636
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6637
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6638
9
                return 0;
6639
9
            }
6640
16
        }
6641
6642
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6643
265
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6644
261
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6645
261
                             "instance_id="
6646
261
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6647
261
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6648
261
                tmp_rowset_keys_to_abort.emplace_back(k);
6649
261
                return 0;
6650
261
            }
6651
265
        }
6652
6653
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6654
        // Remove the rowset ref count key directly since it has not been used.
6655
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6656
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6657
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6658
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6659
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6660
6661
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6662
53.0k
        return 0;
6663
53.2k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6592
16
                                    std::string_view k, std::string_view v) -> int {
6593
16
        ++num_scanned;
6594
16
        total_rowset_key_size += k.size();
6595
16
        total_rowset_value_size += v.size();
6596
16
        doris::RowsetMetaCloudPB rowset;
6597
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6598
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6599
0
            return -1;
6600
0
        }
6601
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6602
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6603
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6604
0
                   << " txn_expiration=" << rowset.txn_expiration()
6605
0
                   << " rowset_creation_time=" << rowset.creation_time();
6606
16
        int64_t current_time = ::time(nullptr);
6607
16
        if (current_time < expiration) { // not expired
6608
0
            return 0;
6609
0
        }
6610
16
        ++num_expired;
6611
16
        expired_rowset_size += v.size();
6612
16
        if (!rowset.has_resource_id()) {
6613
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6614
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6615
0
                return -1;
6616
0
            }
6617
            // might be a delete pred rowset
6618
0
            tmp_rowset_keys.emplace_back(k);
6619
0
            return 0;
6620
0
        }
6621
6622
        // TODO(plat1ko): check rowset not referenced
6623
16
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6624
16
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6625
16
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6626
16
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6627
16
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6628
16
                  << " num_expired=" << num_expired
6629
16
                  << " task_type=" << metrics_context.operation_type;
6630
6631
16
        if (config::enable_mark_delete_rowset_before_recycle) {
6632
16
            if (need_mark_rowset_as_recycled(rowset)) {
6633
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6634
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6635
9
                             "at next turn, instance_id="
6636
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6637
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6638
9
                return 0;
6639
9
            }
6640
16
        }
6641
6642
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6643
7
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6644
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6645
3
                             "instance_id="
6646
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6647
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6648
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6649
3
                return 0;
6650
3
            }
6651
7
        }
6652
6653
4
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6654
        // Remove the rowset ref count key directly since it has not been used.
6655
4
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6656
4
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6657
4
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6658
4
                  << "key=" << hex(rowset_ref_count_key);
6659
4
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6660
6661
4
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6662
4
        return 0;
6663
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6592
53.2k
                                    std::string_view k, std::string_view v) -> int {
6593
53.2k
        ++num_scanned;
6594
53.2k
        total_rowset_key_size += k.size();
6595
53.2k
        total_rowset_value_size += v.size();
6596
53.2k
        doris::RowsetMetaCloudPB rowset;
6597
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6598
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6599
0
            return -1;
6600
0
        }
6601
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6602
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6603
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6604
0
                   << " txn_expiration=" << rowset.txn_expiration()
6605
0
                   << " rowset_creation_time=" << rowset.creation_time();
6606
53.2k
        int64_t current_time = ::time(nullptr);
6607
53.2k
        if (current_time < expiration) { // not expired
6608
0
            return 0;
6609
0
        }
6610
53.2k
        ++num_expired;
6611
53.2k
        expired_rowset_size += v.size();
6612
53.2k
        if (!rowset.has_resource_id()) {
6613
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6614
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6615
0
                return -1;
6616
0
            }
6617
            // might be a delete pred rowset
6618
0
            tmp_rowset_keys.emplace_back(k);
6619
0
            return 0;
6620
0
        }
6621
6622
        // TODO(plat1ko): check rowset not referenced
6623
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6624
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6625
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6626
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6627
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6628
53.2k
                  << " num_expired=" << num_expired
6629
53.2k
                  << " task_type=" << metrics_context.operation_type;
6630
6631
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6632
0
            if (need_mark_rowset_as_recycled(rowset)) {
6633
0
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6634
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6635
0
                             "at next turn, instance_id="
6636
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6637
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6638
0
                return 0;
6639
0
            }
6640
0
        }
6641
6642
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6643
258
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6644
258
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6645
258
                             "instance_id="
6646
258
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6647
258
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6648
258
                tmp_rowset_keys_to_abort.emplace_back(k);
6649
258
                return 0;
6650
258
            }
6651
258
        }
6652
6653
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6654
        // Remove the rowset ref count key directly since it has not been used.
6655
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6656
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6657
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6658
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6659
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6660
6661
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6662
53.0k
        return 0;
6663
53.2k
    };
6664
6665
37
    auto loop_done = [&]() -> int {
6666
24
        std::vector<std::string> tmp_rowset_keys_to_delete;
6667
24
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6668
24
        std::vector<std::string> mark_keys_to_process;
6669
24
        std::vector<std::string> abort_keys_to_process;
6670
24
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6671
24
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6672
24
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6673
24
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6674
24
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6675
24
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6676
24
        if (!mark_keys_to_process.empty()) {
6677
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6678
7
                    *worker_pool, std::move(mark_keys_to_process));
6679
7
        }
6680
24
        if (!abort_keys_to_process.empty()) {
6681
5
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6682
5
                                           &num_recycled, &metrics_context);
6683
5
        }
6684
24
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6685
24
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6686
24
                             tmp_rowset_ref_count_keys_to_delete =
6687
24
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6688
24
                             mark_keys_to_process = std::move(mark_keys_to_process),
6689
24
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6690
24
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6691
24
                                   metrics_context) != 0) {
6692
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6693
2
                return;
6694
2
            }
6695
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6696
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6697
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6698
0
                                 << rs.ShortDebugString();
6699
0
                    return;
6700
0
                }
6701
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6702
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6703
0
                                 << rs.ShortDebugString();
6704
0
                    return;
6705
0
                }
6706
51.0k
            }
6707
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6708
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6709
0
                return;
6710
0
            }
6711
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6712
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6713
0
                return;
6714
0
            }
6715
22
            num_recycled += tmp_rowset_keys_to_delete.size();
6716
22
            return;
6717
22
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6689
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6690
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6691
12
                                   metrics_context) != 0) {
6692
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6693
0
                return;
6694
0
            }
6695
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6696
4
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6697
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6698
0
                                 << rs.ShortDebugString();
6699
0
                    return;
6700
0
                }
6701
4
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6702
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6703
0
                                 << rs.ShortDebugString();
6704
0
                    return;
6705
0
                }
6706
4
            }
6707
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6708
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6709
0
                return;
6710
0
            }
6711
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6712
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6713
0
                return;
6714
0
            }
6715
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6716
12
            return;
6717
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6689
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6690
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6691
12
                                   metrics_context) != 0) {
6692
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6693
2
                return;
6694
2
            }
6695
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6696
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6697
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6698
0
                                 << rs.ShortDebugString();
6699
0
                    return;
6700
0
                }
6701
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6702
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6703
0
                                 << rs.ShortDebugString();
6704
0
                    return;
6705
0
                }
6706
51.0k
            }
6707
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6708
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6709
0
                return;
6710
0
            }
6711
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6712
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6713
0
                return;
6714
0
            }
6715
10
            num_recycled += tmp_rowset_keys_to_delete.size();
6716
10
            return;
6717
10
        });
6718
24
        return 0;
6719
24
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6665
12
    auto loop_done = [&]() -> int {
6666
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6667
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6668
12
        std::vector<std::string> mark_keys_to_process;
6669
12
        std::vector<std::string> abort_keys_to_process;
6670
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6671
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6672
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6673
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6674
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6675
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6676
12
        if (!mark_keys_to_process.empty()) {
6677
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6678
7
                    *worker_pool, std::move(mark_keys_to_process));
6679
7
        }
6680
12
        if (!abort_keys_to_process.empty()) {
6681
3
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6682
3
                                           &num_recycled, &metrics_context);
6683
3
        }
6684
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6685
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6686
12
                             tmp_rowset_ref_count_keys_to_delete =
6687
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6688
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6689
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6690
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6691
12
                                   metrics_context) != 0) {
6692
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6693
12
                return;
6694
12
            }
6695
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6696
12
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6697
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6698
12
                                 << rs.ShortDebugString();
6699
12
                    return;
6700
12
                }
6701
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6702
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6703
12
                                 << rs.ShortDebugString();
6704
12
                    return;
6705
12
                }
6706
12
            }
6707
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6708
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6709
12
                return;
6710
12
            }
6711
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6712
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6713
12
                return;
6714
12
            }
6715
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6716
12
            return;
6717
12
        });
6718
12
        return 0;
6719
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6665
12
    auto loop_done = [&]() -> int {
6666
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6667
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6668
12
        std::vector<std::string> mark_keys_to_process;
6669
12
        std::vector<std::string> abort_keys_to_process;
6670
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6671
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6672
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6673
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6674
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6675
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6676
12
        if (!mark_keys_to_process.empty()) {
6677
0
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6678
0
                    *worker_pool, std::move(mark_keys_to_process));
6679
0
        }
6680
12
        if (!abort_keys_to_process.empty()) {
6681
2
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6682
2
                                           &num_recycled, &metrics_context);
6683
2
        }
6684
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6685
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6686
12
                             tmp_rowset_ref_count_keys_to_delete =
6687
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6688
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6689
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6690
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6691
12
                                   metrics_context) != 0) {
6692
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6693
12
                return;
6694
12
            }
6695
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6696
12
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6697
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6698
12
                                 << rs.ShortDebugString();
6699
12
                    return;
6700
12
                }
6701
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6702
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6703
12
                                 << rs.ShortDebugString();
6704
12
                    return;
6705
12
                }
6706
12
            }
6707
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6708
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6709
12
                return;
6710
12
            }
6711
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6712
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6713
12
                return;
6714
12
            }
6715
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6716
12
            return;
6717
12
        });
6718
12
        return 0;
6719
12
    };
6720
6721
37
    if (config::enable_recycler_stats_metrics) {
6722
0
        scan_and_statistics_tmp_rowsets();
6723
0
    }
6724
    // recycle_func and loop_done for scan and recycle
6725
37
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
6726
37
                               std::move(loop_done));
6727
6728
37
    worker_pool->stop();
6729
6730
    // Report final metrics after all concurrent tasks completed
6731
37
    segment_metrics_context_.report();
6732
37
    metrics_context.report();
6733
6734
37
    return ret;
6735
37
}
6736
6737
int InstanceRecycler::scan_and_recycle(
6738
        std::string begin, std::string_view end,
6739
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
6740
345
        std::function<int()> loop_done, std::function<bool(std::string*)> next_begin_getter) {
6741
345
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
6742
345
    int ret = 0;
6743
345
    int64_t cnt = 0;
6744
345
    int get_range_retried = 0;
6745
345
    std::string err;
6746
345
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6747
345
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6748
345
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6749
345
                  << " ret=" << ret << " err=" << err;
6750
345
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6746
36
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6747
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6748
36
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6749
36
                  << " ret=" << ret << " err=" << err;
6750
36
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6746
309
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6747
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6748
309
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6749
309
                  << " ret=" << ret << " err=" << err;
6750
309
    };
6751
6752
345
    std::unique_ptr<RangeGetIterator> it;
6753
545
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
6754
380
        if (get_range_retried > 1000) {
6755
0
            err = "txn_get exceeds max retry(1000), may not scan all keys";
6756
0
            ret = -3;
6757
0
            return ret;
6758
0
        }
6759
380
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
6760
380
        if (get_ret != 0) { // txn kv may complain "Request for future version"
6761
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
6762
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
6763
0
                         << " get_range_retried=" << get_range_retried;
6764
0
            ++get_range_retried;
6765
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6766
0
            continue; // try again
6767
0
        }
6768
380
        if (!it->has_next()) {
6769
180
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
6770
180
            break; // scan finished
6771
180
        }
6772
200
        bool begin_updated = false;
6773
200
        LOG(INFO) << "scan_and_recycle iterator key_range=[" << hex(begin) << "," << hex(end)
6774
200
                  << ") iterator->size()=" << it->size();
6775
98.2k
        while (it->has_next()) {
6776
98.0k
            ++cnt;
6777
            // recycle corresponding resources
6778
98.0k
            auto [k, v] = it->next();
6779
98.0k
            if (!it->has_next()) {
6780
194
                begin = k;
6781
194
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
6782
194
            }
6783
            // FIXME(gavin): if we want to continue scanning, the recycle_func should not return non-zero
6784
98.0k
            if (recycle_func(k, v) != 0) {
6785
4.00k
                err = "recycle_func error";
6786
4.00k
                ret = -1;
6787
4.00k
            }
6788
98.0k
            if (next_begin_getter) {
6789
4.33k
                std::string next_begin;
6790
4.33k
                if (next_begin_getter(&next_begin)) {
6791
7
                    if (next_begin > k) {
6792
7
                        begin = std::move(next_begin);
6793
7
                        begin_updated = true;
6794
7
                        VLOG_DEBUG << "scan_and_recycle updates begin to " << hex(begin)
6795
0
                                   << " after key=" << hex(k);
6796
7
                        break;
6797
7
                    }
6798
0
                    LOG_WARNING("ignore invalid next begin in scan_and_recycle")
6799
0
                            .tag("next_begin", hex(next_begin))
6800
0
                            .tag("current_key", hex(k));
6801
0
                }
6802
4.33k
            }
6803
98.0k
        }
6804
200
        if (!begin_updated) {
6805
193
            begin.push_back('\x00'); // Update to next smallest key for iteration
6806
193
        } else {
6807
7
            it.reset();
6808
7
        }
6809
6810
        // FIXME(gavin): if we want to continue scanning, the loop_done should not return non-zero
6811
        // if we want to continue scanning, the recycle_func should not return non-zero
6812
200
        if (loop_done && loop_done() != 0) {
6813
5
            err = "loop_done error";
6814
5
            ret = -1;
6815
5
        }
6816
200
    }
6817
345
    return ret;
6818
345
}
6819
6820
19
int InstanceRecycler::abort_timeout_txn() {
6821
19
    const std::string task_name = "abort_timeout_txn";
6822
19
    int64_t num_scanned = 0;
6823
19
    int64_t num_timeout = 0;
6824
19
    int64_t num_abort = 0;
6825
19
    int64_t num_advance = 0;
6826
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6827
6828
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6829
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6830
19
    std::string begin_txn_running_key;
6831
19
    std::string end_txn_running_key;
6832
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6833
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6834
6835
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
6836
6837
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6838
19
    register_recycle_task(task_name, start_time);
6839
6840
19
    DORIS_CLOUD_DEFER {
6841
19
        unregister_recycle_task(task_name);
6842
19
        int64_t cost =
6843
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6844
19
        metrics_context.finish_report();
6845
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6846
19
                .tag("instance_id", instance_id_)
6847
19
                .tag("num_scanned", num_scanned)
6848
19
                .tag("num_timeout", num_timeout)
6849
19
                .tag("num_abort", num_abort)
6850
19
                .tag("num_advance", num_advance);
6851
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6840
3
    DORIS_CLOUD_DEFER {
6841
3
        unregister_recycle_task(task_name);
6842
3
        int64_t cost =
6843
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6844
3
        metrics_context.finish_report();
6845
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6846
3
                .tag("instance_id", instance_id_)
6847
3
                .tag("num_scanned", num_scanned)
6848
3
                .tag("num_timeout", num_timeout)
6849
3
                .tag("num_abort", num_abort)
6850
3
                .tag("num_advance", num_advance);
6851
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6840
16
    DORIS_CLOUD_DEFER {
6841
16
        unregister_recycle_task(task_name);
6842
16
        int64_t cost =
6843
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6844
16
        metrics_context.finish_report();
6845
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6846
16
                .tag("instance_id", instance_id_)
6847
16
                .tag("num_scanned", num_scanned)
6848
16
                .tag("num_timeout", num_timeout)
6849
16
                .tag("num_abort", num_abort)
6850
16
                .tag("num_advance", num_advance);
6851
16
    };
6852
6853
19
    int64_t current_time =
6854
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6855
6856
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
6857
19
                                  &current_time, &metrics_context,
6858
19
                                  this](std::string_view k, std::string_view v) -> int {
6859
9
        ++num_scanned;
6860
6861
9
        std::unique_ptr<Transaction> txn;
6862
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6863
9
        if (err != TxnErrorCode::TXN_OK) {
6864
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6865
0
            return -1;
6866
0
        }
6867
9
        std::string_view k1 = k;
6868
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6869
9
        k1.remove_prefix(1); // Remove key space
6870
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6871
9
        if (decode_key(&k1, &out) != 0) {
6872
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6873
0
            return -1;
6874
0
        }
6875
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6876
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6877
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6878
        // Update txn_info
6879
9
        std::string txn_inf_key, txn_inf_val;
6880
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6881
9
        err = txn->get(txn_inf_key, &txn_inf_val);
6882
9
        if (err != TxnErrorCode::TXN_OK) {
6883
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6884
0
            return -1;
6885
0
        }
6886
9
        TxnInfoPB txn_info;
6887
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
6888
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6889
0
            return -1;
6890
0
        }
6891
6892
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6893
3
            txn.reset();
6894
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6895
3
            std::shared_ptr<TxnLazyCommitTask> task =
6896
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6897
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6898
3
            if (ret.first != MetaServiceCode::OK) {
6899
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6900
0
                             << "msg=" << ret.second;
6901
0
                return -1;
6902
0
            }
6903
3
            ++num_advance;
6904
3
            return 0;
6905
6
        } else {
6906
6
            TxnRunningPB txn_running_pb;
6907
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6908
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6909
0
                return -1;
6910
0
            }
6911
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6912
4
                return 0;
6913
4
            }
6914
2
            ++num_timeout;
6915
6916
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6917
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6918
2
            txn_info.set_finish_time(current_time);
6919
2
            txn_info.set_reason("timeout");
6920
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6921
2
            txn_inf_val.clear();
6922
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6923
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6924
0
                return -1;
6925
0
            }
6926
2
            txn->put(txn_inf_key, txn_inf_val);
6927
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6928
            // Put recycle txn key
6929
2
            std::string recyc_txn_key, recyc_txn_val;
6930
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6931
2
            RecycleTxnPB recycle_txn_pb;
6932
2
            recycle_txn_pb.set_creation_time(current_time);
6933
2
            recycle_txn_pb.set_label(txn_info.label());
6934
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6935
0
                LOG_WARNING("failed to serialize txn recycle info")
6936
0
                        .tag("key", hex(k))
6937
0
                        .tag("db_id", db_id)
6938
0
                        .tag("txn_id", txn_id);
6939
0
                return -1;
6940
0
            }
6941
2
            txn->put(recyc_txn_key, recyc_txn_val);
6942
            // Remove txn running key
6943
2
            txn->remove(k);
6944
2
            err = txn->commit();
6945
2
            if (err != TxnErrorCode::TXN_OK) {
6946
0
                LOG_WARNING("failed to commit txn err={}", err)
6947
0
                        .tag("key", hex(k))
6948
0
                        .tag("db_id", db_id)
6949
0
                        .tag("txn_id", txn_id);
6950
0
                return -1;
6951
0
            }
6952
2
            metrics_context.total_recycled_num = ++num_abort;
6953
2
            metrics_context.report();
6954
2
        }
6955
6956
2
        return 0;
6957
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6858
3
                                  this](std::string_view k, std::string_view v) -> int {
6859
3
        ++num_scanned;
6860
6861
3
        std::unique_ptr<Transaction> txn;
6862
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6863
3
        if (err != TxnErrorCode::TXN_OK) {
6864
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6865
0
            return -1;
6866
0
        }
6867
3
        std::string_view k1 = k;
6868
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6869
3
        k1.remove_prefix(1); // Remove key space
6870
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6871
3
        if (decode_key(&k1, &out) != 0) {
6872
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6873
0
            return -1;
6874
0
        }
6875
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6876
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6877
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6878
        // Update txn_info
6879
3
        std::string txn_inf_key, txn_inf_val;
6880
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6881
3
        err = txn->get(txn_inf_key, &txn_inf_val);
6882
3
        if (err != TxnErrorCode::TXN_OK) {
6883
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6884
0
            return -1;
6885
0
        }
6886
3
        TxnInfoPB txn_info;
6887
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
6888
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6889
0
            return -1;
6890
0
        }
6891
6892
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6893
3
            txn.reset();
6894
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6895
3
            std::shared_ptr<TxnLazyCommitTask> task =
6896
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6897
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6898
3
            if (ret.first != MetaServiceCode::OK) {
6899
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6900
0
                             << "msg=" << ret.second;
6901
0
                return -1;
6902
0
            }
6903
3
            ++num_advance;
6904
3
            return 0;
6905
3
        } else {
6906
0
            TxnRunningPB txn_running_pb;
6907
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6908
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6909
0
                return -1;
6910
0
            }
6911
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6912
0
                return 0;
6913
0
            }
6914
0
            ++num_timeout;
6915
6916
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6917
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6918
0
            txn_info.set_finish_time(current_time);
6919
0
            txn_info.set_reason("timeout");
6920
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6921
0
            txn_inf_val.clear();
6922
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6923
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6924
0
                return -1;
6925
0
            }
6926
0
            txn->put(txn_inf_key, txn_inf_val);
6927
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6928
            // Put recycle txn key
6929
0
            std::string recyc_txn_key, recyc_txn_val;
6930
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6931
0
            RecycleTxnPB recycle_txn_pb;
6932
0
            recycle_txn_pb.set_creation_time(current_time);
6933
0
            recycle_txn_pb.set_label(txn_info.label());
6934
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6935
0
                LOG_WARNING("failed to serialize txn recycle info")
6936
0
                        .tag("key", hex(k))
6937
0
                        .tag("db_id", db_id)
6938
0
                        .tag("txn_id", txn_id);
6939
0
                return -1;
6940
0
            }
6941
0
            txn->put(recyc_txn_key, recyc_txn_val);
6942
            // Remove txn running key
6943
0
            txn->remove(k);
6944
0
            err = txn->commit();
6945
0
            if (err != TxnErrorCode::TXN_OK) {
6946
0
                LOG_WARNING("failed to commit txn err={}", err)
6947
0
                        .tag("key", hex(k))
6948
0
                        .tag("db_id", db_id)
6949
0
                        .tag("txn_id", txn_id);
6950
0
                return -1;
6951
0
            }
6952
0
            metrics_context.total_recycled_num = ++num_abort;
6953
0
            metrics_context.report();
6954
0
        }
6955
6956
0
        return 0;
6957
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6858
6
                                  this](std::string_view k, std::string_view v) -> int {
6859
6
        ++num_scanned;
6860
6861
6
        std::unique_ptr<Transaction> txn;
6862
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6863
6
        if (err != TxnErrorCode::TXN_OK) {
6864
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6865
0
            return -1;
6866
0
        }
6867
6
        std::string_view k1 = k;
6868
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6869
6
        k1.remove_prefix(1); // Remove key space
6870
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6871
6
        if (decode_key(&k1, &out) != 0) {
6872
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6873
0
            return -1;
6874
0
        }
6875
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6876
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6877
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6878
        // Update txn_info
6879
6
        std::string txn_inf_key, txn_inf_val;
6880
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6881
6
        err = txn->get(txn_inf_key, &txn_inf_val);
6882
6
        if (err != TxnErrorCode::TXN_OK) {
6883
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6884
0
            return -1;
6885
0
        }
6886
6
        TxnInfoPB txn_info;
6887
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
6888
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6889
0
            return -1;
6890
0
        }
6891
6892
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6893
0
            txn.reset();
6894
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6895
0
            std::shared_ptr<TxnLazyCommitTask> task =
6896
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6897
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6898
0
            if (ret.first != MetaServiceCode::OK) {
6899
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6900
0
                             << "msg=" << ret.second;
6901
0
                return -1;
6902
0
            }
6903
0
            ++num_advance;
6904
0
            return 0;
6905
6
        } else {
6906
6
            TxnRunningPB txn_running_pb;
6907
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6908
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6909
0
                return -1;
6910
0
            }
6911
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6912
4
                return 0;
6913
4
            }
6914
2
            ++num_timeout;
6915
6916
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6917
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6918
2
            txn_info.set_finish_time(current_time);
6919
2
            txn_info.set_reason("timeout");
6920
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6921
2
            txn_inf_val.clear();
6922
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6923
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6924
0
                return -1;
6925
0
            }
6926
2
            txn->put(txn_inf_key, txn_inf_val);
6927
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6928
            // Put recycle txn key
6929
2
            std::string recyc_txn_key, recyc_txn_val;
6930
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6931
2
            RecycleTxnPB recycle_txn_pb;
6932
2
            recycle_txn_pb.set_creation_time(current_time);
6933
2
            recycle_txn_pb.set_label(txn_info.label());
6934
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6935
0
                LOG_WARNING("failed to serialize txn recycle info")
6936
0
                        .tag("key", hex(k))
6937
0
                        .tag("db_id", db_id)
6938
0
                        .tag("txn_id", txn_id);
6939
0
                return -1;
6940
0
            }
6941
2
            txn->put(recyc_txn_key, recyc_txn_val);
6942
            // Remove txn running key
6943
2
            txn->remove(k);
6944
2
            err = txn->commit();
6945
2
            if (err != TxnErrorCode::TXN_OK) {
6946
0
                LOG_WARNING("failed to commit txn err={}", err)
6947
0
                        .tag("key", hex(k))
6948
0
                        .tag("db_id", db_id)
6949
0
                        .tag("txn_id", txn_id);
6950
0
                return -1;
6951
0
            }
6952
2
            metrics_context.total_recycled_num = ++num_abort;
6953
2
            metrics_context.report();
6954
2
        }
6955
6956
2
        return 0;
6957
6
    };
6958
6959
19
    if (config::enable_recycler_stats_metrics) {
6960
0
        scan_and_statistics_abort_timeout_txn();
6961
0
    }
6962
    // recycle_func and loop_done for scan and recycle
6963
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
6964
19
                            std::move(handle_txn_running_kv));
6965
19
}
6966
6967
19
int InstanceRecycler::recycle_expired_txn_label() {
6968
19
    const std::string task_name = "recycle_expired_txn_label";
6969
19
    int64_t num_scanned = 0;
6970
19
    int64_t num_expired = 0;
6971
19
    std::atomic_long num_recycled = 0;
6972
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6973
19
    int ret = 0;
6974
6975
19
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
6976
19
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6977
19
    std::string begin_recycle_txn_key;
6978
19
    std::string end_recycle_txn_key;
6979
19
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
6980
19
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
6981
19
    std::vector<std::string> recycle_txn_info_keys;
6982
6983
19
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
6984
6985
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6986
19
    register_recycle_task(task_name, start_time);
6987
19
    DORIS_CLOUD_DEFER {
6988
19
        unregister_recycle_task(task_name);
6989
19
        int64_t cost =
6990
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6991
19
        metrics_context.finish_report();
6992
19
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6993
19
                .tag("instance_id", instance_id_)
6994
19
                .tag("num_scanned", num_scanned)
6995
19
                .tag("num_expired", num_expired)
6996
19
                .tag("num_recycled", num_recycled);
6997
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6987
1
    DORIS_CLOUD_DEFER {
6988
1
        unregister_recycle_task(task_name);
6989
1
        int64_t cost =
6990
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6991
1
        metrics_context.finish_report();
6992
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6993
1
                .tag("instance_id", instance_id_)
6994
1
                .tag("num_scanned", num_scanned)
6995
1
                .tag("num_expired", num_expired)
6996
1
                .tag("num_recycled", num_recycled);
6997
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6987
18
    DORIS_CLOUD_DEFER {
6988
18
        unregister_recycle_task(task_name);
6989
18
        int64_t cost =
6990
18
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6991
18
        metrics_context.finish_report();
6992
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6993
18
                .tag("instance_id", instance_id_)
6994
18
                .tag("num_scanned", num_scanned)
6995
18
                .tag("num_expired", num_expired)
6996
18
                .tag("num_recycled", num_recycled);
6997
18
    };
6998
6999
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7000
7001
19
    SyncExecutor<int> concurrent_delete_executor(
7002
19
            _thread_pool_group.s3_producer_pool,
7003
19
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
7004
23.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
7004
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
7004
23.0k
            [](const int& ret) { return ret != 0; });
7005
7006
19
    int64_t current_time_ms =
7007
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7008
7009
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
7010
30.0k
        ++num_scanned;
7011
30.0k
        RecycleTxnPB recycle_txn_pb;
7012
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7013
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7014
0
            return -1;
7015
0
        }
7016
30.0k
        if ((config::force_immediate_recycle) ||
7017
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7018
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7019
30.0k
             current_time_ms)) {
7020
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
7021
23.0k
            num_expired++;
7022
23.0k
            recycle_txn_info_keys.emplace_back(k);
7023
23.0k
        }
7024
30.0k
        return 0;
7025
30.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7009
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
7010
1
        ++num_scanned;
7011
1
        RecycleTxnPB recycle_txn_pb;
7012
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7013
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7014
0
            return -1;
7015
0
        }
7016
1
        if ((config::force_immediate_recycle) ||
7017
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7018
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7019
1
             current_time_ms)) {
7020
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
7021
1
            num_expired++;
7022
1
            recycle_txn_info_keys.emplace_back(k);
7023
1
        }
7024
1
        return 0;
7025
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7009
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
7010
30.0k
        ++num_scanned;
7011
30.0k
        RecycleTxnPB recycle_txn_pb;
7012
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7013
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7014
0
            return -1;
7015
0
        }
7016
30.0k
        if ((config::force_immediate_recycle) ||
7017
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7018
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7019
30.0k
             current_time_ms)) {
7020
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
7021
23.0k
            num_expired++;
7022
23.0k
            recycle_txn_info_keys.emplace_back(k);
7023
23.0k
        }
7024
30.0k
        return 0;
7025
30.0k
    };
7026
7027
    // int 0 for success, 1 for conflict, -1 for error
7028
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7029
23.0k
        std::string_view k1 = k;
7030
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7031
23.0k
        k1.remove_prefix(1); // Remove key space
7032
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7033
23.0k
        int ret = decode_key(&k1, &out);
7034
23.0k
        if (ret != 0) {
7035
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7036
0
            return -1;
7037
0
        }
7038
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7039
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7040
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7041
23.0k
        std::unique_ptr<Transaction> txn;
7042
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7043
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7044
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7045
0
            return -1;
7046
0
        }
7047
        // Remove txn index kv
7048
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
7049
23.0k
        txn->remove(index_key);
7050
        // Remove txn info kv
7051
23.0k
        std::string info_key, info_val;
7052
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7053
23.0k
        err = txn->get(info_key, &info_val);
7054
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7055
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7056
0
            return -1;
7057
0
        }
7058
23.0k
        TxnInfoPB txn_info;
7059
23.0k
        if (!txn_info.ParseFromString(info_val)) {
7060
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7061
0
            return -1;
7062
0
        }
7063
23.0k
        txn->remove(info_key);
7064
        // Remove sub txn index kvs
7065
23.0k
        std::vector<std::string> sub_txn_index_keys;
7066
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7067
23.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7068
23.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
7069
23.0k
        }
7070
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7071
22.9k
            txn->remove(sub_txn_index_key);
7072
22.9k
        }
7073
        // Update txn label
7074
23.0k
        std::string label_key, label_val;
7075
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7076
23.0k
        err = txn->get(label_key, &label_val);
7077
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7078
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7079
0
                         << " err=" << err;
7080
0
            return -1;
7081
0
        }
7082
23.0k
        TxnLabelPB txn_label;
7083
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7084
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7085
0
            return -1;
7086
0
        }
7087
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7088
23.0k
        if (it != txn_label.txn_ids().end()) {
7089
23.0k
            txn_label.mutable_txn_ids()->erase(it);
7090
23.0k
        }
7091
23.0k
        if (txn_label.txn_ids().empty()) {
7092
23.0k
            txn->remove(label_key);
7093
23.0k
            TEST_SYNC_POINT_CALLBACK(
7094
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7095
23.0k
        } else {
7096
73
            if (!txn_label.SerializeToString(&label_val)) {
7097
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7098
0
                return -1;
7099
0
            }
7100
73
            TEST_SYNC_POINT_CALLBACK(
7101
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7102
73
            txn->atomic_set_ver_value(label_key, label_val);
7103
73
            TEST_SYNC_POINT_CALLBACK(
7104
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7105
73
        }
7106
        // Remove recycle txn kv
7107
23.0k
        txn->remove(k);
7108
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7109
23.0k
        err = txn->commit();
7110
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7111
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
7112
62
                TEST_SYNC_POINT_CALLBACK(
7113
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7114
                // log the txn_id and label
7115
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7116
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7117
62
                             << " txn_label=" << txn_info.label();
7118
62
                return 1;
7119
62
            }
7120
62
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7121
0
            return -1;
7122
62
        }
7123
23.0k
        ++num_recycled;
7124
7125
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7126
23.0k
        return 0;
7127
23.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
7028
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7029
1
        std::string_view k1 = k;
7030
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7031
1
        k1.remove_prefix(1); // Remove key space
7032
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7033
1
        int ret = decode_key(&k1, &out);
7034
1
        if (ret != 0) {
7035
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7036
0
            return -1;
7037
0
        }
7038
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7039
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7040
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7041
1
        std::unique_ptr<Transaction> txn;
7042
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7043
1
        if (err != TxnErrorCode::TXN_OK) {
7044
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7045
0
            return -1;
7046
0
        }
7047
        // Remove txn index kv
7048
1
        auto index_key = txn_index_key({instance_id_, txn_id});
7049
1
        txn->remove(index_key);
7050
        // Remove txn info kv
7051
1
        std::string info_key, info_val;
7052
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7053
1
        err = txn->get(info_key, &info_val);
7054
1
        if (err != TxnErrorCode::TXN_OK) {
7055
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7056
0
            return -1;
7057
0
        }
7058
1
        TxnInfoPB txn_info;
7059
1
        if (!txn_info.ParseFromString(info_val)) {
7060
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7061
0
            return -1;
7062
0
        }
7063
1
        txn->remove(info_key);
7064
        // Remove sub txn index kvs
7065
1
        std::vector<std::string> sub_txn_index_keys;
7066
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7067
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7068
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
7069
0
        }
7070
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7071
0
            txn->remove(sub_txn_index_key);
7072
0
        }
7073
        // Update txn label
7074
1
        std::string label_key, label_val;
7075
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7076
1
        err = txn->get(label_key, &label_val);
7077
1
        if (err != TxnErrorCode::TXN_OK) {
7078
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7079
0
                         << " err=" << err;
7080
0
            return -1;
7081
0
        }
7082
1
        TxnLabelPB txn_label;
7083
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7084
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7085
0
            return -1;
7086
0
        }
7087
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7088
1
        if (it != txn_label.txn_ids().end()) {
7089
1
            txn_label.mutable_txn_ids()->erase(it);
7090
1
        }
7091
1
        if (txn_label.txn_ids().empty()) {
7092
1
            txn->remove(label_key);
7093
1
            TEST_SYNC_POINT_CALLBACK(
7094
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7095
1
        } else {
7096
0
            if (!txn_label.SerializeToString(&label_val)) {
7097
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7098
0
                return -1;
7099
0
            }
7100
0
            TEST_SYNC_POINT_CALLBACK(
7101
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7102
0
            txn->atomic_set_ver_value(label_key, label_val);
7103
0
            TEST_SYNC_POINT_CALLBACK(
7104
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7105
0
        }
7106
        // Remove recycle txn kv
7107
1
        txn->remove(k);
7108
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7109
1
        err = txn->commit();
7110
1
        if (err != TxnErrorCode::TXN_OK) {
7111
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
7112
0
                TEST_SYNC_POINT_CALLBACK(
7113
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7114
                // log the txn_id and label
7115
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7116
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7117
0
                             << " txn_label=" << txn_info.label();
7118
0
                return 1;
7119
0
            }
7120
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7121
0
            return -1;
7122
0
        }
7123
1
        ++num_recycled;
7124
7125
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7126
1
        return 0;
7127
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
7028
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7029
23.0k
        std::string_view k1 = k;
7030
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7031
23.0k
        k1.remove_prefix(1); // Remove key space
7032
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7033
23.0k
        int ret = decode_key(&k1, &out);
7034
23.0k
        if (ret != 0) {
7035
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7036
0
            return -1;
7037
0
        }
7038
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7039
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7040
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7041
23.0k
        std::unique_ptr<Transaction> txn;
7042
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7043
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7044
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7045
0
            return -1;
7046
0
        }
7047
        // Remove txn index kv
7048
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
7049
23.0k
        txn->remove(index_key);
7050
        // Remove txn info kv
7051
23.0k
        std::string info_key, info_val;
7052
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7053
23.0k
        err = txn->get(info_key, &info_val);
7054
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7055
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7056
0
            return -1;
7057
0
        }
7058
23.0k
        TxnInfoPB txn_info;
7059
23.0k
        if (!txn_info.ParseFromString(info_val)) {
7060
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7061
0
            return -1;
7062
0
        }
7063
23.0k
        txn->remove(info_key);
7064
        // Remove sub txn index kvs
7065
23.0k
        std::vector<std::string> sub_txn_index_keys;
7066
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7067
23.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7068
23.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
7069
23.0k
        }
7070
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7071
22.9k
            txn->remove(sub_txn_index_key);
7072
22.9k
        }
7073
        // Update txn label
7074
23.0k
        std::string label_key, label_val;
7075
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7076
23.0k
        err = txn->get(label_key, &label_val);
7077
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7078
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7079
0
                         << " err=" << err;
7080
0
            return -1;
7081
0
        }
7082
23.0k
        TxnLabelPB txn_label;
7083
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7084
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7085
0
            return -1;
7086
0
        }
7087
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7088
23.0k
        if (it != txn_label.txn_ids().end()) {
7089
23.0k
            txn_label.mutable_txn_ids()->erase(it);
7090
23.0k
        }
7091
23.0k
        if (txn_label.txn_ids().empty()) {
7092
23.0k
            txn->remove(label_key);
7093
23.0k
            TEST_SYNC_POINT_CALLBACK(
7094
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7095
23.0k
        } else {
7096
73
            if (!txn_label.SerializeToString(&label_val)) {
7097
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7098
0
                return -1;
7099
0
            }
7100
73
            TEST_SYNC_POINT_CALLBACK(
7101
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7102
73
            txn->atomic_set_ver_value(label_key, label_val);
7103
73
            TEST_SYNC_POINT_CALLBACK(
7104
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7105
73
        }
7106
        // Remove recycle txn kv
7107
23.0k
        txn->remove(k);
7108
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7109
23.0k
        err = txn->commit();
7110
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7111
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
7112
62
                TEST_SYNC_POINT_CALLBACK(
7113
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7114
                // log the txn_id and label
7115
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7116
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7117
62
                             << " txn_label=" << txn_info.label();
7118
62
                return 1;
7119
62
            }
7120
62
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7121
0
            return -1;
7122
62
        }
7123
23.0k
        ++num_recycled;
7124
7125
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7126
23.0k
        return 0;
7127
23.0k
    };
7128
7129
19
    auto loop_done = [&]() -> int {
7130
10
        DORIS_CLOUD_DEFER {
7131
10
            recycle_txn_info_keys.clear();
7132
10
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
7130
1
        DORIS_CLOUD_DEFER {
7131
1
            recycle_txn_info_keys.clear();
7132
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
7130
9
        DORIS_CLOUD_DEFER {
7131
9
            recycle_txn_info_keys.clear();
7132
9
        };
7133
10
        TEST_SYNC_POINT_CALLBACK(
7134
10
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
7135
10
                &recycle_txn_info_keys);
7136
23.0k
        for (const auto& k : recycle_txn_info_keys) {
7137
23.0k
            concurrent_delete_executor.add([&]() {
7138
23.0k
                int ret = delete_recycle_txn_kv(k);
7139
23.0k
                if (ret == 1) {
7140
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7141
54
                    for (int i = 1; i <= max_retry; ++i) {
7142
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7143
54
                        ret = delete_recycle_txn_kv(k);
7144
                        // clang-format off
7145
54
                        TEST_SYNC_POINT_CALLBACK(
7146
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
7147
                        // clang-format off
7148
54
                        if (ret != 1) {
7149
18
                            break;
7150
18
                        }
7151
                        // random sleep 0-100 ms to retry
7152
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7153
36
                    }
7154
18
                }
7155
23.0k
                if (ret != 0) {
7156
9
                    LOG_WARNING("failed to delete recycle txn kv")
7157
9
                            .tag("instance id", instance_id_)
7158
9
                            .tag("key", hex(k));
7159
9
                    return -1;
7160
9
                }
7161
23.0k
                return 0;
7162
23.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
7137
1
            concurrent_delete_executor.add([&]() {
7138
1
                int ret = delete_recycle_txn_kv(k);
7139
1
                if (ret == 1) {
7140
0
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7141
0
                    for (int i = 1; i <= max_retry; ++i) {
7142
0
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7143
0
                        ret = delete_recycle_txn_kv(k);
7144
                        // clang-format off
7145
0
                        TEST_SYNC_POINT_CALLBACK(
7146
0
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
7147
                        // clang-format off
7148
0
                        if (ret != 1) {
7149
0
                            break;
7150
0
                        }
7151
                        // random sleep 0-100 ms to retry
7152
0
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7153
0
                    }
7154
0
                }
7155
1
                if (ret != 0) {
7156
0
                    LOG_WARNING("failed to delete recycle txn kv")
7157
0
                            .tag("instance id", instance_id_)
7158
0
                            .tag("key", hex(k));
7159
0
                    return -1;
7160
0
                }
7161
1
                return 0;
7162
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
7137
23.0k
            concurrent_delete_executor.add([&]() {
7138
23.0k
                int ret = delete_recycle_txn_kv(k);
7139
23.0k
                if (ret == 1) {
7140
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7141
54
                    for (int i = 1; i <= max_retry; ++i) {
7142
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7143
54
                        ret = delete_recycle_txn_kv(k);
7144
                        // clang-format off
7145
54
                        TEST_SYNC_POINT_CALLBACK(
7146
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
7147
                        // clang-format off
7148
54
                        if (ret != 1) {
7149
18
                            break;
7150
18
                        }
7151
                        // random sleep 0-100 ms to retry
7152
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7153
36
                    }
7154
18
                }
7155
23.0k
                if (ret != 0) {
7156
9
                    LOG_WARNING("failed to delete recycle txn kv")
7157
9
                            .tag("instance id", instance_id_)
7158
9
                            .tag("key", hex(k));
7159
9
                    return -1;
7160
9
                }
7161
23.0k
                return 0;
7162
23.0k
            });
7163
23.0k
        }
7164
10
        bool finished = true;
7165
10
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7166
23.0k
        for (int r : rets) {
7167
23.0k
            if (r != 0) {
7168
9
                ret = -1;
7169
9
            }
7170
23.0k
        }
7171
7172
10
        ret = finished ? ret : -1;
7173
7174
        // Update metrics after all concurrent tasks completed
7175
10
        metrics_context.total_recycled_num = num_recycled.load();
7176
10
        metrics_context.report();
7177
7178
10
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7179
7180
10
        if (ret != 0) {
7181
3
            LOG_WARNING("recycle txn kv ret!=0")
7182
3
                    .tag("finished", finished)
7183
3
                    .tag("ret", ret)
7184
3
                    .tag("instance_id", instance_id_);
7185
3
            return ret;
7186
3
        }
7187
7
        return ret;
7188
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
7129
1
    auto loop_done = [&]() -> int {
7130
1
        DORIS_CLOUD_DEFER {
7131
1
            recycle_txn_info_keys.clear();
7132
1
        };
7133
1
        TEST_SYNC_POINT_CALLBACK(
7134
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
7135
1
                &recycle_txn_info_keys);
7136
1
        for (const auto& k : recycle_txn_info_keys) {
7137
1
            concurrent_delete_executor.add([&]() {
7138
1
                int ret = delete_recycle_txn_kv(k);
7139
1
                if (ret == 1) {
7140
1
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7141
1
                    for (int i = 1; i <= max_retry; ++i) {
7142
1
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7143
1
                        ret = delete_recycle_txn_kv(k);
7144
                        // clang-format off
7145
1
                        TEST_SYNC_POINT_CALLBACK(
7146
1
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
7147
                        // clang-format off
7148
1
                        if (ret != 1) {
7149
1
                            break;
7150
1
                        }
7151
                        // random sleep 0-100 ms to retry
7152
1
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7153
1
                    }
7154
1
                }
7155
1
                if (ret != 0) {
7156
1
                    LOG_WARNING("failed to delete recycle txn kv")
7157
1
                            .tag("instance id", instance_id_)
7158
1
                            .tag("key", hex(k));
7159
1
                    return -1;
7160
1
                }
7161
1
                return 0;
7162
1
            });
7163
1
        }
7164
1
        bool finished = true;
7165
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7166
1
        for (int r : rets) {
7167
1
            if (r != 0) {
7168
0
                ret = -1;
7169
0
            }
7170
1
        }
7171
7172
1
        ret = finished ? ret : -1;
7173
7174
        // Update metrics after all concurrent tasks completed
7175
1
        metrics_context.total_recycled_num = num_recycled.load();
7176
1
        metrics_context.report();
7177
7178
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7179
7180
1
        if (ret != 0) {
7181
0
            LOG_WARNING("recycle txn kv ret!=0")
7182
0
                    .tag("finished", finished)
7183
0
                    .tag("ret", ret)
7184
0
                    .tag("instance_id", instance_id_);
7185
0
            return ret;
7186
0
        }
7187
1
        return ret;
7188
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
7129
9
    auto loop_done = [&]() -> int {
7130
9
        DORIS_CLOUD_DEFER {
7131
9
            recycle_txn_info_keys.clear();
7132
9
        };
7133
9
        TEST_SYNC_POINT_CALLBACK(
7134
9
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
7135
9
                &recycle_txn_info_keys);
7136
23.0k
        for (const auto& k : recycle_txn_info_keys) {
7137
23.0k
            concurrent_delete_executor.add([&]() {
7138
23.0k
                int ret = delete_recycle_txn_kv(k);
7139
23.0k
                if (ret == 1) {
7140
23.0k
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7141
23.0k
                    for (int i = 1; i <= max_retry; ++i) {
7142
23.0k
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7143
23.0k
                        ret = delete_recycle_txn_kv(k);
7144
                        // clang-format off
7145
23.0k
                        TEST_SYNC_POINT_CALLBACK(
7146
23.0k
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
7147
                        // clang-format off
7148
23.0k
                        if (ret != 1) {
7149
23.0k
                            break;
7150
23.0k
                        }
7151
                        // random sleep 0-100 ms to retry
7152
23.0k
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7153
23.0k
                    }
7154
23.0k
                }
7155
23.0k
                if (ret != 0) {
7156
23.0k
                    LOG_WARNING("failed to delete recycle txn kv")
7157
23.0k
                            .tag("instance id", instance_id_)
7158
23.0k
                            .tag("key", hex(k));
7159
23.0k
                    return -1;
7160
23.0k
                }
7161
23.0k
                return 0;
7162
23.0k
            });
7163
23.0k
        }
7164
9
        bool finished = true;
7165
9
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7166
23.0k
        for (int r : rets) {
7167
23.0k
            if (r != 0) {
7168
9
                ret = -1;
7169
9
            }
7170
23.0k
        }
7171
7172
9
        ret = finished ? ret : -1;
7173
7174
        // Update metrics after all concurrent tasks completed
7175
9
        metrics_context.total_recycled_num = num_recycled.load();
7176
9
        metrics_context.report();
7177
7178
9
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7179
7180
9
        if (ret != 0) {
7181
3
            LOG_WARNING("recycle txn kv ret!=0")
7182
3
                    .tag("finished", finished)
7183
3
                    .tag("ret", ret)
7184
3
                    .tag("instance_id", instance_id_);
7185
3
            return ret;
7186
3
        }
7187
6
        return ret;
7188
9
    };
7189
7190
19
    if (config::enable_recycler_stats_metrics) {
7191
0
        scan_and_statistics_expired_txn_label();
7192
0
    }
7193
    // recycle_func and loop_done for scan and recycle
7194
19
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
7195
19
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
7196
19
}
7197
7198
struct CopyJobIdTuple {
7199
    std::string instance_id;
7200
    std::string stage_id;
7201
    long table_id;
7202
    std::string copy_id;
7203
    std::string stage_path;
7204
};
7205
struct BatchObjStoreAccessor {
7206
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
7207
                          TxnKv* txn_kv)
7208
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
7209
3
    ~BatchObjStoreAccessor() {
7210
3
        if (!paths_.empty()) {
7211
3
            consume();
7212
3
        }
7213
3
    }
7214
7215
    /**
7216
    * To implicitely do batch work and submit the batch delete task to s3
7217
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
7218
    *
7219
    * @param copy_job The protubuf struct consists of the copy job files.
7220
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
7221
    *            it would last until we finish the delete task, here we need pass one string value
7222
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
7223
    */
7224
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
7225
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
7226
5
        auto& file_keys = copy_file_keys_[key];
7227
5
        file_keys.log_trace =
7228
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
7229
5
                            instance_id, stage_id, table_id, copy_id, path);
7230
5
        std::string_view log_trace = file_keys.log_trace;
7231
2.03k
        for (const auto& file : copy_job.object_files()) {
7232
2.03k
            auto relative_path = file.relative_path();
7233
2.03k
            paths_.push_back(relative_path);
7234
2.03k
            file_keys.keys.push_back(copy_file_key(
7235
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
7236
2.03k
            LOG_INFO(log_trace)
7237
2.03k
                    .tag("relative_path", relative_path)
7238
2.03k
                    .tag("batch_count", batch_count_);
7239
2.03k
        }
7240
5
        LOG_INFO(log_trace)
7241
5
                .tag("objects_num", copy_job.object_files().size())
7242
5
                .tag("batch_count", batch_count_);
7243
        // 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
7244
        // recommend using delete objects when objects num is less than 10)
7245
5
        if (paths_.size() < 1000) {
7246
3
            return;
7247
3
        }
7248
2
        consume();
7249
2
    }
7250
7251
private:
7252
5
    void consume() {
7253
5
        DORIS_CLOUD_DEFER {
7254
5
            paths_.clear();
7255
5
            copy_file_keys_.clear();
7256
5
            batch_count_++;
7257
7258
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
7259
5
                        batch_count_);
7260
5
        };
7261
7262
5
        StopWatch sw;
7263
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
7264
5
        if (0 != accessor_->delete_files(paths_)) {
7265
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
7266
2
                        paths_.size(), batch_count_, sw.elapsed_us());
7267
2
            return;
7268
2
        }
7269
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
7270
3
                    paths_.size(), batch_count_, sw.elapsed_us());
7271
        // delete fdb's keys
7272
3
        for (auto& file_keys : copy_file_keys_) {
7273
3
            auto& [log_trace, keys] = file_keys.second;
7274
3
            std::unique_ptr<Transaction> txn;
7275
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
7276
0
                LOG(WARNING) << "failed to create txn";
7277
0
                continue;
7278
0
            }
7279
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7280
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7281
            // limited, should not cause the txn commit failed.
7282
1.02k
            for (const auto& key : keys) {
7283
1.02k
                txn->remove(key);
7284
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
7285
1.02k
            }
7286
3
            txn->remove(file_keys.first);
7287
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
7288
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
7289
0
                continue;
7290
0
            }
7291
3
        }
7292
3
    }
7293
    std::shared_ptr<StorageVaultAccessor> accessor_;
7294
    // the path of the s3 files to be deleted
7295
    std::vector<std::string> paths_;
7296
    struct CopyFiles {
7297
        std::string log_trace;
7298
        std::vector<std::string> keys;
7299
    };
7300
    // pair<std::string, std::vector<std::string>>
7301
    // first: instance_id_ stage_id table_id query_id
7302
    // second: keys to be deleted
7303
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
7304
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
7305
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
7306
    // which can together uniquely identifies different tasks for tracing log
7307
    uint64_t& batch_count_;
7308
    TxnKv* txn_kv_;
7309
};
7310
7311
13
int InstanceRecycler::recycle_copy_jobs() {
7312
13
    int64_t num_scanned = 0;
7313
13
    int64_t num_finished = 0;
7314
13
    int64_t num_expired = 0;
7315
13
    int64_t num_recycled = 0;
7316
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
7317
13
    uint64_t batch_count = 0;
7318
13
    const std::string task_name = "recycle_copy_jobs";
7319
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7320
7321
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
7322
7323
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7324
13
    register_recycle_task(task_name, start_time);
7325
7326
13
    DORIS_CLOUD_DEFER {
7327
13
        unregister_recycle_task(task_name);
7328
13
        int64_t cost =
7329
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7330
13
        metrics_context.finish_report();
7331
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7332
13
                .tag("instance_id", instance_id_)
7333
13
                .tag("num_scanned", num_scanned)
7334
13
                .tag("num_finished", num_finished)
7335
13
                .tag("num_expired", num_expired)
7336
13
                .tag("num_recycled", num_recycled);
7337
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
7326
13
    DORIS_CLOUD_DEFER {
7327
13
        unregister_recycle_task(task_name);
7328
13
        int64_t cost =
7329
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7330
13
        metrics_context.finish_report();
7331
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7332
13
                .tag("instance_id", instance_id_)
7333
13
                .tag("num_scanned", num_scanned)
7334
13
                .tag("num_finished", num_finished)
7335
13
                .tag("num_expired", num_expired)
7336
13
                .tag("num_recycled", num_recycled);
7337
13
    };
7338
7339
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7340
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7341
13
    std::string key0;
7342
13
    std::string key1;
7343
13
    copy_job_key(key_info0, &key0);
7344
13
    copy_job_key(key_info1, &key1);
7345
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
7346
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
7347
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
7348
16
                         this](std::string_view k, std::string_view v) -> int {
7349
16
        ++num_scanned;
7350
16
        CopyJobPB copy_job;
7351
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7352
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7353
0
            return -1;
7354
0
        }
7355
7356
        // decode copy job key
7357
16
        auto k1 = k;
7358
16
        k1.remove_prefix(1);
7359
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7360
16
        decode_key(&k1, &out);
7361
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7362
        // -> CopyJobPB
7363
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7364
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7365
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7366
7367
16
        bool check_storage = true;
7368
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7369
12
            ++num_finished;
7370
7371
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7372
7
                auto it = stage_accessor_map.find(stage_id);
7373
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7374
7
                std::string_view path;
7375
7
                if (it != stage_accessor_map.end()) {
7376
2
                    accessor = it->second;
7377
5
                } else {
7378
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7379
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7380
5
                                                      &inner_accessor);
7381
5
                    if (ret < 0) { // error
7382
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7383
0
                        return -1;
7384
5
                    } else if (ret == 0) {
7385
3
                        path = inner_accessor->uri();
7386
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7387
3
                                inner_accessor, batch_count, txn_kv_.get());
7388
3
                        stage_accessor_map.emplace(stage_id, accessor);
7389
3
                    } else { // stage not found, skip check storage
7390
2
                        check_storage = false;
7391
2
                    }
7392
5
                }
7393
7
                if (check_storage) {
7394
                    // TODO delete objects with key and etag is not supported
7395
5
                    accessor->add(std::move(copy_job), std::string(k),
7396
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7397
5
                    return 0;
7398
5
                }
7399
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7400
5
                int64_t current_time =
7401
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7402
5
                if (copy_job.finish_time_ms() > 0) {
7403
2
                    if (!config::force_immediate_recycle &&
7404
2
                        current_time < copy_job.finish_time_ms() +
7405
2
                                               config::copy_job_max_retention_second * 1000) {
7406
1
                        return 0;
7407
1
                    }
7408
3
                } else {
7409
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7410
3
                    if (!config::force_immediate_recycle &&
7411
3
                        current_time < copy_job.start_time_ms() +
7412
3
                                               config::copy_job_max_retention_second * 1000) {
7413
1
                        return 0;
7414
1
                    }
7415
3
                }
7416
5
            }
7417
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7418
4
            int64_t current_time =
7419
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7420
            // if copy job is timeout: delete all copy file kvs and copy job kv
7421
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7422
2
                return 0;
7423
2
            }
7424
2
            ++num_expired;
7425
2
        }
7426
7427
        // delete all copy files
7428
7
        std::vector<std::string> copy_file_keys;
7429
70
        for (auto& file : copy_job.object_files()) {
7430
70
            copy_file_keys.push_back(copy_file_key(
7431
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7432
70
        }
7433
7
        std::unique_ptr<Transaction> txn;
7434
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7435
0
            LOG(WARNING) << "failed to create txn";
7436
0
            return -1;
7437
0
        }
7438
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7439
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7440
        // limited, should not cause the txn commit failed.
7441
70
        for (const auto& key : copy_file_keys) {
7442
70
            txn->remove(key);
7443
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7444
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7445
70
                      << ", query_id=" << copy_id;
7446
70
        }
7447
7
        txn->remove(k);
7448
7
        TxnErrorCode err = txn->commit();
7449
7
        if (err != TxnErrorCode::TXN_OK) {
7450
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7451
0
            return -1;
7452
0
        }
7453
7454
7
        metrics_context.total_recycled_num = ++num_recycled;
7455
7
        metrics_context.report();
7456
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7457
7
        return 0;
7458
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
7348
16
                         this](std::string_view k, std::string_view v) -> int {
7349
16
        ++num_scanned;
7350
16
        CopyJobPB copy_job;
7351
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7352
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7353
0
            return -1;
7354
0
        }
7355
7356
        // decode copy job key
7357
16
        auto k1 = k;
7358
16
        k1.remove_prefix(1);
7359
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7360
16
        decode_key(&k1, &out);
7361
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7362
        // -> CopyJobPB
7363
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7364
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7365
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7366
7367
16
        bool check_storage = true;
7368
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7369
12
            ++num_finished;
7370
7371
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7372
7
                auto it = stage_accessor_map.find(stage_id);
7373
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7374
7
                std::string_view path;
7375
7
                if (it != stage_accessor_map.end()) {
7376
2
                    accessor = it->second;
7377
5
                } else {
7378
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7379
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7380
5
                                                      &inner_accessor);
7381
5
                    if (ret < 0) { // error
7382
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7383
0
                        return -1;
7384
5
                    } else if (ret == 0) {
7385
3
                        path = inner_accessor->uri();
7386
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7387
3
                                inner_accessor, batch_count, txn_kv_.get());
7388
3
                        stage_accessor_map.emplace(stage_id, accessor);
7389
3
                    } else { // stage not found, skip check storage
7390
2
                        check_storage = false;
7391
2
                    }
7392
5
                }
7393
7
                if (check_storage) {
7394
                    // TODO delete objects with key and etag is not supported
7395
5
                    accessor->add(std::move(copy_job), std::string(k),
7396
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7397
5
                    return 0;
7398
5
                }
7399
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7400
5
                int64_t current_time =
7401
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7402
5
                if (copy_job.finish_time_ms() > 0) {
7403
2
                    if (!config::force_immediate_recycle &&
7404
2
                        current_time < copy_job.finish_time_ms() +
7405
2
                                               config::copy_job_max_retention_second * 1000) {
7406
1
                        return 0;
7407
1
                    }
7408
3
                } else {
7409
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7410
3
                    if (!config::force_immediate_recycle &&
7411
3
                        current_time < copy_job.start_time_ms() +
7412
3
                                               config::copy_job_max_retention_second * 1000) {
7413
1
                        return 0;
7414
1
                    }
7415
3
                }
7416
5
            }
7417
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7418
4
            int64_t current_time =
7419
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7420
            // if copy job is timeout: delete all copy file kvs and copy job kv
7421
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7422
2
                return 0;
7423
2
            }
7424
2
            ++num_expired;
7425
2
        }
7426
7427
        // delete all copy files
7428
7
        std::vector<std::string> copy_file_keys;
7429
70
        for (auto& file : copy_job.object_files()) {
7430
70
            copy_file_keys.push_back(copy_file_key(
7431
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7432
70
        }
7433
7
        std::unique_ptr<Transaction> txn;
7434
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7435
0
            LOG(WARNING) << "failed to create txn";
7436
0
            return -1;
7437
0
        }
7438
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7439
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7440
        // limited, should not cause the txn commit failed.
7441
70
        for (const auto& key : copy_file_keys) {
7442
70
            txn->remove(key);
7443
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7444
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7445
70
                      << ", query_id=" << copy_id;
7446
70
        }
7447
7
        txn->remove(k);
7448
7
        TxnErrorCode err = txn->commit();
7449
7
        if (err != TxnErrorCode::TXN_OK) {
7450
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7451
0
            return -1;
7452
0
        }
7453
7454
7
        metrics_context.total_recycled_num = ++num_recycled;
7455
7
        metrics_context.report();
7456
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7457
7
        return 0;
7458
7
    };
7459
7460
13
    if (config::enable_recycler_stats_metrics) {
7461
0
        scan_and_statistics_copy_jobs();
7462
0
    }
7463
    // recycle_func and loop_done for scan and recycle
7464
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
7465
13
}
7466
7467
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
7468
                                             const StagePB::StageType& stage_type,
7469
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
7470
5
#ifdef UNIT_TEST
7471
    // In unit test, external use the same accessor as the internal stage
7472
5
    auto it = accessor_map_.find(stage_id);
7473
5
    if (it != accessor_map_.end()) {
7474
3
        *accessor = it->second;
7475
3
    } else {
7476
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
7477
2
        return 1;
7478
2
    }
7479
#else
7480
    // init s3 accessor and add to accessor map
7481
    auto stage_it =
7482
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
7483
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
7484
7485
    if (stage_it == instance_info_.stages().end()) {
7486
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
7487
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
7488
        return 1;
7489
    }
7490
7491
    const auto& object_store_info = stage_it->obj_info();
7492
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
7493
7494
    S3Conf s3_conf;
7495
    if (stage_type == StagePB::EXTERNAL) {
7496
        if (stage_access_type == StagePB::AKSK) {
7497
            auto conf = S3Conf::from_obj_store_info(object_store_info);
7498
            if (!conf) {
7499
                return -1;
7500
            }
7501
7502
            s3_conf = std::move(*conf);
7503
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
7504
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
7505
            if (!conf) {
7506
                return -1;
7507
            }
7508
7509
            s3_conf = std::move(*conf);
7510
            if (instance_info_.ram_user().has_encryption_info()) {
7511
                AkSkPair plain_ak_sk_pair;
7512
                int ret = decrypt_ak_sk_helper(
7513
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
7514
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
7515
                if (ret != 0) {
7516
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
7517
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
7518
                    return -1;
7519
                }
7520
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
7521
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
7522
            } else {
7523
                s3_conf.ak = instance_info_.ram_user().ak();
7524
                s3_conf.sk = instance_info_.ram_user().sk();
7525
            }
7526
        } else {
7527
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
7528
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
7529
            return -1;
7530
        }
7531
    } else if (stage_type == StagePB::INTERNAL) {
7532
        int idx = stoi(object_store_info.id());
7533
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7534
            LOG(WARNING) << "invalid idx: " << idx;
7535
            return -1;
7536
        }
7537
7538
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7539
        auto conf = S3Conf::from_obj_store_info(old_obj);
7540
        if (!conf) {
7541
            return -1;
7542
        }
7543
7544
        s3_conf = std::move(*conf);
7545
        s3_conf.prefix = object_store_info.prefix();
7546
    } else {
7547
        LOG(WARNING) << "unknown stage type " << stage_type;
7548
        return -1;
7549
    }
7550
7551
    std::shared_ptr<S3Accessor> s3_accessor;
7552
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
7553
    if (ret != 0) {
7554
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
7555
        return -1;
7556
    }
7557
7558
    *accessor = std::move(s3_accessor);
7559
#endif
7560
3
    return 0;
7561
5
}
7562
7563
11
int InstanceRecycler::recycle_stage() {
7564
11
    int64_t num_scanned = 0;
7565
11
    int64_t num_recycled = 0;
7566
11
    const std::string task_name = "recycle_stage";
7567
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7568
7569
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
7570
7571
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7572
11
    register_recycle_task(task_name, start_time);
7573
7574
11
    DORIS_CLOUD_DEFER {
7575
11
        unregister_recycle_task(task_name);
7576
11
        int64_t cost =
7577
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7578
11
        metrics_context.finish_report();
7579
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7580
11
                .tag("instance_id", instance_id_)
7581
11
                .tag("num_scanned", num_scanned)
7582
11
                .tag("num_recycled", num_recycled);
7583
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
7574
11
    DORIS_CLOUD_DEFER {
7575
11
        unregister_recycle_task(task_name);
7576
11
        int64_t cost =
7577
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7578
11
        metrics_context.finish_report();
7579
        LOG_WARNING("recycle stage, cost={}s", cost)
7580
11
                .tag("instance_id", instance_id_)
7581
11
                .tag("num_scanned", num_scanned)
7582
11
                .tag("num_recycled", num_recycled);
7583
11
    };
7584
7585
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7586
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7587
11
    std::string key0 = recycle_stage_key(key_info0);
7588
11
    std::string key1 = recycle_stage_key(key_info1);
7589
7590
11
    std::vector<std::string_view> stage_keys;
7591
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
7592
11
                         this](std::string_view k, std::string_view v) -> int {
7593
1
        ++num_scanned;
7594
1
        RecycleStagePB recycle_stage;
7595
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7596
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7597
0
            return -1;
7598
0
        }
7599
7600
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7601
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7602
0
            LOG(WARNING) << "invalid idx: " << idx;
7603
0
            return -1;
7604
0
        }
7605
7606
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7607
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7608
1
                [&] {
7609
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7610
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7611
1
                    if (!s3_conf) {
7612
1
                        return -1;
7613
1
                    }
7614
7615
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7616
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7617
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7618
1
                    if (ret != 0) {
7619
1
                        return -1;
7620
1
                    }
7621
7622
1
                    accessor = std::move(s3_accessor);
7623
1
                    return 0;
7624
1
                }(),
7625
1
                "recycle_stage:get_accessor", &accessor);
7626
7627
1
        if (ret != 0) {
7628
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7629
0
            return ret;
7630
0
        }
7631
7632
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7633
1
                .tag("instance_id", instance_id_)
7634
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7635
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7636
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7637
1
                .tag("obj_info_id", idx)
7638
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7639
1
        ret = accessor->delete_all();
7640
1
        if (ret != 0) {
7641
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7642
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7643
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7644
0
                         << ", ret=" << ret;
7645
0
            return -1;
7646
0
        }
7647
1
        metrics_context.total_recycled_num = ++num_recycled;
7648
1
        metrics_context.report();
7649
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7650
1
        stage_keys.push_back(k);
7651
1
        return 0;
7652
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7592
1
                         this](std::string_view k, std::string_view v) -> int {
7593
1
        ++num_scanned;
7594
1
        RecycleStagePB recycle_stage;
7595
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7596
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7597
0
            return -1;
7598
0
        }
7599
7600
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7601
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7602
0
            LOG(WARNING) << "invalid idx: " << idx;
7603
0
            return -1;
7604
0
        }
7605
7606
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7607
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7608
1
                [&] {
7609
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7610
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7611
1
                    if (!s3_conf) {
7612
1
                        return -1;
7613
1
                    }
7614
7615
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7616
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7617
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7618
1
                    if (ret != 0) {
7619
1
                        return -1;
7620
1
                    }
7621
7622
1
                    accessor = std::move(s3_accessor);
7623
1
                    return 0;
7624
1
                }(),
7625
1
                "recycle_stage:get_accessor", &accessor);
7626
7627
1
        if (ret != 0) {
7628
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7629
0
            return ret;
7630
0
        }
7631
7632
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7633
1
                .tag("instance_id", instance_id_)
7634
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7635
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7636
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7637
1
                .tag("obj_info_id", idx)
7638
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7639
1
        ret = accessor->delete_all();
7640
1
        if (ret != 0) {
7641
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7642
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7643
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7644
0
                         << ", ret=" << ret;
7645
0
            return -1;
7646
0
        }
7647
1
        metrics_context.total_recycled_num = ++num_recycled;
7648
1
        metrics_context.report();
7649
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7650
1
        stage_keys.push_back(k);
7651
1
        return 0;
7652
1
    };
7653
7654
11
    auto loop_done = [&stage_keys, this]() -> int {
7655
1
        if (stage_keys.empty()) return 0;
7656
1
        DORIS_CLOUD_DEFER {
7657
1
            stage_keys.clear();
7658
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
7656
1
        DORIS_CLOUD_DEFER {
7657
1
            stage_keys.clear();
7658
1
        };
7659
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7660
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7661
0
            return -1;
7662
0
        }
7663
1
        return 0;
7664
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
7654
1
    auto loop_done = [&stage_keys, this]() -> int {
7655
1
        if (stage_keys.empty()) return 0;
7656
1
        DORIS_CLOUD_DEFER {
7657
1
            stage_keys.clear();
7658
1
        };
7659
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7660
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7661
0
            return -1;
7662
0
        }
7663
1
        return 0;
7664
1
    };
7665
11
    if (config::enable_recycler_stats_metrics) {
7666
0
        scan_and_statistics_stage();
7667
0
    }
7668
    // recycle_func and loop_done for scan and recycle
7669
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
7670
11
}
7671
7672
10
int InstanceRecycler::recycle_expired_stage_objects() {
7673
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
7674
7675
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7676
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7677
7678
10
    DORIS_CLOUD_DEFER {
7679
10
        int64_t cost =
7680
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7681
10
        metrics_context.finish_report();
7682
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7683
10
                .tag("instance_id", instance_id_);
7684
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
7678
10
    DORIS_CLOUD_DEFER {
7679
10
        int64_t cost =
7680
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7681
10
        metrics_context.finish_report();
7682
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7683
10
                .tag("instance_id", instance_id_);
7684
10
    };
7685
7686
10
    int ret = 0;
7687
7688
10
    if (config::enable_recycler_stats_metrics) {
7689
0
        scan_and_statistics_expired_stage_objects();
7690
0
    }
7691
7692
10
    for (const auto& stage : instance_info_.stages()) {
7693
0
        std::stringstream ss;
7694
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
7695
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
7696
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
7697
0
           << ", prefix=" << stage.obj_info().prefix();
7698
7699
0
        if (stopped()) {
7700
0
            break;
7701
0
        }
7702
0
        if (stage.type() == StagePB::EXTERNAL) {
7703
0
            continue;
7704
0
        }
7705
0
        int idx = stoi(stage.obj_info().id());
7706
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7707
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
7708
0
            continue;
7709
0
        }
7710
7711
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7712
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7713
0
        if (!s3_conf) {
7714
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
7715
0
            continue;
7716
0
        }
7717
7718
0
        s3_conf->prefix = stage.obj_info().prefix();
7719
0
        std::shared_ptr<S3Accessor> accessor;
7720
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
7721
0
        if (ret1 != 0) {
7722
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
7723
0
            ret = -1;
7724
0
            continue;
7725
0
        }
7726
7727
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7728
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
7729
0
            ret = -1;
7730
0
            continue;
7731
0
        }
7732
7733
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
7734
0
        int64_t expiration_time =
7735
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
7736
0
                config::internal_stage_objects_expire_time_second;
7737
0
        if (config::force_immediate_recycle) {
7738
0
            expiration_time = INT64_MAX;
7739
0
        }
7740
0
        ret1 = accessor->delete_all(expiration_time);
7741
0
        if (ret1 != 0) {
7742
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
7743
0
                         << ss.str();
7744
0
            ret = -1;
7745
0
            continue;
7746
0
        }
7747
0
        metrics_context.total_recycled_num++;
7748
0
        metrics_context.report();
7749
0
    }
7750
10
    return ret;
7751
10
}
7752
7753
256
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
7754
256
    std::lock_guard lock(recycle_tasks_mutex);
7755
256
    running_recycle_tasks[task_name] = start_time;
7756
256
}
7757
7758
256
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
7759
256
    std::lock_guard lock(recycle_tasks_mutex);
7760
256
    DCHECK(running_recycle_tasks[task_name] > 0);
7761
256
    running_recycle_tasks.erase(task_name);
7762
256
}
7763
7764
3
bool InstanceRecycler::check_recycle_tasks() {
7765
3
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
7766
3
    {
7767
3
        std::lock_guard lock(recycle_tasks_mutex);
7768
3
        tmp_running_recycle_tasks = running_recycle_tasks;
7769
3
    }
7770
7771
3
    bool found = false;
7772
3
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7773
3
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
7774
2
        int64_t cost = now - start_time;
7775
2
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
7776
2
            LOG_INFO("recycle task cost too much time cost={}s", cost)
7777
2
                    .tag("instance_id", instance_id_)
7778
2
                    .tag("task", task_name);
7779
2
            found = true;
7780
2
        }
7781
2
    }
7782
7783
3
    return found;
7784
3
}
7785
7786
// Scan and statistics indexes that need to be recycled
7787
1
int InstanceRecycler::scan_and_statistics_indexes() {
7788
1
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
7789
1
    RecyclerMetricsContext stream_metrics_context(instance_id_, "recycle_stream");
7790
7791
1
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
7792
1
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
7793
1
    std::string index_key0;
7794
1
    std::string index_key1;
7795
1
    recycle_index_key(index_key_info0, &index_key0);
7796
1
    recycle_index_key(index_key_info1, &index_key1);
7797
1
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7798
7799
1
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7800
1
        RecycleIndexPB index_pb;
7801
1
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7802
0
            return 0;
7803
0
        }
7804
1
        int64_t current_time = ::time(nullptr);
7805
1
        if (current_time <
7806
1
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7807
0
            return 0;
7808
0
        }
7809
        // decode index_id
7810
1
        auto k1 = k;
7811
1
        k1.remove_prefix(1);
7812
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7813
1
        decode_key(&k1, &out);
7814
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7815
1
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7816
1
        std::unique_ptr<Transaction> txn;
7817
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7818
1
        if (err != TxnErrorCode::TXN_OK) {
7819
0
            return 0;
7820
0
        }
7821
1
        std::string val;
7822
1
        err = txn->get(k, &val);
7823
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7824
0
            return 0;
7825
0
        }
7826
1
        if (err != TxnErrorCode::TXN_OK) {
7827
0
            return 0;
7828
0
        }
7829
1
        index_pb.Clear();
7830
1
        if (!index_pb.ParseFromString(val)) {
7831
0
            return 0;
7832
0
        }
7833
1
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
7834
1
            if (!index_pb.has_db_id() || !index_pb.has_stream_db_id()) {
7835
0
                LOG_WARNING("table stream recycle index is missing binding")
7836
0
                        .tag("instance_id", instance_id_)
7837
0
                        .tag("stream_id", index_id);
7838
0
                return 0;
7839
0
            }
7840
2
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7841
2
                std::string end = prefix;
7842
2
                end.push_back('\xff');
7843
2
                auto count_offset = [&stream_metrics_context](std::string_view key,
7844
6
                                                              std::string_view value) {
7845
6
                    stream_metrics_context.total_need_recycle_num++;
7846
6
                    stream_metrics_context.total_need_recycle_data_size +=
7847
6
                            key.size() + value.size();
7848
6
                    return 0;
7849
6
                };
Unexecuted instantiation: recycler.cpp:_ZZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_ENKUlS6_S6_E_clES6_S6_
recycler_test.cpp:_ZZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_ENKUlS6_S6_E_clES6_S6_
Line
Count
Source
7844
6
                                                              std::string_view value) {
7845
6
                    stream_metrics_context.total_need_recycle_num++;
7846
6
                    stream_metrics_context.total_need_recycle_data_size +=
7847
6
                            key.size() + value.size();
7848
6
                    return 0;
7849
6
                };
7850
2
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7851
2
            };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_
Line
Count
Source
7840
2
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7841
2
                std::string end = prefix;
7842
2
                end.push_back('\xff');
7843
2
                auto count_offset = [&stream_metrics_context](std::string_view key,
7844
2
                                                              std::string_view value) {
7845
2
                    stream_metrics_context.total_need_recycle_num++;
7846
2
                    stream_metrics_context.total_need_recycle_data_size +=
7847
2
                            key.size() + value.size();
7848
2
                    return 0;
7849
2
                };
7850
2
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7851
2
            };
7852
1
            const std::string latest_prefix = table_stream_offset_key_prefix(
7853
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7854
1
                    index_id);
7855
1
            const std::string versioned_prefix = versioned::table_stream_offset_key_prefix(
7856
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7857
1
                    index_id);
7858
1
            if (scan_offset_prefix(latest_prefix) != 0 ||
7859
1
                scan_offset_prefix(versioned_prefix) != 0) {
7860
0
                LOG_WARNING("failed to scan table stream offsets for recycle statistics")
7861
0
                        .tag("instance_id", instance_id_)
7862
0
                        .tag("stream_id", index_id);
7863
0
            }
7864
1
            return 0;
7865
1
        }
7866
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7867
0
            return 0;
7868
0
        }
7869
0
        metrics_context.total_need_recycle_num++;
7870
0
        return 0;
7871
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7799
1
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7800
1
        RecycleIndexPB index_pb;
7801
1
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7802
0
            return 0;
7803
0
        }
7804
1
        int64_t current_time = ::time(nullptr);
7805
1
        if (current_time <
7806
1
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7807
0
            return 0;
7808
0
        }
7809
        // decode index_id
7810
1
        auto k1 = k;
7811
1
        k1.remove_prefix(1);
7812
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7813
1
        decode_key(&k1, &out);
7814
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7815
1
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7816
1
        std::unique_ptr<Transaction> txn;
7817
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7818
1
        if (err != TxnErrorCode::TXN_OK) {
7819
0
            return 0;
7820
0
        }
7821
1
        std::string val;
7822
1
        err = txn->get(k, &val);
7823
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7824
0
            return 0;
7825
0
        }
7826
1
        if (err != TxnErrorCode::TXN_OK) {
7827
0
            return 0;
7828
0
        }
7829
1
        index_pb.Clear();
7830
1
        if (!index_pb.ParseFromString(val)) {
7831
0
            return 0;
7832
0
        }
7833
1
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
7834
1
            if (!index_pb.has_db_id() || !index_pb.has_stream_db_id()) {
7835
0
                LOG_WARNING("table stream recycle index is missing binding")
7836
0
                        .tag("instance_id", instance_id_)
7837
0
                        .tag("stream_id", index_id);
7838
0
                return 0;
7839
0
            }
7840
1
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7841
1
                std::string end = prefix;
7842
1
                end.push_back('\xff');
7843
1
                auto count_offset = [&stream_metrics_context](std::string_view key,
7844
1
                                                              std::string_view value) {
7845
1
                    stream_metrics_context.total_need_recycle_num++;
7846
1
                    stream_metrics_context.total_need_recycle_data_size +=
7847
1
                            key.size() + value.size();
7848
1
                    return 0;
7849
1
                };
7850
1
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7851
1
            };
7852
1
            const std::string latest_prefix = table_stream_offset_key_prefix(
7853
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7854
1
                    index_id);
7855
1
            const std::string versioned_prefix = versioned::table_stream_offset_key_prefix(
7856
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7857
1
                    index_id);
7858
1
            if (scan_offset_prefix(latest_prefix) != 0 ||
7859
1
                scan_offset_prefix(versioned_prefix) != 0) {
7860
0
                LOG_WARNING("failed to scan table stream offsets for recycle statistics")
7861
0
                        .tag("instance_id", instance_id_)
7862
0
                        .tag("stream_id", index_id);
7863
0
            }
7864
1
            return 0;
7865
1
        }
7866
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7867
0
            return 0;
7868
0
        }
7869
0
        metrics_context.total_need_recycle_num++;
7870
0
        return 0;
7871
0
    };
7872
7873
1
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
7874
1
    metrics_context.report(true);
7875
1
    stream_metrics_context.report(true);
7876
1
    segment_metrics_context_.report(true);
7877
1
    tablet_metrics_context_.report(true);
7878
1
    return ret;
7879
1
}
7880
7881
// Scan and statistics partitions that need to be recycled
7882
0
int InstanceRecycler::scan_and_statistics_partitions() {
7883
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
7884
7885
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
7886
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
7887
0
    std::string part_key0;
7888
0
    std::string part_key1;
7889
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7890
7891
0
    recycle_partition_key(part_key_info0, &part_key0);
7892
0
    recycle_partition_key(part_key_info1, &part_key1);
7893
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
7894
0
        RecyclePartitionPB part_pb;
7895
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
7896
0
            return 0;
7897
0
        }
7898
0
        int64_t current_time = ::time(nullptr);
7899
0
        if (current_time <
7900
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
7901
0
            return 0;
7902
0
        }
7903
        // decode partition_id
7904
0
        auto k1 = k;
7905
0
        k1.remove_prefix(1);
7906
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7907
0
        decode_key(&k1, &out);
7908
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
7909
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
7910
        // Change state to RECYCLING
7911
0
        std::unique_ptr<Transaction> txn;
7912
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7913
0
        if (err != TxnErrorCode::TXN_OK) {
7914
0
            return 0;
7915
0
        }
7916
0
        std::string val;
7917
0
        err = txn->get(k, &val);
7918
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7919
0
            return 0;
7920
0
        }
7921
0
        if (err != TxnErrorCode::TXN_OK) {
7922
0
            return 0;
7923
0
        }
7924
0
        part_pb.Clear();
7925
0
        if (!part_pb.ParseFromString(val)) {
7926
0
            return 0;
7927
0
        }
7928
        // Partitions with PREPARED state MUST have no data
7929
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
7930
0
        int ret = 0;
7931
0
        for (int64_t index_id : part_pb.index_id()) {
7932
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
7933
0
                                            partition_id, is_empty_tablet) != 0) {
7934
0
                ret = 0;
7935
0
            }
7936
0
        }
7937
0
        metrics_context.total_need_recycle_num++;
7938
0
        return ret;
7939
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_
7940
7941
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
7942
0
    metrics_context.report(true);
7943
0
    segment_metrics_context_.report(true);
7944
0
    tablet_metrics_context_.report(true);
7945
0
    return ret;
7946
0
}
7947
7948
// Scan and statistics rowsets that need to be recycled
7949
0
int InstanceRecycler::scan_and_statistics_rowsets() {
7950
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
7951
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
7952
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
7953
0
    std::string recyc_rs_key0;
7954
0
    std::string recyc_rs_key1;
7955
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
7956
0
                recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
7957
0
       int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7958
7959
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
7960
0
        RecycleRowsetPB rowset;
7961
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7962
0
            return 0;
7963
0
        }
7964
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
7965
0
        int64_t current_time = ::time(nullptr);
7966
0
        if (current_time <
7967
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
7968
0
            return 0;
7969
0
        }
7970
7971
0
        if (!rowset.has_type()) {
7972
0
            if (!rowset.has_resource_id()) [[unlikely]] {
7973
0
                return 0;
7974
0
            }
7975
0
            if (rowset.resource_id().empty()) [[unlikely]] {
7976
0
                return 0;
7977
0
            }
7978
0
            metrics_context.total_need_recycle_num++;
7979
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7980
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
7981
0
            segment_metrics_context_.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7982
0
            return 0;
7983
0
        }
7984
7985
0
        if (config::enable_mark_delete_rowset_before_recycle &&
7986
0
            rowset.type() == RecycleRowsetPB::PREPARE &&
7987
0
            (!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled())) {
7988
0
            return 0;
7989
0
        }
7990
7991
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
7992
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
7993
0
                return 0;
7994
0
            }
7995
0
        }
7996
0
        metrics_context.total_need_recycle_num++;
7997
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
7998
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
7999
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
8000
0
        return 0;
8001
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_
8002
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
8003
0
    metrics_context.report(true);
8004
0
    segment_metrics_context_.report(true);
8005
0
    return ret;
8006
0
}
8007
8008
// Scan and statistics tmp_rowsets that need to be recycled
8009
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
8010
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
8011
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
8012
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
8013
0
    std::string tmp_rs_key0;
8014
0
    std::string tmp_rs_key1;
8015
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
8016
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
8017
8018
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8019
8020
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
8021
0
        doris::RowsetMetaCloudPB rowset;
8022
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
8023
0
            return 0;
8024
0
        }
8025
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
8026
0
        int64_t current_time = ::time(nullptr);
8027
0
        if (current_time < expiration) {
8028
0
            return 0;
8029
0
        }
8030
8031
0
        DCHECK_GT(rowset.txn_id(), 0)
8032
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
8033
8034
0
        if(!rowset.has_is_recycled() || !rowset.is_recycled()) {
8035
0
            return 0;
8036
0
        }
8037
8038
0
        if (!rowset.has_resource_id()) {
8039
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
8040
0
                return 0;
8041
0
            }
8042
0
            return 0;
8043
0
        }
8044
8045
0
        metrics_context.total_need_recycle_num++;
8046
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
8047
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
8048
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
8049
0
        return 0;
8050
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_
8051
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
8052
0
    metrics_context.report(true);
8053
0
    segment_metrics_context_.report(true);
8054
0
    return ret;
8055
0
}
8056
8057
// Scan and statistics abort_timeout_txn that need to be recycled
8058
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
8059
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
8060
8061
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
8062
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
8063
0
    std::string begin_txn_running_key;
8064
0
    std::string end_txn_running_key;
8065
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
8066
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
8067
8068
0
    int64_t current_time =
8069
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8070
8071
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
8072
0
                                               std::string_view k, std::string_view v) -> int {
8073
0
        std::unique_ptr<Transaction> txn;
8074
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8075
0
        if (err != TxnErrorCode::TXN_OK) {
8076
0
            return 0;
8077
0
        }
8078
0
        std::string_view k1 = k;
8079
0
        k1.remove_prefix(1);
8080
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8081
0
        if (decode_key(&k1, &out) != 0) {
8082
0
            return 0;
8083
0
        }
8084
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
8085
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
8086
        // Update txn_info
8087
0
        std::string txn_inf_key, txn_inf_val;
8088
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
8089
0
        err = txn->get(txn_inf_key, &txn_inf_val);
8090
0
        if (err != TxnErrorCode::TXN_OK) {
8091
0
            return 0;
8092
0
        }
8093
0
        TxnInfoPB txn_info;
8094
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
8095
0
            return 0;
8096
0
        }
8097
8098
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
8099
0
            TxnRunningPB txn_running_pb;
8100
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
8101
0
                return 0;
8102
0
            }
8103
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
8104
0
                return 0;
8105
0
            }
8106
0
            metrics_context.total_need_recycle_num++;
8107
0
        }
8108
0
        return 0;
8109
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_
8110
8111
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key, std::move(handle_abort_timeout_txn_kv));
8112
0
    metrics_context.report(true);
8113
0
    return ret;
8114
0
}
8115
8116
// Scan and statistics expired_txn_label that need to be recycled
8117
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
8118
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
8119
8120
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
8121
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
8122
0
    std::string begin_recycle_txn_key;
8123
0
    std::string end_recycle_txn_key;
8124
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
8125
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
8126
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8127
0
    int64_t current_time_ms =
8128
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8129
8130
    // for calculate the total num or bytes of recyled objects
8131
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
8132
0
        RecycleTxnPB recycle_txn_pb;
8133
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
8134
0
            return 0;
8135
0
        }
8136
0
        if ((config::force_immediate_recycle) ||
8137
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
8138
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
8139
0
             current_time_ms)) {
8140
0
            metrics_context.total_need_recycle_num++;
8141
0
        }
8142
0
        return 0;
8143
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_
8144
8145
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key, std::move(handle_expired_txn_label_kv));
8146
0
    metrics_context.report(true);
8147
0
    return ret;
8148
0
}
8149
8150
// Scan and statistics copy_jobs that need to be recycled
8151
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
8152
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
8153
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
8154
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
8155
0
    std::string key0;
8156
0
    std::string key1;
8157
0
    copy_job_key(key_info0, &key0);
8158
0
    copy_job_key(key_info1, &key1);
8159
8160
    // for calculate the total num or bytes of recyled objects
8161
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
8162
0
        CopyJobPB copy_job;
8163
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
8164
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
8165
0
            return 0;
8166
0
        }
8167
8168
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
8169
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
8170
0
                int64_t current_time =
8171
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8172
0
                if (copy_job.finish_time_ms() > 0) {
8173
0
                    if (!config::force_immediate_recycle &&
8174
0
                        current_time < copy_job.finish_time_ms() +
8175
0
                                               config::copy_job_max_retention_second * 1000) {
8176
0
                        return 0;
8177
0
                    }
8178
0
                } else {
8179
0
                    if (!config::force_immediate_recycle &&
8180
0
                        current_time < copy_job.start_time_ms() +
8181
0
                                               config::copy_job_max_retention_second * 1000) {
8182
0
                        return 0;
8183
0
                    }
8184
0
                }
8185
0
            }
8186
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
8187
0
            int64_t current_time =
8188
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8189
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
8190
0
                return 0;
8191
0
            }
8192
0
        }
8193
0
        metrics_context.total_need_recycle_num++;
8194
0
        return 0;
8195
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_
8196
8197
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
8198
0
    metrics_context.report(true);
8199
0
    return ret;
8200
0
}
8201
8202
// Scan and statistics stage that need to be recycled
8203
0
int InstanceRecycler::scan_and_statistics_stage() {
8204
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
8205
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
8206
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
8207
0
    std::string key0 = recycle_stage_key(key_info0);
8208
0
    std::string key1 = recycle_stage_key(key_info1);
8209
8210
    // for calculate the total num or bytes of recyled objects
8211
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
8212
0
                                                        std::string_view v) -> int {
8213
0
        RecycleStagePB recycle_stage;
8214
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
8215
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
8216
0
            return 0;
8217
0
        }
8218
8219
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
8220
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
8221
0
            LOG(WARNING) << "invalid idx: " << idx;
8222
0
            return 0;
8223
0
        }
8224
8225
0
        std::shared_ptr<StorageVaultAccessor> accessor;
8226
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
8227
0
                [&] {
8228
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
8229
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8230
0
                    if (!s3_conf) {
8231
0
                        return 0;
8232
0
                    }
8233
8234
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
8235
0
                    std::shared_ptr<S3Accessor> s3_accessor;
8236
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
8237
0
                    if (ret != 0) {
8238
0
                        return 0;
8239
0
                    }
8240
8241
0
                    accessor = std::move(s3_accessor);
8242
0
                    return 0;
8243
0
                }(),
8244
0
                "recycle_stage:get_accessor", &accessor);
8245
8246
0
        if (ret != 0) {
8247
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
8248
0
            return 0;
8249
0
        }
8250
8251
0
        metrics_context.total_need_recycle_num++;
8252
0
        return 0;
8253
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_
8254
8255
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
8256
0
    metrics_context.report(true);
8257
0
    return ret;
8258
0
}
8259
8260
// Scan and statistics expired_stage_objects that need to be recycled
8261
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
8262
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
8263
8264
    // for calculate the total num or bytes of recyled objects
8265
0
    auto scan_and_statistics = [&metrics_context, this]() {
8266
0
        for (const auto& stage : instance_info_.stages()) {
8267
0
            if (stopped()) {
8268
0
                break;
8269
0
            }
8270
0
            if (stage.type() == StagePB::EXTERNAL) {
8271
0
                continue;
8272
0
            }
8273
0
            int idx = stoi(stage.obj_info().id());
8274
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
8275
0
                continue;
8276
0
            }
8277
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
8278
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8279
0
            if (!s3_conf) {
8280
0
                continue;
8281
0
            }
8282
0
            s3_conf->prefix = stage.obj_info().prefix();
8283
0
            std::shared_ptr<S3Accessor> accessor;
8284
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
8285
0
            if (ret1 != 0) {
8286
0
                continue;
8287
0
            }
8288
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
8289
0
                continue;
8290
0
            }
8291
0
            metrics_context.total_need_recycle_num++;
8292
0
        }
8293
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
8294
8295
0
    scan_and_statistics();
8296
0
    metrics_context.report(true);
8297
0
    return 0;
8298
0
}
8299
8300
// Scan and statistics versions that need to be recycled
8301
0
int InstanceRecycler::scan_and_statistics_versions() {
8302
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
8303
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
8304
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
8305
8306
0
    int64_t last_scanned_table_id = 0;
8307
0
    bool is_recycled = false; // Is last scanned kv recycled
8308
    // for calculate the total num or bytes of recyled objects
8309
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
8310
0
                                       std::string_view k, std::string_view) {
8311
0
        auto k1 = k;
8312
0
        k1.remove_prefix(1);
8313
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
8314
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8315
0
        decode_key(&k1, &out);
8316
0
        DCHECK_EQ(out.size(), 6) << k;
8317
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
8318
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
8319
0
            metrics_context.total_need_recycle_num +=
8320
0
                    is_recycled; // Version kv of this table has been recycled
8321
0
            return 0;
8322
0
        }
8323
0
        last_scanned_table_id = table_id;
8324
0
        is_recycled = false;
8325
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
8326
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
8327
0
        std::unique_ptr<Transaction> txn;
8328
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8329
0
        if (err != TxnErrorCode::TXN_OK) {
8330
0
            return 0;
8331
0
        }
8332
0
        std::unique_ptr<RangeGetIterator> iter;
8333
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
8334
0
        if (err != TxnErrorCode::TXN_OK) {
8335
0
            return 0;
8336
0
        }
8337
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
8338
0
            return 0;
8339
0
        }
8340
0
        metrics_context.total_need_recycle_num++;
8341
0
        is_recycled = true;
8342
0
        return 0;
8343
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_
8344
8345
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
8346
0
    metrics_context.report(true);
8347
0
    return ret;
8348
0
}
8349
8350
// Scan and statistics restore jobs that need to be recycled
8351
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
8352
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
8353
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
8354
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
8355
0
    std::string restore_job_key0;
8356
0
    std::string restore_job_key1;
8357
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
8358
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
8359
8360
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8361
8362
    // for calculate the total num or bytes of recyled objects
8363
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
8364
0
        RestoreJobCloudPB restore_job_pb;
8365
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
8366
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
8367
0
            return 0;
8368
0
        }
8369
0
        int64_t expiration =
8370
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
8371
0
        int64_t current_time = ::time(nullptr);
8372
0
        if (current_time < expiration) { // not expired
8373
0
            return 0;
8374
0
        }
8375
0
        metrics_context.total_need_recycle_num++;
8376
0
        if(restore_job_pb.need_recycle_data()) {
8377
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
8378
0
        }
8379
0
        return 0;
8380
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_
8381
8382
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
8383
0
    metrics_context.report(true);
8384
0
    return ret;
8385
0
}
8386
8387
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
8388
3
    if (!should_recycle_versioned_keys()) {
8389
0
        return;
8390
0
    }
8391
8392
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
8393
8394
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
8395
3
    if (recycle_checker.init() != 0) {
8396
0
        return;
8397
0
    }
8398
8399
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
8400
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
8401
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
8402
8403
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
8404
8
    for (; iter->valid(); iter->next()) {
8405
5
        OperationLogPB operation_log;
8406
5
        if (!iter->parse_value(&operation_log)) {
8407
0
            continue;
8408
0
        }
8409
8410
5
        std::string_view key = iter->key();
8411
5
        Versionstamp log_versionstamp;
8412
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
8413
0
            continue;
8414
0
        }
8415
8416
5
        OperationLogReferenceInfo ref_info;
8417
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
8418
5
                                         &ref_info)) {
8419
4
            metrics_context.total_need_recycle_num++;
8420
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
8421
4
        }
8422
5
    }
8423
8424
3
    metrics_context.report(true);
8425
3
}
8426
8427
int InstanceRecycler::classify_rowset_task_by_ref_count(
8428
60
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
8429
60
    constexpr int MAX_RETRY = 10;
8430
60
    const auto& rowset_meta = task.rowset_meta;
8431
60
    int64_t tablet_id = rowset_meta.tablet_id();
8432
60
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
8433
60
    std::string_view reference_instance_id = instance_id_;
8434
60
    if (rowset_meta.has_reference_instance_id()) {
8435
5
        reference_instance_id = rowset_meta.reference_instance_id();
8436
5
    }
8437
8438
61
    for (int i = 0; i < MAX_RETRY; ++i) {
8439
61
        std::unique_ptr<Transaction> txn;
8440
61
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8441
61
        if (err != TxnErrorCode::TXN_OK) {
8442
0
            LOG_WARNING("failed to create txn when classifying rowset task")
8443
0
                    .tag("instance_id", instance_id_)
8444
0
                    .tag("tablet_id", tablet_id)
8445
0
                    .tag("rowset_id", rowset_id)
8446
0
                    .tag("err", err);
8447
0
            return -1;
8448
0
        }
8449
8450
61
        std::string rowset_ref_count_key =
8451
61
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
8452
61
        task.rowset_ref_count_key = rowset_ref_count_key;
8453
8454
61
        int64_t ref_count = 0;
8455
61
        {
8456
61
            std::string value;
8457
61
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
8458
61
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
8459
0
                ref_count = 1;
8460
61
            } else if (err != TxnErrorCode::TXN_OK) {
8461
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
8462
0
                        .tag("instance_id", instance_id_)
8463
0
                        .tag("tablet_id", tablet_id)
8464
0
                        .tag("rowset_id", rowset_id)
8465
0
                        .tag("err", err);
8466
0
                return -1;
8467
61
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
8468
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
8469
0
                        .tag("instance_id", instance_id_)
8470
0
                        .tag("tablet_id", tablet_id)
8471
0
                        .tag("rowset_id", rowset_id)
8472
0
                        .tag("value", hex(value));
8473
0
                return -1;
8474
0
            }
8475
61
        }
8476
8477
61
        if (ref_count > 1) {
8478
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
8479
12
            txn->atomic_add(rowset_ref_count_key, -1);
8480
12
            LOG_INFO("decrease rowset data ref count in classification phase")
8481
12
                    .tag("instance_id", instance_id_)
8482
12
                    .tag("tablet_id", tablet_id)
8483
12
                    .tag("rowset_id", rowset_id)
8484
12
                    .tag("ref_count", ref_count - 1)
8485
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
8486
8487
12
            if (!task.recycle_rowset_key.empty()) {
8488
0
                txn->remove(task.recycle_rowset_key);
8489
0
                LOG_INFO("remove recycle rowset key in classification phase")
8490
0
                        .tag("key", hex(task.recycle_rowset_key));
8491
0
            }
8492
12
            if (!task.non_versioned_rowset_key.empty()) {
8493
12
                txn->remove(task.non_versioned_rowset_key);
8494
12
                LOG_INFO("remove non versioned rowset key in classification phase")
8495
12
                        .tag("key", hex(task.non_versioned_rowset_key));
8496
12
            }
8497
8498
12
            err = txn->commit();
8499
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
8500
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
8501
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
8502
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
8503
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
8504
1
                continue;
8505
11
            } else if (err != TxnErrorCode::TXN_OK) {
8506
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
8507
0
                        .tag("instance_id", instance_id_)
8508
0
                        .tag("tablet_id", tablet_id)
8509
0
                        .tag("rowset_id", rowset_id)
8510
0
                        .tag("err", err);
8511
0
                return -1;
8512
0
            }
8513
11
            return 1; // handled, not added to batch delete
8514
49
        } else {
8515
            // ref_count == 1: Add to batch delete plan without modifying any KV.
8516
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
8517
49
            LOG_INFO("add rowset to batch delete plan")
8518
49
                    .tag("instance_id", instance_id_)
8519
49
                    .tag("tablet_id", tablet_id)
8520
49
                    .tag("rowset_id", rowset_id)
8521
49
                    .tag("resource_id", rowset_meta.resource_id())
8522
49
                    .tag("ref_count", ref_count);
8523
8524
49
            batch_delete_tasks.push_back(std::move(task));
8525
49
            return 0; // added to batch delete
8526
49
        }
8527
61
    }
8528
8529
0
    LOG_WARNING("failed to classify rowset task after retry")
8530
0
            .tag("instance_id", instance_id_)
8531
0
            .tag("tablet_id", tablet_id)
8532
0
            .tag("rowset_id", rowset_id)
8533
0
            .tag("retry", MAX_RETRY);
8534
0
    return -1;
8535
60
}
8536
8537
10
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
8538
10
    int ret = 0;
8539
49
    for (const auto& task : tasks) {
8540
49
        int64_t tablet_id = task.rowset_meta.tablet_id();
8541
49
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
8542
8543
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
8544
        // so we don't need to call it again here.
8545
8546
        // Remove all metadata keys in one transaction
8547
49
        std::unique_ptr<Transaction> txn;
8548
49
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8549
49
        if (err != TxnErrorCode::TXN_OK) {
8550
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
8551
0
                    .tag("instance_id", instance_id_)
8552
0
                    .tag("tablet_id", tablet_id)
8553
0
                    .tag("rowset_id", rowset_id)
8554
0
                    .tag("err", err);
8555
0
            ret = -1;
8556
0
            continue;
8557
0
        }
8558
8559
49
        std::string_view reference_instance_id = instance_id_;
8560
49
        if (task.rowset_meta.has_reference_instance_id()) {
8561
0
            reference_instance_id = task.rowset_meta.reference_instance_id();
8562
0
        }
8563
8564
49
        txn->remove(task.rowset_ref_count_key);
8565
49
        LOG_INFO("delete rowset data ref count key in cleanup phase")
8566
49
                .tag("instance_id", instance_id_)
8567
49
                .tag("tablet_id", tablet_id)
8568
49
                .tag("rowset_id", rowset_id)
8569
49
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
8570
8571
49
        std::string dbm_start_key =
8572
49
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
8573
49
        std::string dbm_end_key = meta_delete_bitmap_key(
8574
49
                {reference_instance_id, tablet_id, rowset_id,
8575
49
                 std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
8576
49
        txn->remove(dbm_start_key, dbm_end_key);
8577
49
        LOG_INFO("remove delete bitmap kv in cleanup phase")
8578
49
                .tag("instance_id", instance_id_)
8579
49
                .tag("tablet_id", tablet_id)
8580
49
                .tag("rowset_id", rowset_id)
8581
49
                .tag("begin", hex(dbm_start_key))
8582
49
                .tag("end", hex(dbm_end_key));
8583
8584
49
        std::string versioned_dbm_start_key =
8585
49
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
8586
49
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
8587
49
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
8588
49
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
8589
49
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
8590
49
                .tag("instance_id", instance_id_)
8591
49
                .tag("tablet_id", tablet_id)
8592
49
                .tag("rowset_id", rowset_id)
8593
49
                .tag("begin", hex(versioned_dbm_start_key))
8594
49
                .tag("end", hex(versioned_dbm_end_key));
8595
8596
        // Remove versioned meta rowset key
8597
49
        if (!task.versioned_rowset_key.empty()) {
8598
49
            versioned::document_remove<RowsetMetaCloudPB>(
8599
49
                txn.get(), task.versioned_rowset_key, task.versionstamp);
8600
49
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
8601
49
                    .tag("instance_id", instance_id_)
8602
49
                    .tag("tablet_id", tablet_id)
8603
49
                    .tag("rowset_id", rowset_id)
8604
49
                    .tag("key_prefix", hex(task.versioned_rowset_key));
8605
49
        }
8606
8607
49
        if (!task.non_versioned_rowset_key.empty()) {
8608
49
            txn->remove(task.non_versioned_rowset_key);
8609
49
            LOG_INFO("remove non versioned rowset key in cleanup phase")
8610
49
                    .tag("instance_id", instance_id_)
8611
49
                    .tag("tablet_id", tablet_id)
8612
49
                    .tag("rowset_id", rowset_id)
8613
49
                    .tag("key", hex(task.non_versioned_rowset_key));
8614
49
        }
8615
8616
        // Remove recycle_rowset_key last to ensure retry safety:
8617
        // if cleanup fails, this key remains and triggers next round retry.
8618
49
        if (!task.recycle_rowset_key.empty()) {
8619
0
            txn->remove(task.recycle_rowset_key);
8620
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
8621
0
                    .tag("instance_id", instance_id_)
8622
0
                    .tag("tablet_id", tablet_id)
8623
0
                    .tag("rowset_id", rowset_id)
8624
0
                    .tag("key", hex(task.recycle_rowset_key));
8625
0
        }
8626
8627
49
        err = txn->commit();
8628
49
        if (err != TxnErrorCode::TXN_OK) {
8629
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
8630
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
8631
0
                    .tag("instance_id", instance_id_)
8632
0
                    .tag("tablet_id", tablet_id)
8633
0
                    .tag("rowset_id", rowset_id)
8634
0
                    .tag("err", err);
8635
0
            ret = -1;
8636
0
            continue;
8637
0
        }
8638
8639
49
        LOG_INFO("cleanup rowset metadata success")
8640
49
                .tag("instance_id", instance_id_)
8641
49
                .tag("tablet_id", tablet_id)
8642
49
                .tag("rowset_id", rowset_id);
8643
49
    }
8644
10
    return ret;
8645
10
}
8646
8647
} // namespace doris::cloud