Coverage Report

Created: 2026-08-21 15:00

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/simple_thread_pool.h"
73
#include "common/util.h"
74
#include "cpp/sync_point.h"
75
#include "meta-store/codec.h"
76
#include "meta-store/document_message.h"
77
#include "meta-store/keys.h"
78
#include "recycler/recycler_service.h"
79
#include "recycler/sync_executor.h"
80
#include "recycler/util.h"
81
#include "snapshot/snapshot_manager_factory.h"
82
83
namespace doris::cloud {
84
85
using namespace std::chrono;
86
87
namespace {
88
89
constexpr size_t kRowsetBatchGetSize = 256;
90
91
0
int64_t packed_file_retry_sleep_ms() {
92
0
    const int64_t min_ms = std::max<int64_t>(0, config::packed_file_txn_retry_sleep_min_ms);
93
0
    const int64_t max_ms = std::max<int64_t>(min_ms, config::packed_file_txn_retry_sleep_max_ms);
94
0
    thread_local std::mt19937_64 gen(std::random_device {}());
95
0
    std::uniform_int_distribution<int64_t> dist(min_ms, max_ms);
96
0
    return dist(gen);
97
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
98
99
0
void sleep_for_packed_file_retry() {
100
0
    std::this_thread::sleep_for(std::chrono::milliseconds(packed_file_retry_sleep_ms()));
101
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
102
103
869k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
104
869k
    const auto& locations = rowset.packed_slice_locations();
105
869k
    auto it = locations.find(path);
106
869k
    return it != locations.end() && it->second.has_packed_file_path() &&
107
869k
           !it->second.packed_file_path().empty();
108
869k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
103
7
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
104
7
    const auto& locations = rowset.packed_slice_locations();
105
7
    auto it = locations.find(path);
106
7
    return it != locations.end() && it->second.has_packed_file_path() &&
107
7
           !it->second.packed_file_path().empty();
108
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
103
869k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
104
869k
    const auto& locations = rowset.packed_slice_locations();
105
869k
    auto it = locations.find(path);
106
869k
    return it != locations.end() && it->second.has_packed_file_path() &&
107
869k
           !it->second.packed_file_path().empty();
108
869k
}
109
110
void add_file_to_delete_if_not_packed(const doris::RowsetMetaCloudPB& rowset,
111
                                      const std::string& path,
112
869k
                                      std::vector<std::string>* file_paths) {
113
870k
    if (!is_packed_slice_path(rowset, path)) {
114
870k
        file_paths->push_back(path);
115
870k
    }
116
869k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
112
7
                                      std::vector<std::string>* file_paths) {
113
7
    if (!is_packed_slice_path(rowset, path)) {
114
7
        file_paths->push_back(path);
115
7
    }
116
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
112
869k
                                      std::vector<std::string>* file_paths) {
113
870k
    if (!is_packed_slice_path(rowset, path)) {
114
870k
        file_paths->push_back(path);
115
870k
    }
116
869k
}
117
118
37
bool filter_out_instance(const std::string& instance_id) {
119
37
    if (config::recycle_whitelist.empty()) {
120
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
121
35
               config::recycle_blacklist.end();
122
35
    }
123
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
124
2
           config::recycle_whitelist.end();
125
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
118
37
bool filter_out_instance(const std::string& instance_id) {
119
37
    if (config::recycle_whitelist.empty()) {
120
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
121
35
               config::recycle_blacklist.end();
122
35
    }
123
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
124
2
           config::recycle_whitelist.end();
125
37
}
126
127
} // namespace
128
129
// return 0 for success get a key, 1 for key not found, negative for error
130
0
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
131
0
    std::unique_ptr<Transaction> txn;
132
0
    TxnErrorCode err = txn_kv->create_txn(&txn);
133
0
    if (err != TxnErrorCode::TXN_OK) {
134
0
        return -1;
135
0
    }
136
0
    switch (txn->get(key, &val, true)) {
137
0
    case TxnErrorCode::TXN_OK:
138
0
        return 0;
139
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
140
0
        return 1;
141
0
    default:
142
0
        return -1;
143
0
    };
144
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
145
146
// 0 for success, negative for error
147
static int txn_get(TxnKv* txn_kv, std::string_view begin, std::string_view end,
148
396
                   std::unique_ptr<RangeGetIterator>& it) {
149
396
    std::unique_ptr<Transaction> txn;
150
396
    TxnErrorCode err = txn_kv->create_txn(&txn);
151
396
    if (err != TxnErrorCode::TXN_OK) {
152
0
        return -1;
153
0
    }
154
396
    switch (txn->get(begin, end, &it, true)) {
155
396
    case TxnErrorCode::TXN_OK:
156
396
        return 0;
157
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
158
0
        return 1;
159
0
    default:
160
0
        return -1;
161
396
    };
162
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
148
36
                   std::unique_ptr<RangeGetIterator>& it) {
149
36
    std::unique_ptr<Transaction> txn;
150
36
    TxnErrorCode err = txn_kv->create_txn(&txn);
151
36
    if (err != TxnErrorCode::TXN_OK) {
152
0
        return -1;
153
0
    }
154
36
    switch (txn->get(begin, end, &it, true)) {
155
36
    case TxnErrorCode::TXN_OK:
156
36
        return 0;
157
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
158
0
        return 1;
159
0
    default:
160
0
        return -1;
161
36
    };
162
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
148
360
                   std::unique_ptr<RangeGetIterator>& it) {
149
360
    std::unique_ptr<Transaction> txn;
150
360
    TxnErrorCode err = txn_kv->create_txn(&txn);
151
360
    if (err != TxnErrorCode::TXN_OK) {
152
0
        return -1;
153
0
    }
154
360
    switch (txn->get(begin, end, &it, true)) {
155
360
    case TxnErrorCode::TXN_OK:
156
360
        return 0;
157
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
158
0
        return 1;
159
0
    default:
160
0
        return -1;
161
360
    };
162
0
}
163
164
// return 0 for success otherwise error
165
10
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
166
10
    std::unique_ptr<Transaction> txn;
167
10
    TxnErrorCode err = txn_kv->create_txn(&txn);
168
10
    if (err != TxnErrorCode::TXN_OK) {
169
0
        return -1;
170
0
    }
171
18
    for (auto k : keys) {
172
18
        txn->remove(k);
173
18
    }
174
10
    switch (txn->commit()) {
175
10
    case TxnErrorCode::TXN_OK:
176
10
        return 0;
177
0
    case TxnErrorCode::TXN_CONFLICT:
178
0
        return -1;
179
0
    default:
180
0
        return -1;
181
10
    }
182
10
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
165
3
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
166
3
    std::unique_ptr<Transaction> txn;
167
3
    TxnErrorCode err = txn_kv->create_txn(&txn);
168
3
    if (err != TxnErrorCode::TXN_OK) {
169
0
        return -1;
170
0
    }
171
3
    for (auto k : keys) {
172
3
        txn->remove(k);
173
3
    }
174
3
    switch (txn->commit()) {
175
3
    case TxnErrorCode::TXN_OK:
176
3
        return 0;
177
0
    case TxnErrorCode::TXN_CONFLICT:
178
0
        return -1;
179
0
    default:
180
0
        return -1;
181
3
    }
182
3
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
165
7
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
166
7
    std::unique_ptr<Transaction> txn;
167
7
    TxnErrorCode err = txn_kv->create_txn(&txn);
168
7
    if (err != TxnErrorCode::TXN_OK) {
169
0
        return -1;
170
0
    }
171
15
    for (auto k : keys) {
172
15
        txn->remove(k);
173
15
    }
174
7
    switch (txn->commit()) {
175
7
    case TxnErrorCode::TXN_OK:
176
7
        return 0;
177
0
    case TxnErrorCode::TXN_CONFLICT:
178
0
        return -1;
179
0
    default:
180
0
        return -1;
181
7
    }
182
7
}
183
184
// return 0 for success otherwise error
185
360
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
186
360
    std::unique_ptr<Transaction> txn;
187
360
    TxnErrorCode err = txn_kv->create_txn(&txn);
188
360
    if (err != TxnErrorCode::TXN_OK) {
189
0
        return -1;
190
0
    }
191
106k
    for (auto& k : keys) {
192
106k
        txn->remove(k);
193
106k
    }
194
360
    switch (txn->commit()) {
195
360
    case TxnErrorCode::TXN_OK:
196
360
        return 0;
197
0
    case TxnErrorCode::TXN_CONFLICT:
198
0
        return -1;
199
0
    default:
200
0
        return -1;
201
360
    }
202
360
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
185
33
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
186
33
    std::unique_ptr<Transaction> txn;
187
33
    TxnErrorCode err = txn_kv->create_txn(&txn);
188
33
    if (err != TxnErrorCode::TXN_OK) {
189
0
        return -1;
190
0
    }
191
33
    for (auto& k : keys) {
192
17
        txn->remove(k);
193
17
    }
194
33
    switch (txn->commit()) {
195
33
    case TxnErrorCode::TXN_OK:
196
33
        return 0;
197
0
    case TxnErrorCode::TXN_CONFLICT:
198
0
        return -1;
199
0
    default:
200
0
        return -1;
201
33
    }
202
33
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
185
327
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
186
327
    std::unique_ptr<Transaction> txn;
187
327
    TxnErrorCode err = txn_kv->create_txn(&txn);
188
327
    if (err != TxnErrorCode::TXN_OK) {
189
0
        return -1;
190
0
    }
191
106k
    for (auto& k : keys) {
192
106k
        txn->remove(k);
193
106k
    }
194
327
    switch (txn->commit()) {
195
327
    case TxnErrorCode::TXN_OK:
196
327
        return 0;
197
0
    case TxnErrorCode::TXN_CONFLICT:
198
0
        return -1;
199
0
    default:
200
0
        return -1;
201
327
    }
202
327
}
203
204
// return 0 for success otherwise error
205
[[maybe_unused]] static int txn_remove(TxnKv* txn_kv, std::string_view begin,
206
106k
                                       std::string_view end) {
207
106k
    std::unique_ptr<Transaction> txn;
208
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
209
106k
    if (err != TxnErrorCode::TXN_OK) {
210
0
        return -1;
211
0
    }
212
106k
    txn->remove(begin, end);
213
106k
    switch (txn->commit()) {
214
106k
    case TxnErrorCode::TXN_OK:
215
106k
        return 0;
216
0
    case TxnErrorCode::TXN_CONFLICT:
217
0
        return -1;
218
0
    default:
219
0
        return -1;
220
106k
    }
221
106k
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
206
17
                                       std::string_view end) {
207
17
    std::unique_ptr<Transaction> txn;
208
17
    TxnErrorCode err = txn_kv->create_txn(&txn);
209
17
    if (err != TxnErrorCode::TXN_OK) {
210
0
        return -1;
211
0
    }
212
17
    txn->remove(begin, end);
213
17
    switch (txn->commit()) {
214
17
    case TxnErrorCode::TXN_OK:
215
17
        return 0;
216
0
    case TxnErrorCode::TXN_CONFLICT:
217
0
        return -1;
218
0
    default:
219
0
        return -1;
220
17
    }
221
17
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
206
106k
                                       std::string_view end) {
207
106k
    std::unique_ptr<Transaction> txn;
208
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
209
106k
    if (err != TxnErrorCode::TXN_OK) {
210
0
        return -1;
211
0
    }
212
106k
    txn->remove(begin, end);
213
106k
    switch (txn->commit()) {
214
106k
    case TxnErrorCode::TXN_OK:
215
106k
        return 0;
216
0
    case TxnErrorCode::TXN_CONFLICT:
217
0
        return -1;
218
0
    default:
219
0
        return -1;
220
106k
    }
221
106k
}
222
223
void scan_restore_job_rowset(
224
        Transaction* txn, const std::string& instance_id, int64_t tablet_id, MetaServiceCode& code,
225
        std::string& msg,
226
        std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>* restore_job_rs_metas);
227
228
static inline void check_recycle_task(const std::string& instance_id, const std::string& task_name,
229
                                      int64_t num_scanned, int64_t num_recycled,
230
55
                                      int64_t start_time) {
231
55
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
232
0
        int64_t cost =
233
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
234
0
        if (cost > config::recycle_task_threshold_seconds) {
235
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
236
0
                    .tag("instance_id", instance_id)
237
0
                    .tag("task", task_name)
238
0
                    .tag("num_scanned", num_scanned)
239
0
                    .tag("num_recycled", num_recycled);
240
0
        }
241
0
    }
242
55
    return;
243
55
}
recycler.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
230
4
                                      int64_t start_time) {
231
4
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
232
0
        int64_t cost =
233
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
234
0
        if (cost > config::recycle_task_threshold_seconds) {
235
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
236
0
                    .tag("instance_id", instance_id)
237
0
                    .tag("task", task_name)
238
0
                    .tag("num_scanned", num_scanned)
239
0
                    .tag("num_recycled", num_recycled);
240
0
        }
241
0
    }
242
4
    return;
243
4
}
recycler_test.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
230
51
                                      int64_t start_time) {
231
51
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
232
0
        int64_t cost =
233
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
234
0
        if (cost > config::recycle_task_threshold_seconds) {
235
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
236
0
                    .tag("instance_id", instance_id)
237
0
                    .tag("task", task_name)
238
0
                    .tag("num_scanned", num_scanned)
239
0
                    .tag("num_recycled", num_recycled);
240
0
        }
241
0
    }
242
51
    return;
243
51
}
244
245
6
Recycler::Recycler(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
246
6
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
247
248
6
    auto s3_producer_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
249
6
                                                               "s3_producer_pool");
250
6
    s3_producer_pool->start();
251
6
    auto recycle_tablet_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
252
6
                                                                  "recycle_tablet_pool");
253
6
    recycle_tablet_pool->start();
254
6
    auto group_recycle_function_pool = std::make_shared<SimpleThreadPool>(
255
6
            config::recycle_pool_parallelism, "group_recycle_function_pool");
256
6
    group_recycle_function_pool->start();
257
6
    _thread_pool_group =
258
6
            RecyclerThreadPoolGroup(std::move(s3_producer_pool), std::move(recycle_tablet_pool),
259
6
                                    std::move(group_recycle_function_pool));
260
261
6
    auto resource_mgr = std::make_shared<ResourceManager>(txn_kv_);
262
6
    txn_lazy_committer_ = std::make_shared<TxnLazyCommitter>(txn_kv_, std::move(resource_mgr));
263
6
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
264
6
}
265
266
6
Recycler::~Recycler() {
267
6
    if (!stopped()) {
268
0
        stop();
269
0
    }
270
6
}
271
272
5
void Recycler::instance_scanner_callback() {
273
    // sleep 60 seconds before scheduling for the launch procedure to complete:
274
    // some bad hdfs connection may cause some log to stdout stderr
275
    // which may pollute .out file and affect the script to check success
276
5
    std::this_thread::sleep_for(
277
5
            std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
278
1.37k
    while (!stopped()) {
279
1.36k
        if (config::enable_recycler) {
280
4
            std::vector<InstanceInfoPB> instances;
281
4
            get_all_instances(txn_kv_.get(), instances);
282
            // TODO(plat1ko): delete job recycle kv of non-existent instances
283
4
            LOG(INFO) << "Recycler get instances: " << [&instances] {
284
4
                std::stringstream ss;
285
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
286
4
                return ss.str();
287
4
            }();
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
Line
Count
Source
283
4
            LOG(INFO) << "Recycler get instances: " << [&instances] {
284
4
                std::stringstream ss;
285
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
286
4
                return ss.str();
287
4
            }();
288
4
            if (!instances.empty()) {
289
                // enqueue instances
290
3
                std::lock_guard lock(mtx_);
291
30
                for (auto& instance : instances) {
292
30
                    if (filter_out_instance(instance.instance_id())) continue;
293
30
                    auto [_, success] = pending_instance_set_.insert(instance.instance_id());
294
                    // skip instance already in pending queue
295
30
                    if (success) {
296
30
                        pending_instance_queue_.push_back(std::move(instance));
297
30
                    }
298
30
                }
299
3
                pending_instance_cond_.notify_all();
300
3
            }
301
1.36k
        } else {
302
1.36k
            LOG(WARNING) << "Skip recycler since enable_recycler is false";
303
1.36k
        }
304
1.36k
        {
305
1.36k
            std::unique_lock lock(mtx_);
306
1.36k
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
307
2.73k
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
307
2.73k
                               [&]() { return stopped(); });
308
1.36k
        }
309
1.36k
    }
310
5
}
311
312
9
void Recycler::recycle_callback() {
313
40
    while (!stopped()) {
314
39
        InstanceInfoPB instance;
315
39
        {
316
39
            std::unique_lock lock(mtx_);
317
39
            pending_instance_cond_.wait(
318
52
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
318
52
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
319
39
            if (stopped()) {
320
8
                return;
321
8
            }
322
31
            instance = std::move(pending_instance_queue_.front());
323
31
            pending_instance_queue_.pop_front();
324
31
            pending_instance_set_.erase(instance.instance_id());
325
31
        }
326
0
        auto& instance_id = instance.instance_id();
327
31
        {
328
31
            std::lock_guard lock(mtx_);
329
            // skip instance in recycling
330
31
            if (recycling_instance_map_.count(instance_id)) continue;
331
31
        }
332
31
        if (!config::enable_recycler) {
333
1
            LOG(WARNING) << "Skip recycle instance_id=" << instance_id
334
1
                         << " since enable_recycler is false";
335
1
            continue;
336
1
        }
337
30
        auto instance_recycler = std::make_shared<InstanceRecycler>(
338
30
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
339
340
30
        if (int r = instance_recycler->init(); r != 0) {
341
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
342
0
                         << " ret=" << r;
343
0
            continue;
344
0
        }
345
30
        std::string recycle_job_key;
346
30
        job_recycle_key({instance_id}, &recycle_job_key);
347
30
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
348
30
                                               ip_port_, config::recycle_interval_seconds * 1000);
349
30
        if (ret != 0) { // Prepare failed
350
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
351
20
                         << " ret=" << ret;
352
20
            continue;
353
20
        } else {
354
10
            std::lock_guard lock(mtx_);
355
10
            recycling_instance_map_.emplace(instance_id, instance_recycler);
356
10
        }
357
10
        if (stopped()) return;
358
10
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
359
10
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
360
10
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
361
10
        g_bvar_recycler_instance_recycle_task_status.put({"submitted"}, 1);
362
10
        ret = instance_recycler->do_recycle();
363
        // If instance recycler has been aborted, don't finish this job
364
365
10
        if (!instance_recycler->stopped()) {
366
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
367
10
                                        ret == 0, ctime_ms);
368
10
        }
369
10
        if (instance_recycler->stopped() || ret != 0) {
370
0
            g_bvar_recycler_instance_recycle_task_status.put({"error"}, 1);
371
0
        }
372
10
        {
373
10
            std::lock_guard lock(mtx_);
374
10
            recycling_instance_map_.erase(instance_id);
375
10
        }
376
377
10
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
378
10
        auto elpased_ms = now - ctime_ms;
379
10
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
380
10
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
381
10
        g_bvar_recycler_instance_next_ts.put({instance_id},
382
10
                                             now + config::recycle_interval_seconds * 1000);
383
10
        g_bvar_recycler_instance_recycle_task_status.put({"completed"}, 1);
384
10
        LOG(INFO) << "recycle instance done, "
385
10
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
386
10
                  << " now: " << now;
387
388
10
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
389
390
10
        LOG_WARNING("finish recycle instance")
391
10
                .tag("instance_id", instance_id)
392
10
                .tag("cost_ms", elpased_ms);
393
10
    }
394
9
}
395
396
4
void Recycler::lease_recycle_jobs() {
397
54
    while (!stopped()) {
398
50
        std::vector<std::string> instances;
399
50
        instances.reserve(recycling_instance_map_.size());
400
50
        {
401
50
            std::lock_guard lock(mtx_);
402
50
            for (auto& [id, _] : recycling_instance_map_) {
403
30
                instances.push_back(id);
404
30
            }
405
50
        }
406
50
        for (auto& i : instances) {
407
30
            std::string recycle_job_key;
408
30
            job_recycle_key({i}, &recycle_job_key);
409
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
410
30
            if (ret == 1) {
411
0
                std::lock_guard lock(mtx_);
412
0
                if (auto it = recycling_instance_map_.find(i);
413
0
                    it != recycling_instance_map_.end()) {
414
0
                    it->second->stop();
415
0
                }
416
0
            }
417
30
        }
418
50
        {
419
50
            std::unique_lock lock(mtx_);
420
50
            notifier_.wait_for(lock,
421
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
422
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
422
100
                               [&]() { return stopped(); });
423
50
        }
424
50
    }
425
4
}
426
427
4
void Recycler::check_recycle_tasks() {
428
7
    while (!stopped()) {
429
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
430
3
        {
431
3
            std::lock_guard lock(mtx_);
432
3
            recycling_instance_map = recycling_instance_map_;
433
3
        }
434
3
        for (auto& entry : recycling_instance_map) {
435
0
            entry.second->check_recycle_tasks();
436
0
        }
437
438
3
        std::unique_lock lock(mtx_);
439
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
440
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
440
6
                           [&]() { return stopped(); });
441
3
    }
442
4
}
443
444
4
int Recycler::start(brpc::Server* server) {
445
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
446
4
    S3Environment::getInstance();
447
448
4
    if (config::enable_checker) {
449
0
        checker_ = std::make_unique<Checker>(txn_kv_);
450
0
        int ret = checker_->start();
451
0
        std::string msg;
452
0
        if (ret != 0) {
453
0
            msg = "failed to start checker";
454
0
            LOG(ERROR) << msg;
455
0
            std::cerr << msg << std::endl;
456
0
            return ret;
457
0
        }
458
0
        msg = "checker started";
459
0
        LOG(INFO) << msg;
460
0
        std::cout << msg << std::endl;
461
0
    }
462
463
4
    if (server) {
464
        // Add service
465
1
        auto recycler_service =
466
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
467
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
468
1
    }
469
470
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
470
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
471
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
472
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
472
8
        workers_.emplace_back([this] { recycle_callback(); });
473
8
    }
474
475
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
476
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
477
478
4
    if (config::enable_snapshot_data_migrator) {
479
0
        snapshot_data_migrator_ = std::make_shared<SnapshotDataMigrator>(txn_kv_);
480
0
        int ret = snapshot_data_migrator_->start();
481
0
        if (ret != 0) {
482
0
            LOG(ERROR) << "failed to start snapshot data migrator";
483
0
            return ret;
484
0
        }
485
0
        LOG(INFO) << "snapshot data migrator started";
486
0
    }
487
488
4
    if (config::enable_snapshot_chain_compactor) {
489
0
        snapshot_chain_compactor_ = std::make_shared<SnapshotChainCompactor>(txn_kv_);
490
0
        int ret = snapshot_chain_compactor_->start();
491
0
        if (ret != 0) {
492
0
            LOG(ERROR) << "failed to start snapshot chain compactor";
493
0
            return ret;
494
0
        }
495
0
        LOG(INFO) << "snapshot chain compactor started";
496
0
    }
497
498
4
    return 0;
499
4
}
500
501
4
void Recycler::stop() {
502
4
    stopped_ = true;
503
4
    notifier_.notify_all();
504
4
    pending_instance_cond_.notify_all();
505
4
    {
506
4
        std::lock_guard lock(mtx_);
507
4
        for (auto& [_, recycler] : recycling_instance_map_) {
508
0
            recycler->stop();
509
0
        }
510
4
    }
511
20
    for (auto& w : workers_) {
512
20
        if (w.joinable()) w.join();
513
20
    }
514
4
    if (checker_) {
515
0
        checker_->stop();
516
0
    }
517
4
    if (snapshot_data_migrator_) {
518
0
        snapshot_data_migrator_->stop();
519
0
    }
520
4
    if (snapshot_chain_compactor_) {
521
0
        snapshot_chain_compactor_->stop();
522
0
    }
523
4
}
524
525
class InstanceRecycler::InvertedIndexIdCache {
526
public:
527
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
528
174
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
529
530
    // Return 0 if success, 1 if schema kv not found, negative for error
531
    // For the same index_id, schema_version, res, since `get` is not completely atomic
532
    // one thread has not finished inserting, and another thread has not get the index_id and schema_version,
533
    // resulting in repeated addition and inaccuracy.
534
    // however, this approach can reduce the lock range and sacrifice a bit of meta repeated get to improve concurrency performance.
535
    // repeated addition does not affect correctness.
536
28.4k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
537
28.4k
        {
538
28.4k
            std::lock_guard lock(mtx_);
539
28.4k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
540
4.70k
                return 0;
541
4.70k
            }
542
23.7k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
543
23.7k
                it != inverted_index_id_map_.end()) {
544
18.1k
                res = it->second;
545
18.1k
                return 0;
546
18.1k
            }
547
23.7k
        }
548
        // Get schema from kv
549
        // TODO(plat1ko): Single flight
550
5.54k
        std::unique_ptr<Transaction> txn;
551
5.54k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
552
5.54k
        if (err != TxnErrorCode::TXN_OK) {
553
0
            LOG(WARNING) << "failed to create txn, err=" << err;
554
0
            return -1;
555
0
        }
556
5.54k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
557
5.54k
        ValueBuf val_buf;
558
5.54k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
559
5.54k
        if (err != TxnErrorCode::TXN_OK) {
560
500
            LOG(WARNING) << "failed to get schema, err=" << err;
561
500
            return static_cast<int>(err);
562
500
        }
563
5.04k
        doris::TabletSchemaCloudPB schema;
564
5.04k
        if (!parse_schema_value(val_buf, &schema)) {
565
0
            LOG(WARNING) << "malformed schema value, key=" << hex(schema_key);
566
0
            return -1;
567
0
        }
568
5.04k
        if (schema.index_size() > 0) {
569
4.01k
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
570
4.01k
            if (schema.has_inverted_index_storage_format()) {
571
4.00k
                index_format = schema.inverted_index_storage_format();
572
4.00k
            }
573
4.01k
            res.first = index_format;
574
4.01k
            res.second.reserve(schema.index_size());
575
10.0k
            for (auto& i : schema.index()) {
576
10.0k
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
577
10.0k
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
578
10.0k
                }
579
10.0k
            }
580
4.01k
        }
581
5.04k
        insert(index_id, schema_version, res);
582
5.04k
        return 0;
583
5.04k
    }
584
585
    // Empty `ids` means this schema has no inverted index
586
5.04k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
587
5.04k
        if (index_info.second.empty()) {
588
1.03k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
589
1.03k
            std::lock_guard lock(mtx_);
590
1.03k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
591
4.01k
        } else {
592
4.01k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
593
4.01k
            std::lock_guard lock(mtx_);
594
4.01k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
595
4.01k
        }
596
5.04k
    }
597
598
private:
599
    std::string instance_id_;
600
    std::shared_ptr<TxnKv> txn_kv_;
601
602
    std::mutex mtx_;
603
    using Key = std::pair<int64_t, int32_t>; // <index_id, schema_version>
604
    struct HashOfKey {
605
57.2k
        size_t operator()(const Key& key) const {
606
57.2k
            size_t seed = 0;
607
57.2k
            seed = std::hash<int64_t> {}(key.first);
608
57.2k
            seed = std::hash<int32_t> {}(key.second);
609
57.2k
            return seed;
610
57.2k
        }
611
    };
612
    // <index_id, schema_version> -> inverted_index_ids
613
    std::unordered_map<Key, InvertedIndexInfo, HashOfKey> inverted_index_id_map_;
614
    // Store <index_id, schema_version> of schema which doesn't have inverted index
615
    std::unordered_set<Key, HashOfKey> schemas_without_inverted_index_;
616
};
617
618
InstanceRecycler::InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
619
                                   RecyclerThreadPoolGroup thread_pool_group,
620
                                   std::shared_ptr<TxnLazyCommitter> txn_lazy_committer)
621
174
        : txn_kv_(std::move(txn_kv)),
622
174
          instance_id_(instance.instance_id()),
623
174
          instance_info_(instance),
624
174
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
625
174
          _thread_pool_group(std::move(thread_pool_group)),
626
174
          txn_lazy_committer_(std::move(txn_lazy_committer)),
627
174
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
628
174
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
629
174
    delete_bitmap_lock_white_list_->init();
630
174
    resource_mgr_->init();
631
632
174
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
633
634
    // Since the recycler's resource manager could not be notified when instance info changes,
635
    // we need to refresh the instance info here to ensure the resource manager has the latest info.
636
174
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
637
174
};
638
639
174
InstanceRecycler::~InstanceRecycler() = default;
640
641
148
int InstanceRecycler::init_obj_store_accessors() {
642
148
    for (const auto& obj_info : instance_info_.obj_info()) {
643
105
#ifdef UNIT_TEST
644
105
        auto accessor = std::make_shared<MockAccessor>();
645
#else
646
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
647
        if (!s3_conf) {
648
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
649
            return -1;
650
        }
651
652
        std::shared_ptr<S3Accessor> accessor;
653
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
654
        if (ret != 0) {
655
            LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
656
                         << " resource_id=" << obj_info.id();
657
            return ret;
658
        }
659
#endif
660
105
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
661
105
    }
662
663
148
    return 0;
664
148
}
665
666
148
int InstanceRecycler::init_storage_vault_accessors() {
667
148
    if (instance_info_.resource_ids().empty()) {
668
141
        return 0;
669
141
    }
670
671
7
    FullRangeGetOptions opts(txn_kv_);
672
7
    opts.prefetch = true;
673
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
674
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
675
676
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
677
18
        auto [k, v] = *kv;
678
18
        StorageVaultPB vault;
679
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
680
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
681
0
            return -1;
682
0
        }
683
18
        std::string recycler_storage_vault_white_list = accumulate(
684
18
                config::recycler_storage_vault_white_list.begin(),
685
18
                config::recycler_storage_vault_white_list.end(), std::string(),
686
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
686
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
687
18
        LOG_INFO("config::recycler_storage_vault_white_list")
688
18
                .tag("", recycler_storage_vault_white_list);
689
18
        if (!config::recycler_storage_vault_white_list.empty()) {
690
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
691
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
692
8
                it == config::recycler_storage_vault_white_list.end()) {
693
2
                LOG_WARNING(
694
2
                        "failed to init accessor for vault because this vault is not in "
695
2
                        "config::recycler_storage_vault_white_list. ")
696
2
                        .tag(" vault name:", vault.name())
697
2
                        .tag(" config::recycler_storage_vault_white_list:",
698
2
                             recycler_storage_vault_white_list);
699
2
                continue;
700
2
            }
701
8
        }
702
18
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
703
16
                                 &accessor_map_, &vault);
704
16
        if (vault.has_hdfs_info()) {
705
9
#ifdef ENABLE_HDFS_STORAGE_VAULT
706
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
707
9
            int ret = accessor->init();
708
9
            if (ret != 0) {
709
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
710
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
711
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
712
4
                continue;
713
4
            }
714
9
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
715
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
716
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
717
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
718
#else
719
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
720
                       << "but HDFS storage vaults were detected";
721
#endif
722
7
        } else if (vault.has_obj_info()) {
723
            // TODO: Propagate object storage session tokens to Recycler in a follow-up PR.
724
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
725
7
            if (!s3_conf) {
726
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
727
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
728
1
                continue;
729
1
            }
730
731
6
            std::shared_ptr<S3Accessor> accessor;
732
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
733
6
            if (ret != 0) {
734
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
735
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
736
0
                             << " ret=" << ret
737
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
738
0
                continue;
739
0
            }
740
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
741
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
742
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
743
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
744
6
        }
745
16
    }
746
747
7
    if (!it->is_valid()) {
748
0
        LOG_WARNING("failed to get storage vault kv");
749
0
        return -1;
750
0
    }
751
752
7
    if (accessor_map_.empty()) {
753
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
754
1
        return -2;
755
1
    }
756
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
757
6
             instance_id_);
758
759
6
    return 0;
760
7
}
761
762
149
int InstanceRecycler::init() {
763
149
    if (instance_info_.status() == InstanceInfoPB::DELETED &&
764
149
        (instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING ||
765
4
         instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED)) {
766
1
        return 0;
767
1
    }
768
769
148
    int ret = init_obj_store_accessors();
770
148
    if (ret != 0) {
771
0
        return ret;
772
0
    }
773
774
148
    return init_storage_vault_accessors();
775
148
}
776
777
template <typename... Func>
778
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
779
120
    return [funcs...]() {
780
120
        return [](std::initializer_list<int> ret_vals) {
781
120
            int i = 0;
782
140
            for (int ret : ret_vals) {
783
140
                if (ret != 0) {
784
0
                    i = ret;
785
0
                }
786
140
            }
787
120
            return i;
788
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
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
0
                    i = ret;
785
0
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
0
                    i = ret;
785
0
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
20
            for (int ret : ret_vals) {
783
20
                if (ret != 0) {
784
0
                    i = ret;
785
0
                }
786
20
            }
787
10
            return i;
788
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
0
                    i = ret;
785
0
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
0
                    i = ret;
785
0
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
0
                    i = ret;
785
0
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
20
            for (int ret : ret_vals) {
783
20
                if (ret != 0) {
784
0
                    i = ret;
785
0
                }
786
20
            }
787
10
            return i;
788
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
0
                    i = ret;
785
0
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
0
                    i = ret;
785
0
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
0
                    i = ret;
785
0
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
0
                    i = ret;
785
0
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
0
                    i = ret;
785
0
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
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
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
790
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
778
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
790
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
778
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
790
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
778
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
790
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
778
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
790
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
778
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
790
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
778
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
790
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
778
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
790
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
778
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
790
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
778
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
790
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
778
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
790
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
778
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
790
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
778
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
779
10
    return [funcs...]() {
780
10
        return [](std::initializer_list<int> ret_vals) {
781
10
            int i = 0;
782
10
            for (int ret : ret_vals) {
783
10
                if (ret != 0) {
784
10
                    i = ret;
785
10
                }
786
10
            }
787
10
            return i;
788
10
        }({funcs()...});
789
10
    };
790
10
}
791
792
11
int InstanceRecycler::do_recycle() {
793
11
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
794
11
    tablet_metrics_context_.reset();
795
11
    segment_metrics_context_.reset();
796
11
    DORIS_CLOUD_DEFER {
797
11
        tablet_metrics_context_.finish_report();
798
11
        segment_metrics_context_.finish_report();
799
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
796
11
    DORIS_CLOUD_DEFER {
797
11
        tablet_metrics_context_.finish_report();
798
11
        segment_metrics_context_.finish_report();
799
11
    };
800
11
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
801
1
        int res = recycle_cluster_snapshots();
802
1
        if (res != 0) {
803
0
            return -1;
804
0
        }
805
1
        return recycle_deleted_instance();
806
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
807
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
808
10
                                        fmt::format("instance id {}", instance_id_),
809
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
809
120
                                        [](int r) { return r != 0; });
810
10
        sync_executor
811
10
                .add(task_wrapper(
812
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
812
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
813
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
813
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
814
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
815
                                   // becase they may both recycle the same set of tablets
816
                        // recycle dropped table or idexes(mv, rollup)
817
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
817
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
818
                        // recycle dropped partitions
819
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
819
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
820
10
                .add(task_wrapper(
821
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
821
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
822
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
822
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
823
10
                .add(task_wrapper(
824
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
824
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
825
10
                .add(task_wrapper(
826
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
826
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
827
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
827
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
828
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
828
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
829
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
829
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
830
10
                .add(task_wrapper(
831
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
831
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
832
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
832
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
833
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
833
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
834
10
        bool finished = true;
835
10
        std::vector<int> rets = sync_executor.when_all(&finished);
836
120
        for (int ret : rets) {
837
120
            if (ret != 0) {
838
0
                return ret;
839
0
            }
840
120
        }
841
10
        return finished ? 0 : -1;
842
10
    } else {
843
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
844
0
                     << " instance_id=" << instance_id_;
845
0
        return -1;
846
0
    }
847
11
}
848
849
/**
850
* 1. delete all remote data
851
* 2. delete all kv
852
* 3. remove instance kv depend on config::retain_deleted_instance_tombstone
853
*/
854
13
int InstanceRecycler::recycle_deleted_instance() {
855
13
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
856
857
13
    int ret = 0;
858
13
    auto start_time = steady_clock::now();
859
13
    const auto recycle_state = instance_info_.recycle_state();
860
861
13
    if (config::retain_deleted_instance_tombstone &&
862
13
        recycle_state == InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
863
4
        return 0;
864
4
    }
865
866
9
    DORIS_CLOUD_DEFER {
867
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
868
9
        if (ret != 0) {
869
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
870
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
871
0
                         << "s, instance_id=" << instance_id_;
872
9
        } else if (recycle_state ==
873
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
874
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
875
0
                      << "s, instance_id=" << instance_id_;
876
9
        } else {
877
9
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
878
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
879
9
                      << "s, instance_id=" << instance_id_;
880
9
        }
881
9
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
866
9
    DORIS_CLOUD_DEFER {
867
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
868
9
        if (ret != 0) {
869
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
870
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
871
0
                         << "s, instance_id=" << instance_id_;
872
9
        } else if (recycle_state ==
873
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
874
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
875
0
                      << "s, instance_id=" << instance_id_;
876
9
        } else {
877
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
878
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
879
9
                      << "s, instance_id=" << instance_id_;
880
9
        }
881
9
    };
882
883
9
    switch (recycle_state) {
884
6
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING:
885
6
        ret = recycle_deleted_instance_data();
886
6
        break;
887
3
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING:
888
3
        ret = recycle_deleted_instance_metadata();
889
3
        break;
890
0
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED:
891
0
        ret = remove_instance_key();
892
0
        break;
893
0
    default:
894
0
        LOG_WARNING("invalid instance recycle state")
895
0
                .tag("instance_id", instance_id_)
896
0
                .tag("recycle_state", instance_info_.recycle_state());
897
0
        ret = -1;
898
0
        break;
899
9
    }
900
901
9
    return ret;
902
9
}
903
904
6
int InstanceRecycler::recycle_deleted_instance_data() {
905
6
    int ret = 0;
906
907
    // Step 1: Recycle tmp rowsets (contains ref count but txn is not committed)
908
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
909
6
        int res = recycle_tmp_rowsets();
910
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
911
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
912
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
913
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
914
            // and cannot be recycled.
915
0
            res = recycle_tmp_rowsets();
916
0
        }
917
6
        return res;
918
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
Line
Count
Source
908
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
909
6
        int res = recycle_tmp_rowsets();
910
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
911
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
912
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
913
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
914
            // and cannot be recycled.
915
0
            res = recycle_tmp_rowsets();
916
0
        }
917
6
        return res;
918
6
    };
919
920
6
    if (recycle_tmp_rowsets_with_mark_delete_enabled() != 0) {
921
0
        LOG_WARNING("failed to recycle tmp rowsets").tag("instance_id", instance_id_);
922
0
        return -1;
923
0
    }
924
925
    // Step 2: Recycle versioned rowsets in recycle space (already marked for deletion)
926
6
    if (recycle_versioned_rowsets() != 0) {
927
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
928
0
        return -1;
929
0
    }
930
931
    // Step 3: Recycle operation logs (can recycle logs not referenced by snapshots)
932
6
    if (recycle_operation_logs() != 0) {
933
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
934
0
        return -1;
935
0
    }
936
937
    // Step 4: Check if there are still cluster snapshots
938
6
    bool has_snapshots = false;
939
6
    if (has_cluster_snapshots(&has_snapshots) != 0) {
940
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
941
0
        return -1;
942
6
    } else if (has_snapshots) {
943
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
944
1
        return 0;
945
1
    }
946
947
5
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
948
5
                            instance_info().snapshot_switch_status() !=
949
1
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
950
5
    if (snapshot_enabled) {
951
1
        bool has_unrecycled_rowsets = false;
952
1
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
953
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
954
0
            return -1;
955
1
        } else if (has_unrecycled_rowsets) {
956
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
957
0
                    .tag("instance_id", instance_id_);
958
0
            return ret;
959
0
        }
960
4
    } else { // delete all remote data if snapshot is disabled
961
4
        for (auto& [_, accessor] : accessor_map_) {
962
4
            if (stopped()) {
963
0
                return ret;
964
0
            }
965
966
4
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
967
4
            int del_ret = accessor->delete_all();
968
4
            if (del_ret == 0) {
969
4
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
970
4
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
971
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
972
                // so the recycling has been successful.
973
0
                ret = -1;
974
0
            }
975
4
        }
976
977
4
        if (ret != 0) {
978
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
979
0
            return ret;
980
0
        }
981
4
    }
982
983
5
    if (update_instance_recycle_state(
984
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING,
985
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) != 0) {
986
0
        return -1;
987
0
    }
988
989
5
    return 0;
990
5
}
991
992
7
int InstanceRecycler::recycle_deleted_instance_metadata() {
993
    // Check successor instance, if exists, skip deleting kv because successor instance may still need the data in kv
994
7
    if (instance_info_.has_successor_instance_id() &&
995
7
        !instance_info_.successor_instance_id().empty()) {
996
4
        std::string key = instance_key(instance_info_.successor_instance_id());
997
4
        std::unique_ptr<Transaction> txn;
998
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
999
4
        if (err != TxnErrorCode::TXN_OK) {
1000
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_
1001
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1002
0
                         << " err=" << err;
1003
0
            return -1;
1004
0
        }
1005
1006
4
        InstanceInfoPB successor_instance;
1007
4
        std::string value;
1008
4
        err = txn->get(key, &value);
1009
4
        if (err == TxnErrorCode::TXN_OK) {
1010
3
            InstanceInfoPB successor_instance;
1011
3
            if (!successor_instance.ParseFromString(value)) {
1012
0
                LOG(WARNING) << "failed to parse successor instance, instance_id=" << instance_id_
1013
0
                             << " successor_instance_id=" << instance_info_.successor_instance_id();
1014
0
                return -1;
1015
0
            }
1016
3
            if (!successor_instance.has_recycle_state() ||
1017
3
                successor_instance.recycle_state() !=
1018
2
                        InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1019
2
                LOG(INFO) << "instance successor has not completed recycling, skip deleting kv,"
1020
2
                          << " instance_id=" << instance_id_
1021
2
                          << " successor_instance_id=" << instance_info_.successor_instance_id()
1022
2
                          << " successor_status=" << successor_instance.status()
1023
2
                          << " successor_recycled_state=" << successor_instance.recycle_state();
1024
2
                return 0;
1025
2
            }
1026
3
        } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1027
0
            LOG(WARNING) << "failed to get successor instance, instance_id=" << instance_id_
1028
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1029
0
                         << " err=" << err;
1030
0
            return -1;
1031
0
        }
1032
4
    }
1033
1034
    // delete all kv
1035
5
    std::unique_ptr<Transaction> txn;
1036
5
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1037
5
    if (err != TxnErrorCode::TXN_OK) {
1038
0
        LOG(WARNING) << "failed to create txn";
1039
0
        return -1;
1040
0
    }
1041
5
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
1042
    // delete kv before deleting objects to prevent the checker from misjudging data loss
1043
5
    std::string start_txn_key = txn_key_prefix(instance_id_);
1044
5
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
1045
5
    txn->remove(start_txn_key, end_txn_key);
1046
5
    std::string start_version_key = version_key_prefix(instance_id_);
1047
5
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
1048
5
    txn->remove(start_version_key, end_version_key);
1049
5
    std::string start_meta_key = meta_key_prefix(instance_id_);
1050
5
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
1051
5
    txn->remove(start_meta_key, end_meta_key);
1052
5
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
1053
5
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
1054
5
    txn->remove(start_recycle_key, end_recycle_key);
1055
5
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
1056
5
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1057
5
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
1058
5
    std::string start_copy_key = copy_key_prefix(instance_id_);
1059
5
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
1060
5
    txn->remove(start_copy_key, end_copy_key);
1061
    // should not remove job key range, because we need to reserve job recycle kv
1062
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
1063
5
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
1064
5
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1065
5
    txn->remove(start_job_tablet_key, end_job_tablet_key);
1066
5
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
1067
5
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
1068
5
    std::string start_vault_key = storage_vault_key(key_info0);
1069
5
    std::string end_vault_key = storage_vault_key(key_info1);
1070
5
    txn->remove(start_vault_key, end_vault_key);
1071
5
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
1072
5
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
1073
5
    txn->remove(versioned_version_key_start, versioned_version_key_end);
1074
5
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
1075
5
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
1076
5
    txn->remove(versioned_index_key_start, versioned_index_key_end);
1077
5
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
1078
5
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
1079
5
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
1080
5
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
1081
5
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
1082
5
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
1083
5
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
1084
5
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
1085
5
    txn->remove(versioned_data_key_start, versioned_data_key_end);
1086
5
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
1087
5
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
1088
5
    txn->remove(versioned_log_key_start, versioned_log_key_end);
1089
1090
    // Updating the recycle state also commits this transaction, making the metadata deletions
1091
    // and state transition atomic.
1092
5
    if (update_instance_recycle_state(
1093
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING,
1094
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED, txn.get()) != 0) {
1095
0
        return -1;
1096
0
    }
1097
1098
5
    return 0;
1099
5
}
1100
1101
0
int InstanceRecycler::remove_instance_key() {
1102
0
    std::unique_ptr<Transaction> txn;
1103
0
    std::string key = instance_key(instance_info_.instance_id());
1104
0
    std::string value;
1105
0
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1106
0
    if (err != TxnErrorCode::TXN_OK) {
1107
0
        LOG(WARNING) << "failed to create txn";
1108
0
        return -1;
1109
0
    }
1110
1111
0
    err = txn->get(key, &value);
1112
0
    if (err != TxnErrorCode::TXN_OK) {
1113
0
        LOG(WARNING) << "failed to get instance, instance_id=" << instance_info_.instance_id()
1114
0
                     << ", err=" << err;
1115
0
        return -1;
1116
0
    }
1117
1118
0
    InstanceInfoPB instance;
1119
0
    if (!instance.ParseFromString(value)) {
1120
0
        LOG(WARNING) << "malformed instance info, key=" << key;
1121
0
        return -1;
1122
0
    }
1123
1124
0
    if (instance.status() != InstanceInfoPB::DELETED) {
1125
0
        LOG(WARNING) << "failed to remove instance key, instance is not deleted, instance_id="
1126
0
                     << instance_id_ << ", status=" << instance.status();
1127
0
        return -1;
1128
0
    }
1129
1130
0
    if (instance.recycle_state() != INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1131
0
        LOG(WARNING) << "failed to remove instance key, invalid recycle state, instance_id="
1132
0
                     << instance_id_
1133
0
                     << ", current_state=" << InstanceRecycleState_Name(instance.recycle_state())
1134
0
                     << ", expected_state="
1135
0
                     << InstanceRecycleState_Name(INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1136
0
        return -1;
1137
0
    }
1138
1139
0
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1140
0
    txn->remove(key);
1141
0
    err = txn->commit();
1142
0
    if (err != TxnErrorCode::TXN_OK) {
1143
0
        LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
1144
0
                     << " err=" << err;
1145
0
        return -1;
1146
0
    }
1147
0
    return 0;
1148
0
}
1149
1150
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState expected_state,
1151
7
                                                    InstanceRecycleState target_state) {
1152
7
    std::unique_ptr<Transaction> txn;
1153
7
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1154
7
    if (err != TxnErrorCode::TXN_OK) {
1155
0
        LOG(WARNING) << "failed to create txn";
1156
0
        return -1;
1157
0
    }
1158
7
    return update_instance_recycle_state(expected_state, target_state, txn.get());
1159
7
}
1160
1161
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState current_state,
1162
                                                    InstanceRecycleState target_state,
1163
12
                                                    Transaction* txn) {
1164
12
    const bool valid_transition =
1165
12
            (current_state == INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING &&
1166
12
             target_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) ||
1167
12
            (current_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING &&
1168
6
             target_state == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1169
1170
12
    if (!valid_transition) {
1171
1
        LOG_WARNING("invalid instance recycled state transition")
1172
1
                .tag("instance_id", instance_id_)
1173
1
                .tag("current_state", InstanceRecycleState_Name(current_state))
1174
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1175
1
        return -1;
1176
1
    }
1177
1178
11
    std::string key = instance_key({instance_id_});
1179
11
    std::string value;
1180
11
    TxnErrorCode err = txn->get(key, &value);
1181
11
    if (err != TxnErrorCode::TXN_OK) {
1182
0
        LOG_WARNING("failed to get instance when updating instance recycled state")
1183
0
                .tag("instance_id", instance_id_)
1184
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1185
0
                .tag("target_state", InstanceRecycleState_Name(target_state))
1186
0
                .tag("err", err);
1187
0
        return -1;
1188
0
    }
1189
1190
11
    InstanceInfoPB instance;
1191
11
    if (!instance.ParseFromString(value)) {
1192
0
        LOG_WARNING("failed to parse InstanceInfoPB when updating instance recycled state")
1193
0
                .tag("instance_id", instance_id_)
1194
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1195
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1196
0
        return -1;
1197
0
    }
1198
11
    if (instance.status() != InstanceInfoPB::DELETED) {
1199
0
        LOG_WARNING("instance is not deleted when updating instance recycled state")
1200
0
                .tag("instance_id", instance_id_)
1201
0
                .tag("status", instance.status())
1202
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1203
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1204
0
        return -1;
1205
0
    }
1206
11
    if (instance.recycle_state() != current_state) {
1207
1
        LOG_WARNING("instance recycled state changed before update")
1208
1
                .tag("instance_id", instance_id_)
1209
1
                .tag("current_state", InstanceRecycleState_Name(instance.recycle_state()))
1210
1
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1211
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1212
1
        return -1;
1213
1
    }
1214
1215
10
    instance.set_recycle_state(target_state);
1216
10
    instance.set_recycle_state_update_time_ms(
1217
10
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count());
1218
10
    if (!instance.SerializeToString(&value)) {
1219
0
        LOG_WARNING("failed to serialize InstanceInfoPB when updating instance recycled state")
1220
0
                .tag("instance_id", instance_id_)
1221
0
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1222
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1223
0
        return -1;
1224
0
    }
1225
1226
10
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1227
10
    txn->put(key, value);
1228
10
    err = txn->commit();
1229
10
    if (err != TxnErrorCode::TXN_OK) {
1230
0
        LOG(WARNING) << "failed to commit fdb txn when updating instance recycled state, "
1231
0
                     << "instance_id=" << instance_id_ << ", err=" << err;
1232
0
        return -1;
1233
0
    }
1234
1235
10
    instance_info_.Swap(&instance);
1236
10
    LOG_INFO("updated instance recycled state")
1237
10
            .tag("instance_id", instance_id_)
1238
10
            .tag("recycle_state", InstanceRecycleState_Name(target_state));
1239
10
    return 0;
1240
10
}
1241
1242
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
1243
9
                                          bool* exists, PackedFileRecycleStats* stats) {
1244
9
    if (exists == nullptr) {
1245
0
        return -1;
1246
0
    }
1247
9
    *exists = false;
1248
1249
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
1250
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1251
9
    std::string scan_begin = begin;
1252
1253
9
    while (true) {
1254
9
        std::unique_ptr<RangeGetIterator> it_range;
1255
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
1256
9
        if (get_ret < 0) {
1257
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1258
0
                    .tag("instance_id", instance_id_)
1259
0
                    .tag("tablet_id", tablet_id)
1260
0
                    .tag("ret", get_ret);
1261
0
            return -1;
1262
0
        }
1263
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1264
6
            return 0;
1265
6
        }
1266
1267
3
        std::string last_key;
1268
3
        while (it_range->has_next()) {
1269
3
            auto [k, v] = it_range->next();
1270
3
            last_key.assign(k.data(), k.size());
1271
3
            doris::RowsetMetaCloudPB rowset_meta;
1272
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1273
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1274
0
                        .tag("instance_id", instance_id_)
1275
0
                        .tag("tablet_id", tablet_id)
1276
0
                        .tag("key", hex(k));
1277
0
                continue;
1278
0
            }
1279
3
            if (stats) {
1280
3
                ++stats->rowset_scan_count;
1281
3
            }
1282
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1283
3
                *exists = true;
1284
3
                return 0;
1285
3
            }
1286
3
        }
1287
1288
0
        if (!it_range->more()) {
1289
0
            return 0;
1290
0
        }
1291
1292
        // Continue scanning from the next key to keep each transaction short.
1293
0
        scan_begin = std::move(last_key);
1294
0
        scan_begin.push_back('\x00');
1295
0
    }
1296
9
}
1297
1298
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1299
                                                          const std::string& rowset_id,
1300
                                                          int64_t txn_id, bool* recycle_exists,
1301
11
                                                          bool* tmp_exists) {
1302
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1303
0
        return -1;
1304
0
    }
1305
11
    *recycle_exists = false;
1306
11
    *tmp_exists = false;
1307
1308
11
    if (txn_id <= 0) {
1309
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1310
0
                .tag("instance_id", instance_id_)
1311
0
                .tag("tablet_id", tablet_id)
1312
0
                .tag("rowset_id", rowset_id)
1313
0
                .tag("txn_id", txn_id);
1314
0
        return -1;
1315
0
    }
1316
1317
11
    std::unique_ptr<Transaction> txn;
1318
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1319
11
    if (err != TxnErrorCode::TXN_OK) {
1320
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1321
0
                .tag("instance_id", instance_id_)
1322
0
                .tag("tablet_id", tablet_id)
1323
0
                .tag("rowset_id", rowset_id)
1324
0
                .tag("txn_id", txn_id)
1325
0
                .tag("err", err);
1326
0
        return -1;
1327
0
    }
1328
1329
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1330
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1331
11
    if (ret == TxnErrorCode::TXN_OK) {
1332
1
        *recycle_exists = true;
1333
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1334
0
        LOG_WARNING("failed to check recycle rowset existence")
1335
0
                .tag("instance_id", instance_id_)
1336
0
                .tag("tablet_id", tablet_id)
1337
0
                .tag("rowset_id", rowset_id)
1338
0
                .tag("key", hex(recycle_key))
1339
0
                .tag("err", ret);
1340
0
        return -1;
1341
0
    }
1342
1343
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1344
11
    ret = key_exists(txn.get(), tmp_key, true);
1345
11
    if (ret == TxnErrorCode::TXN_OK) {
1346
1
        *tmp_exists = true;
1347
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1348
0
        LOG_WARNING("failed to check tmp rowset existence")
1349
0
                .tag("instance_id", instance_id_)
1350
0
                .tag("tablet_id", tablet_id)
1351
0
                .tag("txn_id", txn_id)
1352
0
                .tag("key", hex(tmp_key))
1353
0
                .tag("err", ret);
1354
0
        return -1;
1355
0
    }
1356
1357
11
    return 0;
1358
11
}
1359
1360
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1361
8
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1362
8
    if (!hint.empty()) {
1363
8
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1364
8
            return {hint, it->second};
1365
8
        }
1366
8
    }
1367
1368
0
    return {"", nullptr};
1369
8
}
1370
1371
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1372
                                               const std::string& packed_file_path,
1373
3
                                               PackedFileRecycleStats* stats) {
1374
3
    bool local_changed = false;
1375
3
    int64_t left_num = 0;
1376
3
    int64_t left_bytes = 0;
1377
3
    bool all_small_files_confirmed = true;
1378
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1379
1380
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1381
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1382
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1383
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1384
14
        LOG_INFO("packed slice correction status")
1385
14
                .tag("instance_id", instance_id_)
1386
14
                .tag("packed_file_path", packed_file_path)
1387
14
                .tag("small_file_path", file.path())
1388
14
                .tag("tablet_id", tablet_id)
1389
14
                .tag("rowset_id", rowset_id)
1390
14
                .tag("txn_id", txn_id)
1391
14
                .tag("size", file.size())
1392
14
                .tag("deleted", file.deleted())
1393
14
                .tag("corrected", file.corrected())
1394
14
                .tag("confirmed_this_round", confirmed_this_round);
1395
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
1380
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1381
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1382
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1383
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1384
        LOG_INFO("packed slice correction status")
1385
14
                .tag("instance_id", instance_id_)
1386
14
                .tag("packed_file_path", packed_file_path)
1387
14
                .tag("small_file_path", file.path())
1388
14
                .tag("tablet_id", tablet_id)
1389
14
                .tag("rowset_id", rowset_id)
1390
14
                .tag("txn_id", txn_id)
1391
14
                .tag("size", file.size())
1392
14
                .tag("deleted", file.deleted())
1393
14
                .tag("corrected", file.corrected())
1394
14
                .tag("confirmed_this_round", confirmed_this_round);
1395
14
    };
1396
1397
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1398
14
        auto* small_file = packed_info->mutable_slices(i);
1399
14
        if (small_file->deleted()) {
1400
3
            log_small_file_status(*small_file, small_file->corrected());
1401
3
            continue;
1402
3
        }
1403
1404
11
        if (small_file->corrected()) {
1405
0
            left_num++;
1406
0
            left_bytes += small_file->size();
1407
0
            log_small_file_status(*small_file, true);
1408
0
            continue;
1409
0
        }
1410
1411
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1412
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1413
0
                    .tag("instance_id", instance_id_)
1414
0
                    .tag("small_file_path", small_file->path())
1415
0
                    .tag("index", i);
1416
0
            return -1;
1417
0
        }
1418
1419
11
        int64_t tablet_id = small_file->tablet_id();
1420
11
        const std::string& rowset_id = small_file->rowset_id();
1421
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1422
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1423
0
                    .tag("instance_id", instance_id_)
1424
0
                    .tag("small_file_path", small_file->path())
1425
0
                    .tag("index", i)
1426
0
                    .tag("tablet_id", tablet_id)
1427
0
                    .tag("rowset_id", rowset_id)
1428
0
                    .tag("has_txn_id", small_file->has_txn_id())
1429
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1430
0
            return -1;
1431
0
        }
1432
11
        int64_t txn_id = small_file->txn_id();
1433
11
        bool recycle_exists = false;
1434
11
        bool tmp_exists = false;
1435
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1436
11
                                                &tmp_exists) != 0) {
1437
0
            return -1;
1438
0
        }
1439
1440
11
        bool small_file_confirmed = false;
1441
11
        if (tmp_exists) {
1442
1
            left_num++;
1443
1
            left_bytes += small_file->size();
1444
1
            small_file_confirmed = true;
1445
10
        } else if (recycle_exists) {
1446
1
            left_num++;
1447
1
            left_bytes += small_file->size();
1448
            // keep small_file_confirmed=false so the packed file remains uncorrected
1449
9
        } else {
1450
9
            bool rowset_exists = false;
1451
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1452
0
                return -1;
1453
0
            }
1454
1455
9
            if (!rowset_exists) {
1456
6
                if (!small_file->deleted()) {
1457
6
                    small_file->set_deleted(true);
1458
6
                    local_changed = true;
1459
6
                }
1460
6
                if (!small_file->corrected()) {
1461
6
                    small_file->set_corrected(true);
1462
6
                    local_changed = true;
1463
6
                }
1464
6
                small_file_confirmed = true;
1465
6
            } else {
1466
3
                left_num++;
1467
3
                left_bytes += small_file->size();
1468
3
                small_file_confirmed = true;
1469
3
            }
1470
9
        }
1471
1472
11
        if (!small_file_confirmed) {
1473
1
            all_small_files_confirmed = false;
1474
1
        }
1475
1476
11
        if (small_file->corrected() != small_file_confirmed) {
1477
4
            small_file->set_corrected(small_file_confirmed);
1478
4
            local_changed = true;
1479
4
        }
1480
1481
11
        log_small_file_status(*small_file, small_file_confirmed);
1482
11
    }
1483
1484
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1485
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1486
3
        local_changed = true;
1487
3
    }
1488
3
    if (packed_info->ref_cnt() != left_num) {
1489
3
        auto old_ref_cnt = packed_info->ref_cnt();
1490
3
        packed_info->set_ref_cnt(left_num);
1491
3
        LOG_INFO("corrected packed file ref count")
1492
3
                .tag("instance_id", instance_id_)
1493
3
                .tag("resource_id", packed_info->resource_id())
1494
3
                .tag("packed_file_path", packed_file_path)
1495
3
                .tag("old_ref_cnt", old_ref_cnt)
1496
3
                .tag("new_ref_cnt", left_num);
1497
3
        local_changed = true;
1498
3
    }
1499
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1500
2
        packed_info->set_corrected(all_small_files_confirmed);
1501
2
        local_changed = true;
1502
2
    }
1503
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1504
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1505
1
        local_changed = true;
1506
1
    }
1507
1508
3
    if (changed != nullptr) {
1509
3
        *changed = local_changed;
1510
3
    }
1511
3
    return 0;
1512
3
}
1513
1514
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1515
                                                 const std::string& packed_file_path,
1516
3
                                                 PackedFileRecycleStats* stats) {
1517
3
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1518
3
    bool correction_ok = false;
1519
3
    cloud::PackedFileInfoPB packed_info;
1520
1521
3
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1522
3
        if (stopped()) {
1523
0
            LOG_WARNING("recycler stopped before processing packed file")
1524
0
                    .tag("instance_id", instance_id_)
1525
0
                    .tag("packed_file_path", packed_file_path)
1526
0
                    .tag("attempt", attempt);
1527
0
            return -1;
1528
0
        }
1529
1530
3
        std::unique_ptr<Transaction> txn;
1531
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1532
3
        if (err != TxnErrorCode::TXN_OK) {
1533
0
            LOG_WARNING("failed to create txn when processing packed file")
1534
0
                    .tag("instance_id", instance_id_)
1535
0
                    .tag("packed_file_path", packed_file_path)
1536
0
                    .tag("attempt", attempt)
1537
0
                    .tag("err", err);
1538
0
            return -1;
1539
0
        }
1540
1541
3
        std::string packed_val;
1542
3
        err = txn->get(packed_key, &packed_val);
1543
3
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1544
0
            return 0;
1545
0
        }
1546
3
        if (err != TxnErrorCode::TXN_OK) {
1547
0
            LOG_WARNING("failed to get packed file kv")
1548
0
                    .tag("instance_id", instance_id_)
1549
0
                    .tag("packed_file_path", packed_file_path)
1550
0
                    .tag("attempt", attempt)
1551
0
                    .tag("err", err);
1552
0
            return -1;
1553
0
        }
1554
1555
3
        if (!packed_info.ParseFromString(packed_val)) {
1556
0
            LOG_WARNING("failed to parse packed file info")
1557
0
                    .tag("instance_id", instance_id_)
1558
0
                    .tag("packed_file_path", packed_file_path)
1559
0
                    .tag("attempt", attempt);
1560
0
            return -1;
1561
0
        }
1562
1563
3
        int64_t now_sec = ::time(nullptr);
1564
3
        bool corrected = packed_info.corrected();
1565
3
        bool due = config::force_immediate_recycle ||
1566
3
                   now_sec - packed_info.created_at_sec() >=
1567
3
                           config::packed_file_correction_delay_seconds;
1568
1569
3
        if (!corrected && due) {
1570
3
            bool changed = false;
1571
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1572
0
                LOG_WARNING("correct_packed_file_info failed")
1573
0
                        .tag("instance_id", instance_id_)
1574
0
                        .tag("packed_file_path", packed_file_path)
1575
0
                        .tag("attempt", attempt);
1576
0
                return -1;
1577
0
            }
1578
3
            if (changed) {
1579
3
                std::string updated;
1580
3
                if (!packed_info.SerializeToString(&updated)) {
1581
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1582
0
                            .tag("instance_id", instance_id_)
1583
0
                            .tag("packed_file_path", packed_file_path)
1584
0
                            .tag("attempt", attempt);
1585
0
                    return -1;
1586
0
                }
1587
3
                txn->put(packed_key, updated);
1588
3
                err = txn->commit();
1589
3
                if (err == TxnErrorCode::TXN_OK) {
1590
3
                    if (stats) {
1591
3
                        ++stats->num_corrected;
1592
3
                    }
1593
3
                } else {
1594
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1595
0
                        LOG_WARNING(
1596
0
                                "failed to commit correction for packed file due to conflict, "
1597
0
                                "retrying")
1598
0
                                .tag("instance_id", instance_id_)
1599
0
                                .tag("packed_file_path", packed_file_path)
1600
0
                                .tag("attempt", attempt);
1601
0
                        sleep_for_packed_file_retry();
1602
0
                        packed_info.Clear();
1603
0
                        continue;
1604
0
                    }
1605
0
                    LOG_WARNING("failed to commit correction for packed file")
1606
0
                            .tag("instance_id", instance_id_)
1607
0
                            .tag("packed_file_path", packed_file_path)
1608
0
                            .tag("attempt", attempt)
1609
0
                            .tag("err", err);
1610
0
                    return -1;
1611
0
                }
1612
3
            }
1613
3
        }
1614
1615
3
        correction_ok = true;
1616
3
        break;
1617
3
    }
1618
1619
3
    if (!correction_ok) {
1620
0
        return -1;
1621
0
    }
1622
1623
3
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1624
3
          packed_info.ref_cnt() == 0)) {
1625
2
        return 0;
1626
2
    }
1627
1628
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1629
0
        LOG_WARNING("packed file missing resource id when recycling")
1630
0
                .tag("instance_id", instance_id_)
1631
0
                .tag("packed_file_path", packed_file_path);
1632
0
        return -1;
1633
0
    }
1634
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1635
1
    if (!accessor) {
1636
0
        LOG_WARNING("no accessor available to delete packed file")
1637
0
                .tag("instance_id", instance_id_)
1638
0
                .tag("packed_file_path", packed_file_path)
1639
0
                .tag("resource_id", packed_info.resource_id());
1640
0
        return -1;
1641
0
    }
1642
1
    int del_ret = accessor->delete_file(packed_file_path);
1643
1
    if (del_ret != 0 && del_ret != 1) {
1644
0
        LOG_WARNING("failed to delete packed file")
1645
0
                .tag("instance_id", instance_id_)
1646
0
                .tag("packed_file_path", packed_file_path)
1647
0
                .tag("resource_id", resource_id)
1648
0
                .tag("ret", del_ret);
1649
0
        return -1;
1650
0
    }
1651
1
    if (del_ret == 1) {
1652
0
        LOG_INFO("packed file already removed")
1653
0
                .tag("instance_id", instance_id_)
1654
0
                .tag("packed_file_path", packed_file_path)
1655
0
                .tag("resource_id", resource_id);
1656
1
    } else {
1657
1
        LOG_INFO("deleted packed file")
1658
1
                .tag("instance_id", instance_id_)
1659
1
                .tag("packed_file_path", packed_file_path)
1660
1
                .tag("resource_id", resource_id);
1661
1
    }
1662
1663
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1664
1
        std::unique_ptr<Transaction> del_txn;
1665
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1666
1
        if (err != TxnErrorCode::TXN_OK) {
1667
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1668
0
                    .tag("instance_id", instance_id_)
1669
0
                    .tag("packed_file_path", packed_file_path)
1670
0
                    .tag("del_attempt", del_attempt)
1671
0
                    .tag("err", err);
1672
0
            return -1;
1673
0
        }
1674
1675
1
        std::string latest_val;
1676
1
        err = del_txn->get(packed_key, &latest_val);
1677
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1678
0
            return 0;
1679
0
        }
1680
1
        if (err != TxnErrorCode::TXN_OK) {
1681
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1682
0
                    .tag("instance_id", instance_id_)
1683
0
                    .tag("packed_file_path", packed_file_path)
1684
0
                    .tag("del_attempt", del_attempt)
1685
0
                    .tag("err", err);
1686
0
            return -1;
1687
0
        }
1688
1689
1
        cloud::PackedFileInfoPB latest_info;
1690
1
        if (!latest_info.ParseFromString(latest_val)) {
1691
0
            LOG_WARNING("failed to parse packed file info before removal")
1692
0
                    .tag("instance_id", instance_id_)
1693
0
                    .tag("packed_file_path", packed_file_path)
1694
0
                    .tag("del_attempt", del_attempt);
1695
0
            return -1;
1696
0
        }
1697
1698
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1699
1
              latest_info.ref_cnt() == 0)) {
1700
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1701
0
                    .tag("instance_id", instance_id_)
1702
0
                    .tag("packed_file_path", packed_file_path)
1703
0
                    .tag("del_attempt", del_attempt);
1704
0
            return 0;
1705
0
        }
1706
1707
1
        del_txn->remove(packed_key);
1708
1
        err = del_txn->commit();
1709
1
        if (err == TxnErrorCode::TXN_OK) {
1710
1
            if (stats) {
1711
1
                ++stats->num_deleted;
1712
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1713
1
                                        static_cast<int64_t>(latest_val.size());
1714
1
                if (del_ret == 0 || del_ret == 1) {
1715
1
                    ++stats->num_object_deleted;
1716
1
                    int64_t object_size = latest_info.total_slice_bytes();
1717
1
                    if (object_size <= 0) {
1718
0
                        object_size = packed_info.total_slice_bytes();
1719
0
                    }
1720
1
                    stats->bytes_object_deleted += object_size;
1721
1
                }
1722
1
            }
1723
1
            LOG_INFO("removed packed file metadata")
1724
1
                    .tag("instance_id", instance_id_)
1725
1
                    .tag("packed_file_path", packed_file_path);
1726
1
            return 0;
1727
1
        }
1728
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1729
0
            if (del_attempt >= max_retry_times) {
1730
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1731
0
                        .tag("instance_id", instance_id_)
1732
0
                        .tag("packed_file_path", packed_file_path)
1733
0
                        .tag("del_attempt", del_attempt);
1734
0
                return -1;
1735
0
            }
1736
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1737
0
                    .tag("instance_id", instance_id_)
1738
0
                    .tag("packed_file_path", packed_file_path)
1739
0
                    .tag("del_attempt", del_attempt);
1740
0
            sleep_for_packed_file_retry();
1741
0
            continue;
1742
0
        }
1743
0
        LOG_WARNING("failed to remove packed file kv")
1744
0
                .tag("instance_id", instance_id_)
1745
0
                .tag("packed_file_path", packed_file_path)
1746
0
                .tag("del_attempt", del_attempt)
1747
0
                .tag("err", err);
1748
0
        return -1;
1749
0
    }
1750
1751
0
    return -1;
1752
1
}
1753
1754
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view value,
1755
4
                                            PackedFileRecycleStats* stats, int* ret) {
1756
4
    if (stats) {
1757
4
        ++stats->num_scanned;
1758
4
    }
1759
4
    std::string packed_file_path;
1760
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1761
0
        LOG_WARNING("failed to decode packed file key")
1762
0
                .tag("instance_id", instance_id_)
1763
0
                .tag("key", hex(key));
1764
0
        if (stats) {
1765
0
            ++stats->num_failed;
1766
0
        }
1767
0
        if (ret) {
1768
0
            *ret = -1;
1769
0
        }
1770
0
        return 0;
1771
0
    }
1772
1773
4
    cloud::PackedFileInfoPB packed_info;
1774
4
    if (!packed_info.ParseFromArray(value.data(), value.size())) {
1775
0
        LOG_WARNING("failed to parse packed file info from scan")
1776
0
                .tag("instance_id", instance_id_)
1777
0
                .tag("packed_file_path", packed_file_path);
1778
0
        if (stats) {
1779
0
            ++stats->num_failed;
1780
0
        }
1781
0
        if (ret) {
1782
0
            *ret = -1;
1783
0
        }
1784
0
        return 0;
1785
0
    }
1786
1787
4
    const int64_t now_sec = ::time(nullptr);
1788
4
    const bool due =
1789
4
            config::force_immediate_recycle ||
1790
4
            now_sec - packed_info.created_at_sec() >= config::packed_file_correction_delay_seconds;
1791
4
    const bool need_correction = !packed_info.corrected() && due;
1792
4
    const bool need_recycle =
1793
4
            packed_info.state() == cloud::PackedFileInfoPB::RECYCLING && packed_info.ref_cnt() == 0;
1794
4
    if (!need_correction && !need_recycle) {
1795
1
        return 0;
1796
1
    }
1797
1798
3
    std::string packed_key(key);
1799
3
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1800
3
    if (process_ret != 0) {
1801
0
        if (stats) {
1802
0
            ++stats->num_failed;
1803
0
        }
1804
0
        if (ret) {
1805
0
            *ret = -1;
1806
0
        }
1807
0
    }
1808
3
    return 0;
1809
4
}
1810
1811
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1812
6.34k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1813
6.34k
    if (config::force_immediate_recycle) {
1814
295
        return 0L;
1815
295
    }
1816
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1817
6.05k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1818
6.05k
    int64_t retention_seconds = config::retention_seconds;
1819
6.05k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1820
4.75k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1821
4.75k
    }
1822
6.05k
    int64_t final_expiration = expiration + retention_seconds;
1823
6.05k
    if (*earlest_ts > final_expiration) {
1824
17
        *earlest_ts = final_expiration;
1825
17
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1826
17
    }
1827
6.05k
    return final_expiration;
1828
6.34k
}
1829
1830
int64_t calculate_partition_expired_time(
1831
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1832
11
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1833
11
    if (config::force_immediate_recycle) {
1834
5
        return 0L;
1835
5
    }
1836
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1837
6
                                                            : partition_meta_pb.creation_time();
1838
6
    int64_t retention_seconds = config::retention_seconds;
1839
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1840
6
        retention_seconds =
1841
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1842
6
    }
1843
6
    int64_t final_expiration = expiration + retention_seconds;
1844
6
    if (*earlest_ts > final_expiration) {
1845
2
        *earlest_ts = final_expiration;
1846
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1847
2
    }
1848
6
    return final_expiration;
1849
11
}
1850
1851
int64_t calculate_index_expired_time(const std::string& instance_id_,
1852
                                     const RecycleIndexPB& index_meta_pb,
1853
14
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1854
14
    if (config::force_immediate_recycle) {
1855
8
        return 0L;
1856
8
    }
1857
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1858
6
                                                        : index_meta_pb.creation_time();
1859
6
    int64_t retention_seconds = config::retention_seconds;
1860
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1861
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1862
6
    }
1863
6
    int64_t final_expiration = expiration + retention_seconds;
1864
6
    if (*earlest_ts > final_expiration) {
1865
2
        *earlest_ts = final_expiration;
1866
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1867
2
    }
1868
6
    return final_expiration;
1869
14
}
1870
1871
int64_t calculate_tmp_rowset_expired_time(
1872
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1873
53.2k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1874
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1875
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1876
    //  duration or timeout always < `retention_time` in practice.
1877
53.2k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1878
53.2k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1879
53.2k
                                 : tmp_rowset_meta_pb.creation_time();
1880
53.2k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1881
53.2k
    int64_t final_expiration = expiration + config::retention_seconds;
1882
53.2k
    if (*earlest_ts > final_expiration) {
1883
20
        *earlest_ts = final_expiration;
1884
20
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1885
20
    }
1886
53.2k
    return final_expiration;
1887
53.2k
}
1888
1889
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1890
30.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1891
30.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1892
30.0k
    if (*earlest_ts > final_expiration / 1000) {
1893
8
        *earlest_ts = final_expiration / 1000;
1894
8
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1895
8
    }
1896
30.0k
    return final_expiration;
1897
30.0k
}
1898
1899
int64_t calculate_restore_job_expired_time(
1900
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1901
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1902
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1903
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1904
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1905
        // final state, recycle immediately
1906
41
        return 0L;
1907
41
    }
1908
    // not final state, wait much longer than the FE's timeout(1 day)
1909
0
    int64_t last_modified_s =
1910
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1911
0
    int64_t expiration = restore_job.expired_at_s() > 0
1912
0
                                 ? last_modified_s + restore_job.expired_at_s()
1913
0
                                 : last_modified_s;
1914
0
    int64_t final_expiration = expiration + config::retention_seconds;
1915
0
    if (*earlest_ts > final_expiration) {
1916
0
        *earlest_ts = final_expiration;
1917
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1918
0
    }
1919
0
    return final_expiration;
1920
41
}
1921
1922
537
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1923
537
    AbortTxnRequest req;
1924
537
    TxnInfoPB txn_info;
1925
537
    MetaServiceCode code = MetaServiceCode::OK;
1926
537
    std::string msg;
1927
537
    std::stringstream ss;
1928
537
    std::unique_ptr<Transaction> txn;
1929
537
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1930
537
    if (err != TxnErrorCode::TXN_OK) {
1931
0
        LOG_WARNING("failed to create txn").tag("err", err);
1932
0
        return -1;
1933
0
    }
1934
1935
    // get txn index
1936
537
    TxnIndexPB txn_idx_pb;
1937
537
    auto index_key = txn_index_key({instance_id_, txn_id});
1938
537
    std::string index_val;
1939
537
    err = txn->get(index_key, &index_val);
1940
537
    if (err != TxnErrorCode::TXN_OK) {
1941
2
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1942
            // maybe recycled
1943
2
            LOG_WARNING("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1944
2
                    .tag("key", hex(index_key))
1945
2
                    .tag("txn_id", txn_id);
1946
2
            return 0;
1947
2
        }
1948
0
        LOG_WARNING("failed to get txn index")
1949
0
                .tag("err", err)
1950
0
                .tag("key", hex(index_key))
1951
0
                .tag("txn_id", txn_id);
1952
0
        return -1;
1953
2
    }
1954
535
    if (!txn_idx_pb.ParseFromString(index_val)) {
1955
1
        LOG_WARNING("failed to parse txn index")
1956
1
                .tag("err", err)
1957
1
                .tag("key", hex(index_key))
1958
1
                .tag("txn_id", txn_id);
1959
1
        return -1;
1960
1
    }
1961
534
    if (!txn_idx_pb.has_tablet_index() || !txn_idx_pb.tablet_index().has_db_id() ||
1962
534
        txn_idx_pb.tablet_index().db_id() <= 0) {
1963
3
        LOG_WARNING("malformed txn index, tablet index is missing or db id is invalid")
1964
3
                .tag("key", hex(index_key))
1965
3
                .tag("txn_id", txn_id)
1966
3
                .tag("db_id",
1967
3
                     txn_idx_pb.has_tablet_index() ? txn_idx_pb.tablet_index().db_id() : 0);
1968
3
        return -1;
1969
3
    }
1970
1971
531
    const int64_t db_id = txn_idx_pb.tablet_index().db_id();
1972
531
    const int64_t owner_txn_id =
1973
531
            txn_idx_pb.has_parent_txn_id() ? txn_idx_pb.parent_txn_id() : txn_id;
1974
531
    if (owner_txn_id <= 0) {
1975
1
        LOG_WARNING("malformed txn index, owner txn id is invalid")
1976
1
                .tag("key", hex(index_key))
1977
1
                .tag("txn_id", txn_id)
1978
1
                .tag("owner_txn_id", owner_txn_id);
1979
1
        return -1;
1980
1
    }
1981
1982
530
    auto info_key = txn_info_key({instance_id_, db_id, owner_txn_id});
1983
530
    std::string info_val;
1984
530
    err = txn->get(info_key, &info_val);
1985
530
    if (err != TxnErrorCode::TXN_OK) {
1986
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1987
            // maybe recycled
1988
1
            LOG_WARNING("txn info not found, txn_id={} owner_txn_id={} instance_id={}", txn_id,
1989
1
                        owner_txn_id, instance_id_)
1990
1
                    .tag("key", hex(info_key))
1991
1
                    .tag("txn_id", txn_id)
1992
1
                    .tag("owner_txn_id", owner_txn_id);
1993
1
            return 0;
1994
1
        }
1995
0
        LOG_WARNING("failed to get txn info")
1996
0
                .tag("err", err)
1997
0
                .tag("key", hex(info_key))
1998
0
                .tag("txn_id", txn_id)
1999
0
                .tag("owner_txn_id", owner_txn_id);
2000
0
        return -1;
2001
1
    }
2002
529
    if (!txn_info.ParseFromString(info_val)) {
2003
1
        LOG_WARNING("failed to parse txn info")
2004
1
                .tag("err", err)
2005
1
                .tag("key", hex(info_key))
2006
1
                .tag("txn_id", txn_id)
2007
1
                .tag("owner_txn_id", owner_txn_id);
2008
1
        return -1;
2009
1
    }
2010
528
    if (!txn_info.has_txn_id() || txn_info.txn_id() != owner_txn_id) {
2011
1
        LOG_WARNING("malformed txn info, txn id does not match owner txn id")
2012
1
                .tag("key", hex(info_key))
2013
1
                .tag("txn_id", txn_id)
2014
1
                .tag("owner_txn_id", owner_txn_id)
2015
1
                .tag("txn_info_txn_id", txn_info.txn_id());
2016
1
        return -1;
2017
1
    }
2018
2019
527
    if (txn_info.status() == TxnStatusPB::TXN_STATUS_ABORTED) {
2020
514
        LOG_INFO("txn has already been aborted, txn_id={} owner_txn_id={}", txn_id, owner_txn_id)
2021
514
                .tag("key", hex(info_key))
2022
514
                .tag("txn_id", txn_id)
2023
514
                .tag("owner_txn_id", owner_txn_id);
2024
514
        return 0;
2025
514
    }
2026
13
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
2027
4
        LOG_WARNING("txn cannot be aborted, txn_id={} owner_txn_id={} status={}", txn_id,
2028
4
                    owner_txn_id, txn_info.status())
2029
4
                .tag("key", hex(info_key))
2030
4
                .tag("txn_id", txn_id)
2031
4
                .tag("owner_txn_id", owner_txn_id);
2032
4
        return -1;
2033
4
    }
2034
2035
9
    req.set_txn_id(owner_txn_id);
2036
9
    req.set_db_id(db_id);
2037
2038
9
    LOG(WARNING) << "begin abort txn for related rowset, txn_id=" << txn_id
2039
9
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2040
9
                 << " txn_info=" << txn_info.ShortDebugString();
2041
2042
9
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
2043
9
    if (code != MetaServiceCode::OK) {
2044
0
        LOG(WARNING) << "failed to abort txn for related rowset, txn_id=" << txn_id
2045
0
                     << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2046
0
                     << " code=" << code << " msg=" << msg;
2047
0
        return -1;
2048
0
    }
2049
2050
9
    err = txn->commit();
2051
9
    if (err != TxnErrorCode::TXN_OK) {
2052
0
        code = cast_as<ErrCategory::COMMIT>(err);
2053
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
2054
0
        msg = ss.str();
2055
0
        return -1;
2056
0
    }
2057
2058
9
    LOG(WARNING) << "finish abort txn for related rowset, txn_id=" << txn_id
2059
9
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2060
9
                 << " txn_info=" << txn_info.ShortDebugString() << " code=" << code
2061
9
                 << " msg=" << msg;
2062
2063
9
    return 0;
2064
9
}
2065
2066
int InstanceRecycler::abort_job_for_related_rowset(int64_t tablet_id, const std::string& rowset_id,
2067
11
                                                   const std::string& job_id) {
2068
11
    FinishTabletJobRequest req;
2069
11
    FinishTabletJobResponse res;
2070
11
    req.set_action(FinishTabletJobRequest::ABORT);
2071
11
    MetaServiceCode code = MetaServiceCode::OK;
2072
11
    std::string msg;
2073
11
    std::stringstream ss;
2074
2075
11
    TabletIndexPB tablet_idx;
2076
11
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, tablet_id, tablet_idx);
2077
11
    if (ret == 1) {
2078
        // tablet maybe recycled, directly return 0
2079
1
        return 0;
2080
10
    } else if (ret != 0) {
2081
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << tablet_id
2082
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
2083
0
        return ret;
2084
0
    }
2085
2086
10
    std::unique_ptr<Transaction> txn;
2087
10
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2088
10
    if (err != TxnErrorCode::TXN_OK) {
2089
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
2090
0
        return -1;
2091
0
    }
2092
2093
10
    std::string job_key =
2094
10
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
2095
10
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
2096
10
    std::string job_val;
2097
10
    err = txn->get(job_key, &job_val);
2098
10
    if (err != TxnErrorCode::TXN_OK) {
2099
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2100
1
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
2101
1
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2102
            // A previous recycler round may have aborted the job. The caller must recheck the
2103
            // recycle key before deleting object data.
2104
1
            return 0;
2105
1
        }
2106
1
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
2107
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
2108
0
                     << " key=" << hex(job_key);
2109
0
        return -1;
2110
1
    }
2111
2112
9
    TabletJobInfoPB job_pb;
2113
9
    if (!job_pb.ParseFromString(job_val)) {
2114
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
2115
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2116
0
        return -1;
2117
0
    }
2118
2119
9
    const TabletCompactionJobPB* matched_compaction = nullptr;
2120
9
    for (const auto& compaction : job_pb.compaction()) {
2121
9
        if (compaction.id() == job_id) {
2122
5
            matched_compaction = &compaction;
2123
5
            break;
2124
5
        }
2125
9
    }
2126
9
    const TabletSchemaChangeJobPB* matched_schema_change = nullptr;
2127
9
    if (matched_compaction == nullptr && job_pb.has_schema_change() &&
2128
9
        job_pb.schema_change().id() == job_id) {
2129
3
        matched_schema_change = &job_pb.schema_change();
2130
3
    }
2131
2132
9
    if (matched_compaction != nullptr || matched_schema_change != nullptr) {
2133
8
        LOG(WARNING) << "begin to abort job for related rowset, job_id=" << job_id
2134
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
2135
        // Compaction jobs belong to the rowset's tablet. A schema-change job is mirrored under
2136
        // the new tablet key, but its recorded index remains the base tablet so ABORT can remove
2137
        // both the base and mirrored schema-change records.
2138
8
        if (matched_compaction != nullptr) {
2139
5
            req.mutable_job()->mutable_idx()->CopyFrom(tablet_idx);
2140
5
            req.mutable_job()->add_compaction()->CopyFrom(*matched_compaction);
2141
5
        } else {
2142
3
            req.mutable_job()->mutable_idx()->CopyFrom(job_pb.idx());
2143
3
            req.mutable_job()->mutable_schema_change()->CopyFrom(*matched_schema_change);
2144
3
        }
2145
8
        req.set_action(FinishTabletJobRequest::ABORT);
2146
8
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
2147
8
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
2148
8
                           ss);
2149
8
        if (code != MetaServiceCode::OK) {
2150
            // These two codes mean that the job cannot be aborted anymore.
2151
            // TABLET_NOT_FOUND means that the tablet has been dropped or recycled.
2152
            // There is no running job that still owns the PREPARE rowset, so the caller may
2153
            // recheck the recycle key.
2154
0
            bool no_job_to_abort = code == MetaServiceCode::TABLET_NOT_FOUND;
2155
            // INVALID_ARGUMENT has more than one meaning. It may mean that this job was removed or
2156
            // replaced by a newer job, but it may also report invalid metadata. Read the current
2157
            // job again and continue recycling only when the target job id no longer exists.
2158
0
            if (!no_job_to_abort && code == MetaServiceCode::INVALID_ARGUMENT) {
2159
0
                std::unique_ptr<Transaction> check_txn;
2160
0
                err = txn_kv_->create_txn(&check_txn);
2161
0
                if (err != TxnErrorCode::TXN_OK) {
2162
0
                    LOG(WARNING) << "failed to create txn to check related job, instance_id="
2163
0
                                 << instance_id_ << " err=" << err;
2164
0
                    return -1;
2165
0
                }
2166
2167
0
                const auto& idx = req.job().idx();
2168
0
                std::string current_job_key =
2169
0
                        job_tablet_key({instance_id_, idx.table_id(), idx.index_id(),
2170
0
                                        idx.partition_id(), idx.tablet_id()});
2171
0
                std::string current_job_val;
2172
0
                err = check_txn->get(current_job_key, &current_job_val);
2173
0
                if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2174
0
                    no_job_to_abort = true;
2175
0
                } else if (err != TxnErrorCode::TXN_OK) {
2176
0
                    LOG(WARNING) << "failed to check related job, instance_id=" << instance_id_
2177
0
                                 << " tablet_id=" << idx.tablet_id() << " err=" << err
2178
0
                                 << " key=" << hex(current_job_key);
2179
0
                    return -1;
2180
0
                } else {
2181
0
                    TabletJobInfoPB current_job;
2182
0
                    if (!current_job.ParseFromString(current_job_val)) {
2183
0
                        LOG(WARNING) << "failed to parse related job, instance_id=" << instance_id_
2184
0
                                     << " tablet_id=" << idx.tablet_id()
2185
0
                                     << " key=" << hex(current_job_key);
2186
0
                        return -1;
2187
0
                    }
2188
0
                    if (matched_compaction != nullptr) {
2189
0
                        no_job_to_abort = true;
2190
0
                        for (const auto& compaction : current_job.compaction()) {
2191
0
                            if (compaction.id() == job_id) {
2192
0
                                no_job_to_abort = false;
2193
0
                                break;
2194
0
                            }
2195
0
                        }
2196
0
                    } else {
2197
0
                        no_job_to_abort = !current_job.has_schema_change() ||
2198
0
                                          current_job.schema_change().id() != job_id;
2199
0
                    }
2200
0
                }
2201
0
            }
2202
0
            if (no_job_to_abort) {
2203
0
                return 0;
2204
0
            }
2205
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
2206
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
2207
0
                         << " msg=" << msg;
2208
0
            return -1;
2209
0
        }
2210
8
        LOG(WARNING) << "finish abort job for related rowset, job_id=" << job_id
2211
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
2212
8
                     << " code=" << code << " msg=" << msg;
2213
8
    } else {
2214
        // clang-format off
2215
1
        LOG(INFO) << "there is no job for related rowset, recheck recycle rowset before deletion"
2216
1
                  << ", instance_id=" << instance_id_ 
2217
1
                  << ", tablet_id=" << tablet_idx.tablet_id() 
2218
1
                  << ", job_id=" << job_id
2219
1
                  << ", rowset_id=" << rowset_id;
2220
        // clang-format on
2221
1
    }
2222
2223
9
    return 0;
2224
9
}
2225
2226
template <typename T>
2227
22
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2228
22
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2229
13
        return rowset_meta_pb.mutable_rowset_meta();
2230
13
    } else {
2231
9
        return &rowset_meta_pb;
2232
9
    }
2233
22
}
_ZN5doris5cloud19mutable_rowset_metaINS0_15RecycleRowsetPBEEEPNS_17RowsetMetaCloudPBERT_
Line
Count
Source
2227
13
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2228
13
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2229
13
        return rowset_meta_pb.mutable_rowset_meta();
2230
    } else {
2231
        return &rowset_meta_pb;
2232
    }
2233
13
}
_ZN5doris5cloud19mutable_rowset_metaINS_17RowsetMetaCloudPBEEEPS2_RT_
Line
Count
Source
2227
9
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2228
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2229
        return rowset_meta_pb.mutable_rowset_meta();
2230
9
    } else {
2231
9
        return &rowset_meta_pb;
2232
9
    }
2233
9
}
2234
2235
template <typename T>
2236
1.63k
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2237
1.63k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2238
833
        return rowset_meta_pb.rowset_meta();
2239
833
    } else {
2240
799
        return rowset_meta_pb;
2241
799
    }
2242
1.63k
}
_ZN5doris5cloud11rowset_metaINS0_15RecycleRowsetPBEEERKNS_17RowsetMetaCloudPBERKT_
Line
Count
Source
2236
833
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2237
833
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2238
833
        return rowset_meta_pb.rowset_meta();
2239
    } else {
2240
        return rowset_meta_pb;
2241
    }
2242
833
}
_ZN5doris5cloud11rowset_metaINS_17RowsetMetaCloudPBEEERKS2_RKT_
Line
Count
Source
2236
799
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2237
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2238
        return rowset_meta_pb.rowset_meta();
2239
799
    } else {
2240
799
        return rowset_meta_pb;
2241
799
    }
2242
799
}
2243
2244
template <typename T>
2245
std::optional<RelatedTxnOrJobAbortTask> make_related_txn_or_job_abort_task(
2246
1.07k
        const T& rowset_meta_pb) {
2247
1.07k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2248
545
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2249
0
            return std::nullopt;
2250
0
        }
2251
545
    }
2252
2253
545
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2254
1.07k
    RelatedTxnOrJobAbortTask task;
2255
1.07k
    task.tablet_id = rs_meta.tablet_id();
2256
1.07k
    task.start_version = rs_meta.start_version();
2257
1.07k
    task.end_version = rs_meta.end_version();
2258
1.07k
    task.rowset_id = rs_meta.rowset_id_v2();
2259
1.07k
    if (rs_meta.has_load_id()) {
2260
1.05k
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2261
1.05k
        task.txn_id = rs_meta.txn_id();
2262
1.05k
        return task;
2263
1.05k
    }
2264
19
    if (rs_meta.has_job_id()) {
2265
14
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2266
14
        task.job_id = rs_meta.job_id();
2267
14
        return task;
2268
14
    }
2269
5
    return std::nullopt;
2270
19
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2246
545
        const T& rowset_meta_pb) {
2247
545
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2248
545
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2249
0
            return std::nullopt;
2250
0
        }
2251
545
    }
2252
2253
545
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2254
545
    RelatedTxnOrJobAbortTask task;
2255
545
    task.tablet_id = rs_meta.tablet_id();
2256
545
    task.start_version = rs_meta.start_version();
2257
545
    task.end_version = rs_meta.end_version();
2258
545
    task.rowset_id = rs_meta.rowset_id_v2();
2259
545
    if (rs_meta.has_load_id()) {
2260
534
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2261
534
        task.txn_id = rs_meta.txn_id();
2262
534
        return task;
2263
534
    }
2264
11
    if (rs_meta.has_job_id()) {
2265
10
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2266
10
        task.job_id = rs_meta.job_id();
2267
10
        return task;
2268
10
    }
2269
1
    return std::nullopt;
2270
11
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2246
526
        const T& rowset_meta_pb) {
2247
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2248
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2249
            return std::nullopt;
2250
        }
2251
    }
2252
2253
526
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2254
526
    RelatedTxnOrJobAbortTask task;
2255
526
    task.tablet_id = rs_meta.tablet_id();
2256
526
    task.start_version = rs_meta.start_version();
2257
526
    task.end_version = rs_meta.end_version();
2258
526
    task.rowset_id = rs_meta.rowset_id_v2();
2259
526
    if (rs_meta.has_load_id()) {
2260
518
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2261
518
        task.txn_id = rs_meta.txn_id();
2262
518
        return task;
2263
518
    }
2264
8
    if (rs_meta.has_job_id()) {
2265
4
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2266
4
        task.job_id = rs_meta.job_id();
2267
4
        return task;
2268
4
    }
2269
4
    return std::nullopt;
2270
8
}
2271
2272
template <typename T>
2273
bool matches_related_txn_or_job_abort_task(const T& rowset_meta_pb,
2274
529
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2275
529
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2276
268
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2277
0
            return false;
2278
0
        }
2279
268
    }
2280
2281
268
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2282
529
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2283
529
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2284
0
        return false;
2285
0
    }
2286
529
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2287
523
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2288
523
    }
2289
6
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2290
529
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2274
268
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2275
268
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2276
268
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2277
0
            return false;
2278
0
        }
2279
268
    }
2280
2281
268
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2282
268
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2283
268
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2284
0
        return false;
2285
0
    }
2286
268
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2287
264
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2288
264
    }
2289
4
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2290
268
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2274
261
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2275
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2276
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2277
            return false;
2278
        }
2279
    }
2280
2281
261
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2282
261
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2283
261
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2284
0
        return false;
2285
0
    }
2286
261
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2287
259
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2288
259
    }
2289
2
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2290
261
}
2291
2292
71
bool need_mark_rowset_as_recycled(const RowsetMetaCloudPB& rowset_meta_pb) {
2293
71
    return !rowset_meta_pb.has_is_recycled() || !rowset_meta_pb.is_recycled();
2294
71
}
2295
2296
template <typename T>
2297
int batch_mark_rowsets_as_recycled(TxnKv* txn_kv, const std::string& instance_id,
2298
18
                                   const std::vector<std::string>& keys) {
2299
35
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2300
18
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2301
18
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2302
18
        std::unique_ptr<Transaction> txn;
2303
18
        TxnErrorCode err = txn_kv->create_txn(&txn);
2304
18
        if (err != TxnErrorCode::TXN_OK) {
2305
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2306
0
            return -1;
2307
0
        }
2308
18
        std::vector<std::optional<std::string>> values;
2309
18
        err = txn->batch_get(&values, batch_keys);
2310
18
        if (err != TxnErrorCode::TXN_OK) {
2311
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2312
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2313
0
            return -1;
2314
0
        }
2315
18
        DCHECK_EQ(values.size(), batch_keys.size());
2316
40
        for (size_t i = 0; i < batch_keys.size(); i++) {
2317
22
            if (!values[i].has_value()) {
2318
                // has already been removed by commit_rowset
2319
0
                continue;
2320
0
            }
2321
22
            const auto& key = batch_keys[i];
2322
22
            auto val = values[i].value();
2323
22
            T rowset_meta_pb;
2324
22
            if (!rowset_meta_pb.ParseFromString(val)) {
2325
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2326
0
                             << " key=" << hex(key);
2327
0
                return -1;
2328
0
            }
2329
22
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2330
0
                continue;
2331
0
            }
2332
22
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2333
22
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2334
13
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2335
13
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2336
13
            }
2337
22
            val.clear();
2338
22
            rowset_meta_pb.SerializeToString(&val);
2339
22
            txn->put(key, val);
2340
22
        }
2341
18
        err = txn->commit();
2342
18
        if (err != TxnErrorCode::TXN_OK) {
2343
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2344
1
            return -1;
2345
1
        }
2346
18
    }
2347
2348
17
    return 0;
2349
18
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2298
11
                                   const std::vector<std::string>& keys) {
2299
21
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2300
11
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2301
11
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2302
11
        std::unique_ptr<Transaction> txn;
2303
11
        TxnErrorCode err = txn_kv->create_txn(&txn);
2304
11
        if (err != TxnErrorCode::TXN_OK) {
2305
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2306
0
            return -1;
2307
0
        }
2308
11
        std::vector<std::optional<std::string>> values;
2309
11
        err = txn->batch_get(&values, batch_keys);
2310
11
        if (err != TxnErrorCode::TXN_OK) {
2311
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2312
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2313
0
            return -1;
2314
0
        }
2315
11
        DCHECK_EQ(values.size(), batch_keys.size());
2316
24
        for (size_t i = 0; i < batch_keys.size(); i++) {
2317
13
            if (!values[i].has_value()) {
2318
                // has already been removed by commit_rowset
2319
0
                continue;
2320
0
            }
2321
13
            const auto& key = batch_keys[i];
2322
13
            auto val = values[i].value();
2323
13
            T rowset_meta_pb;
2324
13
            if (!rowset_meta_pb.ParseFromString(val)) {
2325
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2326
0
                             << " key=" << hex(key);
2327
0
                return -1;
2328
0
            }
2329
13
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2330
0
                continue;
2331
0
            }
2332
13
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2333
13
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2334
13
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2335
13
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2336
13
            }
2337
13
            val.clear();
2338
13
            rowset_meta_pb.SerializeToString(&val);
2339
13
            txn->put(key, val);
2340
13
        }
2341
11
        err = txn->commit();
2342
11
        if (err != TxnErrorCode::TXN_OK) {
2343
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2344
1
            return -1;
2345
1
        }
2346
11
    }
2347
2348
10
    return 0;
2349
11
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2298
7
                                   const std::vector<std::string>& keys) {
2299
14
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2300
7
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2301
7
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2302
7
        std::unique_ptr<Transaction> txn;
2303
7
        TxnErrorCode err = txn_kv->create_txn(&txn);
2304
7
        if (err != TxnErrorCode::TXN_OK) {
2305
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2306
0
            return -1;
2307
0
        }
2308
7
        std::vector<std::optional<std::string>> values;
2309
7
        err = txn->batch_get(&values, batch_keys);
2310
7
        if (err != TxnErrorCode::TXN_OK) {
2311
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2312
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2313
0
            return -1;
2314
0
        }
2315
7
        DCHECK_EQ(values.size(), batch_keys.size());
2316
16
        for (size_t i = 0; i < batch_keys.size(); i++) {
2317
9
            if (!values[i].has_value()) {
2318
                // has already been removed by commit_rowset
2319
0
                continue;
2320
0
            }
2321
9
            const auto& key = batch_keys[i];
2322
9
            auto val = values[i].value();
2323
9
            T rowset_meta_pb;
2324
9
            if (!rowset_meta_pb.ParseFromString(val)) {
2325
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2326
0
                             << " key=" << hex(key);
2327
0
                return -1;
2328
0
            }
2329
9
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2330
0
                continue;
2331
0
            }
2332
9
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2333
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2334
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2335
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2336
            }
2337
9
            val.clear();
2338
9
            rowset_meta_pb.SerializeToString(&val);
2339
9
            txn->put(key, val);
2340
9
        }
2341
7
        err = txn->commit();
2342
7
        if (err != TxnErrorCode::TXN_OK) {
2343
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2344
0
            return -1;
2345
0
        }
2346
7
    }
2347
2348
7
    return 0;
2349
7
}
2350
2351
template <typename T>
2352
void InstanceRecycler::submit_batch_mark_rowsets_as_recycled_job(
2353
18
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2354
18
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2355
18
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2356
1
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2357
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2358
1
        }
2359
18
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2354
11
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2355
11
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2356
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2357
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2358
1
        }
2359
11
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2354
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2355
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2356
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2357
0
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2358
0
        }
2359
7
    });
2360
18
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2353
11
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2354
11
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2355
11
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2356
11
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2357
11
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2358
11
        }
2359
11
    });
2360
11
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2353
7
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2354
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2355
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2356
7
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2357
7
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2358
7
        }
2359
7
    });
2360
7
}
2361
2362
template <typename T>
2363
int collect_deferred_abort_tasks(TxnKv* txn_kv, const std::string& instance_id,
2364
                                 const std::vector<std::string>& keys,
2365
20
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2366
42
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2367
22
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2368
22
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2369
22
        std::unique_ptr<Transaction> txn;
2370
22
        TxnErrorCode err = txn_kv->create_txn(&txn);
2371
22
        if (err != TxnErrorCode::TXN_OK) {
2372
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2373
0
            return -1;
2374
0
        }
2375
22
        std::vector<std::optional<std::string>> values;
2376
22
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2377
22
        if (err != TxnErrorCode::TXN_OK) {
2378
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2379
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2380
0
            return -1;
2381
0
        }
2382
22
        DCHECK_EQ(values.size(), batch_keys.size());
2383
555
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2384
533
            const std::string& key = batch_keys[idx];
2385
533
            if (!values[idx].has_value()) {
2386
                // has already been removed
2387
0
                continue;
2388
0
            }
2389
533
            T rowset_meta_pb;
2390
533
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2391
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2392
0
                             << " key=" << hex(key);
2393
0
                return -1;
2394
0
            }
2395
533
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2396
533
                abort_task.has_value()) {
2397
533
                abort_task->key = key;
2398
533
                abort_tasks->emplace_back(std::move(*abort_task));
2399
533
            }
2400
533
        }
2401
22
    }
2402
20
    return 0;
2403
20
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2365
15
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2366
31
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2367
16
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2368
16
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2369
16
        std::unique_ptr<Transaction> txn;
2370
16
        TxnErrorCode err = txn_kv->create_txn(&txn);
2371
16
        if (err != TxnErrorCode::TXN_OK) {
2372
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2373
0
            return -1;
2374
0
        }
2375
16
        std::vector<std::optional<std::string>> values;
2376
16
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2377
16
        if (err != TxnErrorCode::TXN_OK) {
2378
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2379
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2380
0
            return -1;
2381
0
        }
2382
16
        DCHECK_EQ(values.size(), batch_keys.size());
2383
288
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2384
272
            const std::string& key = batch_keys[idx];
2385
272
            if (!values[idx].has_value()) {
2386
                // has already been removed
2387
0
                continue;
2388
0
            }
2389
272
            T rowset_meta_pb;
2390
272
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2391
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2392
0
                             << " key=" << hex(key);
2393
0
                return -1;
2394
0
            }
2395
272
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2396
272
                abort_task.has_value()) {
2397
272
                abort_task->key = key;
2398
272
                abort_tasks->emplace_back(std::move(*abort_task));
2399
272
            }
2400
272
        }
2401
16
    }
2402
15
    return 0;
2403
15
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2365
5
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2366
11
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2367
6
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2368
6
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2369
6
        std::unique_ptr<Transaction> txn;
2370
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2371
6
        if (err != TxnErrorCode::TXN_OK) {
2372
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2373
0
            return -1;
2374
0
        }
2375
6
        std::vector<std::optional<std::string>> values;
2376
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2377
6
        if (err != TxnErrorCode::TXN_OK) {
2378
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2379
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2380
0
            return -1;
2381
0
        }
2382
6
        DCHECK_EQ(values.size(), batch_keys.size());
2383
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2384
261
            const std::string& key = batch_keys[idx];
2385
261
            if (!values[idx].has_value()) {
2386
                // has already been removed
2387
0
                continue;
2388
0
            }
2389
261
            T rowset_meta_pb;
2390
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2391
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2392
0
                             << " key=" << hex(key);
2393
0
                return -1;
2394
0
            }
2395
261
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2396
261
                abort_task.has_value()) {
2397
261
                abort_task->key = key;
2398
261
                abort_tasks->emplace_back(std::move(*abort_task));
2399
261
            }
2400
261
        }
2401
6
    }
2402
5
    return 0;
2403
5
}
2404
2405
template <typename T>
2406
int batch_recheck_rowsets_after_abort(
2407
        TxnKv* txn_kv, const std::string& instance_id,
2408
        const std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck,
2409
18
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2410
18
    int ret = 0;
2411
38
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2412
20
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2413
20
        std::vector<std::string> batch_keys;
2414
20
        batch_keys.reserve(limit - offset);
2415
550
        for (size_t idx = offset; idx < limit; ++idx) {
2416
530
            batch_keys.push_back(keys_to_recheck[idx].first);
2417
530
        }
2418
2419
20
        std::unique_ptr<Transaction> txn;
2420
20
        TxnErrorCode err = txn_kv->create_txn(&txn);
2421
20
        if (err != TxnErrorCode::TXN_OK) {
2422
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2423
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2424
0
            ret = -1;
2425
0
            continue;
2426
0
        }
2427
2428
20
        std::vector<std::optional<std::string>> values;
2429
20
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2430
20
        if (err != TxnErrorCode::TXN_OK) {
2431
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2432
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2433
0
            ret = -1;
2434
0
            continue;
2435
0
        }
2436
20
        DCHECK_EQ(values.size(), batch_keys.size());
2437
20
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2438
20
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2439
20
                                 &batch_size);
2440
2441
550
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2442
530
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2443
530
            if (!values[idx].has_value()) {
2444
1
                continue;
2445
1
            }
2446
2447
529
            T rowset_meta_pb;
2448
529
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2449
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2450
0
                             << instance_id << " key=" << hex(key);
2451
0
                ret = -1;
2452
0
                continue;
2453
0
            }
2454
529
            if (config::enable_mark_delete_rowset_before_recycle &&
2455
529
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2456
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2457
0
                             << instance_id << " key=" << hex(key);
2458
0
                continue;
2459
0
            }
2460
529
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2461
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2462
1
                             << instance_id << " key=" << hex(key);
2463
1
                continue;
2464
1
            }
2465
528
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2466
528
        }
2467
20
    }
2468
18
    return ret;
2469
18
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2409
13
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2410
13
    int ret = 0;
2411
27
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2412
14
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2413
14
        std::vector<std::string> batch_keys;
2414
14
        batch_keys.reserve(limit - offset);
2415
283
        for (size_t idx = offset; idx < limit; ++idx) {
2416
269
            batch_keys.push_back(keys_to_recheck[idx].first);
2417
269
        }
2418
2419
14
        std::unique_ptr<Transaction> txn;
2420
14
        TxnErrorCode err = txn_kv->create_txn(&txn);
2421
14
        if (err != TxnErrorCode::TXN_OK) {
2422
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2423
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2424
0
            ret = -1;
2425
0
            continue;
2426
0
        }
2427
2428
14
        std::vector<std::optional<std::string>> values;
2429
14
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2430
14
        if (err != TxnErrorCode::TXN_OK) {
2431
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2432
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2433
0
            ret = -1;
2434
0
            continue;
2435
0
        }
2436
14
        DCHECK_EQ(values.size(), batch_keys.size());
2437
14
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2438
14
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2439
14
                                 &batch_size);
2440
2441
283
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2442
269
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2443
269
            if (!values[idx].has_value()) {
2444
1
                continue;
2445
1
            }
2446
2447
268
            T rowset_meta_pb;
2448
268
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2449
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2450
0
                             << instance_id << " key=" << hex(key);
2451
0
                ret = -1;
2452
0
                continue;
2453
0
            }
2454
268
            if (config::enable_mark_delete_rowset_before_recycle &&
2455
268
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2456
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2457
0
                             << instance_id << " key=" << hex(key);
2458
0
                continue;
2459
0
            }
2460
268
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2461
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2462
1
                             << instance_id << " key=" << hex(key);
2463
1
                continue;
2464
1
            }
2465
267
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2466
267
        }
2467
14
    }
2468
13
    return ret;
2469
13
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2409
5
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2410
5
    int ret = 0;
2411
11
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2412
6
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2413
6
        std::vector<std::string> batch_keys;
2414
6
        batch_keys.reserve(limit - offset);
2415
267
        for (size_t idx = offset; idx < limit; ++idx) {
2416
261
            batch_keys.push_back(keys_to_recheck[idx].first);
2417
261
        }
2418
2419
6
        std::unique_ptr<Transaction> txn;
2420
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2421
6
        if (err != TxnErrorCode::TXN_OK) {
2422
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2423
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2424
0
            ret = -1;
2425
0
            continue;
2426
0
        }
2427
2428
6
        std::vector<std::optional<std::string>> values;
2429
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2430
6
        if (err != TxnErrorCode::TXN_OK) {
2431
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2432
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2433
0
            ret = -1;
2434
0
            continue;
2435
0
        }
2436
6
        DCHECK_EQ(values.size(), batch_keys.size());
2437
6
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2438
6
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2439
6
                                 &batch_size);
2440
2441
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2442
261
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2443
261
            if (!values[idx].has_value()) {
2444
0
                continue;
2445
0
            }
2446
2447
261
            T rowset_meta_pb;
2448
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2449
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2450
0
                             << instance_id << " key=" << hex(key);
2451
0
                ret = -1;
2452
0
                continue;
2453
0
            }
2454
261
            if (config::enable_mark_delete_rowset_before_recycle &&
2455
261
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2456
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2457
0
                             << instance_id << " key=" << hex(key);
2458
0
                continue;
2459
0
            }
2460
261
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2461
0
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2462
0
                             << instance_id << " key=" << hex(key);
2463
0
                continue;
2464
0
            }
2465
261
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2466
261
        }
2467
6
    }
2468
5
    return ret;
2469
5
}
2470
2471
template <typename T>
2472
int InstanceRecycler::batch_abort_txn_or_job_for_recycle(
2473
        const std::vector<std::string>& keys,
2474
20
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2475
20
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2476
20
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2477
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2478
0
        return -1;
2479
0
    }
2480
20
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2481
20
    int ret = 0;
2482
533
    for (const auto& abort_task : abort_tasks) {
2483
533
        int abort_ret = 0;
2484
533
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2485
526
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2486
526
        } else {
2487
7
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2488
7
                                                     abort_task.job_id);
2489
7
        }
2490
533
        if (abort_ret != 0) {
2491
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2492
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2493
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2494
3
            ret = abort_ret;
2495
3
            continue;
2496
3
        }
2497
530
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2498
530
    }
2499
20
    return ret;
2500
20
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2474
15
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2475
15
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2476
15
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2477
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2478
0
        return -1;
2479
0
    }
2480
15
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2481
15
    int ret = 0;
2482
272
    for (const auto& abort_task : abort_tasks) {
2483
272
        int abort_ret = 0;
2484
272
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2485
267
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2486
267
        } else {
2487
5
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2488
5
                                                     abort_task.job_id);
2489
5
        }
2490
272
        if (abort_ret != 0) {
2491
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2492
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2493
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2494
3
            ret = abort_ret;
2495
3
            continue;
2496
3
        }
2497
269
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2498
269
    }
2499
15
    return ret;
2500
15
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2474
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2475
5
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2476
5
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2477
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2478
0
        return -1;
2479
0
    }
2480
5
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2481
5
    int ret = 0;
2482
261
    for (const auto& abort_task : abort_tasks) {
2483
261
        int abort_ret = 0;
2484
261
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2485
259
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2486
259
        } else {
2487
2
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2488
2
                                                     abort_task.job_id);
2489
2
        }
2490
261
        if (abort_ret != 0) {
2491
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2492
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2493
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2494
0
            ret = abort_ret;
2495
0
            continue;
2496
0
        }
2497
261
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2498
261
    }
2499
5
    return ret;
2500
5
}
2501
2502
void InstanceRecycler::submit_recycle_prepare_rowsets_job(
2503
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_abort,
2504
15
        std::atomic_long* num_recycled) {
2505
15
    int ret = worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort),
2506
15
                                  num_recycled]() mutable {
2507
15
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2508
15
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2509
15
                                                                            keys_to_recheck);
2510
15
        if (abort_ret != 0) {
2511
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2512
2
                            "instance_id="
2513
2
                         << instance_id_;
2514
2
        }
2515
15
        if (keys_to_recheck.empty()) {
2516
2
            return;
2517
2
        }
2518
2519
13
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2520
13
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2521
13
                                                            keys_to_recheck, &rowsets_to_recycle);
2522
13
        if (recheck_ret != 0) {
2523
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2524
0
                         << instance_id_;
2525
0
        }
2526
267
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2527
267
            const auto& current_meta = current_rowset.rowset_meta();
2528
267
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2529
267
                                   current_meta.rowset_id_v2()) != 0) {
2530
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2531
1
                continue;
2532
1
            }
2533
266
            if (delete_versioned_delete_bitmap_kvs(current_meta.tablet_id(),
2534
266
                                                   current_meta.rowset_id_v2()) != 0) {
2535
0
                continue;
2536
0
            }
2537
266
            std::vector<std::string> keys {key};
2538
266
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2539
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2540
0
                continue;
2541
0
            }
2542
266
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2543
266
        }
2544
13
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEEN3$_0clEv
Line
Count
Source
2506
2
                                  num_recycled]() mutable {
2507
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2508
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2509
2
                                                                            keys_to_recheck);
2510
2
        if (abort_ret != 0) {
2511
0
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2512
0
                            "instance_id="
2513
0
                         << instance_id_;
2514
0
        }
2515
2
        if (keys_to_recheck.empty()) {
2516
0
            return;
2517
0
        }
2518
2519
2
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2520
2
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2521
2
                                                            keys_to_recheck, &rowsets_to_recycle);
2522
2
        if (recheck_ret != 0) {
2523
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2524
0
                         << instance_id_;
2525
0
        }
2526
2
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2527
2
            const auto& current_meta = current_rowset.rowset_meta();
2528
2
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2529
2
                                   current_meta.rowset_id_v2()) != 0) {
2530
0
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2531
0
                continue;
2532
0
            }
2533
2
            if (delete_versioned_delete_bitmap_kvs(current_meta.tablet_id(),
2534
2
                                                   current_meta.rowset_id_v2()) != 0) {
2535
0
                continue;
2536
0
            }
2537
2
            std::vector<std::string> keys {key};
2538
2
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2539
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2540
0
                continue;
2541
0
            }
2542
2
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2543
2
        }
2544
2
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEEN3$_0clEv
Line
Count
Source
2506
13
                                  num_recycled]() mutable {
2507
13
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2508
13
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2509
13
                                                                            keys_to_recheck);
2510
13
        if (abort_ret != 0) {
2511
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2512
2
                            "instance_id="
2513
2
                         << instance_id_;
2514
2
        }
2515
13
        if (keys_to_recheck.empty()) {
2516
2
            return;
2517
2
        }
2518
2519
11
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2520
11
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2521
11
                                                            keys_to_recheck, &rowsets_to_recycle);
2522
11
        if (recheck_ret != 0) {
2523
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2524
0
                         << instance_id_;
2525
0
        }
2526
265
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2527
265
            const auto& current_meta = current_rowset.rowset_meta();
2528
265
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2529
265
                                   current_meta.rowset_id_v2()) != 0) {
2530
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2531
1
                continue;
2532
1
            }
2533
264
            if (delete_versioned_delete_bitmap_kvs(current_meta.tablet_id(),
2534
264
                                                   current_meta.rowset_id_v2()) != 0) {
2535
0
                continue;
2536
0
            }
2537
264
            std::vector<std::string> keys {key};
2538
264
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2539
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2540
0
                continue;
2541
0
            }
2542
264
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2543
264
        }
2544
11
    });
2545
15
    if (ret != 0) {
2546
0
        LOG(WARNING) << "failed to submit recycle prepare rowset job, instance_id=" << instance_id_;
2547
0
    }
2548
15
}
2549
2550
void InstanceRecycler::submit_recycle_tmp_rowsets_job(SimpleThreadPool& worker_pool,
2551
                                                      std::vector<std::string> rowset_keys_to_abort,
2552
                                                      std::atomic_long* num_recycled,
2553
5
                                                      RecyclerMetricsContext* metrics_context) {
2554
5
    if (rowset_keys_to_abort.empty()) {
2555
0
        return;
2556
0
    }
2557
5
    worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort), num_recycled,
2558
5
                        metrics_context]() mutable {
2559
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2560
5
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2561
5
                rowset_keys_to_abort, abort_keys_to_recheck);
2562
5
        if (abort_ret != 0) {
2563
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2564
0
                            "instance_id="
2565
0
                         << instance_id_;
2566
0
        }
2567
2568
5
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2569
5
        std::vector<std::string> keys_to_delete;
2570
5
        std::vector<std::string> ref_count_keys_to_delete;
2571
5
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2572
5
        int recheck_ret = batch_recheck_rowsets_after_abort(
2573
5
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2574
5
        if (recheck_ret != 0) {
2575
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2576
0
                         << instance_id_;
2577
0
        }
2578
261
        for (auto& [key, rowset] : rowsets_to_recycle) {
2579
261
            keys_to_delete.push_back(key);
2580
261
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2581
261
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2582
261
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2583
261
        }
2584
2585
5
        if (keys_to_delete.empty()) {
2586
0
            return;
2587
0
        }
2588
5
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2589
5
                               *metrics_context) != 0) {
2590
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2591
0
            return;
2592
0
        }
2593
261
        for (const auto& [_, rowset] : rowsets_to_delete) {
2594
261
            if (delete_versioned_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) !=
2595
261
                0) {
2596
0
                return;
2597
0
            }
2598
261
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2599
0
                return;
2600
0
            }
2601
261
        }
2602
5
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2603
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2604
0
            return;
2605
0
        }
2606
5
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2607
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2608
0
                         << instance_id_;
2609
0
            return;
2610
0
        }
2611
5
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2612
5
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2558
3
                        metrics_context]() mutable {
2559
3
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2560
3
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2561
3
                rowset_keys_to_abort, abort_keys_to_recheck);
2562
3
        if (abort_ret != 0) {
2563
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2564
0
                            "instance_id="
2565
0
                         << instance_id_;
2566
0
        }
2567
2568
3
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2569
3
        std::vector<std::string> keys_to_delete;
2570
3
        std::vector<std::string> ref_count_keys_to_delete;
2571
3
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2572
3
        int recheck_ret = batch_recheck_rowsets_after_abort(
2573
3
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2574
3
        if (recheck_ret != 0) {
2575
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2576
0
                         << instance_id_;
2577
0
        }
2578
3
        for (auto& [key, rowset] : rowsets_to_recycle) {
2579
3
            keys_to_delete.push_back(key);
2580
3
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2581
3
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2582
3
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2583
3
        }
2584
2585
3
        if (keys_to_delete.empty()) {
2586
0
            return;
2587
0
        }
2588
3
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2589
3
                               *metrics_context) != 0) {
2590
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2591
0
            return;
2592
0
        }
2593
3
        for (const auto& [_, rowset] : rowsets_to_delete) {
2594
3
            if (delete_versioned_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) !=
2595
3
                0) {
2596
0
                return;
2597
0
            }
2598
3
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2599
0
                return;
2600
0
            }
2601
3
        }
2602
3
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2603
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2604
0
            return;
2605
0
        }
2606
3
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2607
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2608
0
                         << instance_id_;
2609
0
            return;
2610
0
        }
2611
3
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2612
3
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2558
2
                        metrics_context]() mutable {
2559
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2560
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2561
2
                rowset_keys_to_abort, abort_keys_to_recheck);
2562
2
        if (abort_ret != 0) {
2563
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2564
0
                            "instance_id="
2565
0
                         << instance_id_;
2566
0
        }
2567
2568
2
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2569
2
        std::vector<std::string> keys_to_delete;
2570
2
        std::vector<std::string> ref_count_keys_to_delete;
2571
2
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2572
2
        int recheck_ret = batch_recheck_rowsets_after_abort(
2573
2
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2574
2
        if (recheck_ret != 0) {
2575
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2576
0
                         << instance_id_;
2577
0
        }
2578
258
        for (auto& [key, rowset] : rowsets_to_recycle) {
2579
258
            keys_to_delete.push_back(key);
2580
258
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2581
258
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2582
258
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2583
258
        }
2584
2585
2
        if (keys_to_delete.empty()) {
2586
0
            return;
2587
0
        }
2588
2
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2589
2
                               *metrics_context) != 0) {
2590
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2591
0
            return;
2592
0
        }
2593
258
        for (const auto& [_, rowset] : rowsets_to_delete) {
2594
258
            if (delete_versioned_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) !=
2595
258
                0) {
2596
0
                return;
2597
0
            }
2598
258
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2599
0
                return;
2600
0
            }
2601
258
        }
2602
2
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2603
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2604
0
            return;
2605
0
        }
2606
2
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2607
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2608
0
                         << instance_id_;
2609
0
            return;
2610
0
        }
2611
2
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2612
2
    });
2613
5
}
2614
2615
1
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
2616
1
    const std::string task_name = "recycle_ref_rowsets";
2617
1
    *has_unrecycled_rowsets = false;
2618
2619
1
    std::string data_rowset_ref_count_key_start =
2620
1
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
2621
1
    std::string data_rowset_ref_count_key_end =
2622
1
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
2623
2624
1
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
2625
2626
1
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2627
1
    register_recycle_task(task_name, start_time);
2628
2629
1
    DORIS_CLOUD_DEFER {
2630
1
        unregister_recycle_task(task_name);
2631
1
        int64_t cost =
2632
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2633
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2634
1
                .tag("instance_id", instance_id_);
2635
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Line
Count
Source
2629
1
    DORIS_CLOUD_DEFER {
2630
1
        unregister_recycle_task(task_name);
2631
1
        int64_t cost =
2632
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2633
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2634
1
                .tag("instance_id", instance_id_);
2635
1
    };
2636
2637
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
2638
1
    std::set<int64_t> tablets_with_refs;
2639
1
    int64_t num_scanned = 0;
2640
2641
1
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
2642
0
        ++num_scanned;
2643
0
        int64_t tablet_id;
2644
0
        std::string rowset_id;
2645
0
        std::string_view key(k);
2646
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
2647
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
2648
0
            return 0; // Continue scanning
2649
0
        }
2650
2651
0
        tablets_with_refs.insert(tablet_id);
2652
0
        return 0;
2653
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
2654
2655
1
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
2656
1
                         std::move(scan_func)) != 0) {
2657
0
        LOG_WARNING("failed to scan data rowset ref count keys");
2658
0
        return -1;
2659
0
    }
2660
2661
1
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
2662
1
             tablets_with_refs.size(), num_scanned)
2663
1
            .tag("instance_id", instance_id_);
2664
2665
    // Phase 2: Recycle each tablet
2666
1
    int64_t num_recycled_tablets = 0;
2667
1
    for (int64_t tablet_id : tablets_with_refs) {
2668
0
        if (stopped()) {
2669
0
            LOG_INFO("recycler stopped, skip remaining tablets")
2670
0
                    .tag("instance_id", instance_id_)
2671
0
                    .tag("tablets_processed", num_recycled_tablets)
2672
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
2673
0
            break;
2674
0
        }
2675
2676
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
2677
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
2678
0
            LOG_WARNING("failed to recycle tablet")
2679
0
                    .tag("instance_id", instance_id_)
2680
0
                    .tag("tablet_id", tablet_id);
2681
0
            return -1;
2682
0
        }
2683
0
        ++num_recycled_tablets;
2684
0
    }
2685
2686
1
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
2687
1
            .tag("instance_id", instance_id_)
2688
1
            .tag("total_tablets", tablets_with_refs.size());
2689
2690
    // Phase 3: Scan again to check if any ref count keys still exist
2691
1
    std::unique_ptr<Transaction> txn;
2692
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2693
1
    if (err != TxnErrorCode::TXN_OK) {
2694
0
        LOG_WARNING("failed to create txn for final check")
2695
0
                .tag("instance_id", instance_id_)
2696
0
                .tag("err", err);
2697
0
        return -1;
2698
0
    }
2699
2700
1
    std::unique_ptr<RangeGetIterator> iter;
2701
1
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2702
1
    if (err != TxnErrorCode::TXN_OK) {
2703
0
        LOG_WARNING("failed to create range iterator for final check")
2704
0
                .tag("instance_id", instance_id_)
2705
0
                .tag("err", err);
2706
0
        return -1;
2707
0
    }
2708
2709
1
    *has_unrecycled_rowsets = iter->has_next();
2710
1
    if (*has_unrecycled_rowsets) {
2711
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2712
0
                .tag("instance_id", instance_id_);
2713
0
    }
2714
2715
1
    return 0;
2716
1
}
2717
2718
int InstanceRecycler::recycle_table_stream_offset_prefix(std::string prefix,
2719
6
                                                         RecyclerMetricsContext* metrics_context) {
2720
6
    std::string end = prefix;
2721
6
    end.push_back('\xff');
2722
6
    std::vector<std::string_view> keys;
2723
8
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2724
8
        keys.push_back(key);
2725
8
        return 0;
2726
8
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_1clESt17basic_string_viewIcS5_ESC_
Line
Count
Source
2723
2
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2724
2
        keys.push_back(key);
2725
2
        return 0;
2726
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_1clESt17basic_string_viewIcS5_ESC_
Line
Count
Source
2723
6
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2724
6
        keys.push_back(key);
2725
6
        return 0;
2726
6
    };
2727
6
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2728
4
        if (keys.empty()) {
2729
0
            return 0;
2730
0
        }
2731
4
        DORIS_CLOUD_DEFER {
2732
4
            keys.clear();
2733
4
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlvE_clEv
Line
Count
Source
2731
2
        DORIS_CLOUD_DEFER {
2732
2
            keys.clear();
2733
2
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlvE_clEv
Line
Count
Source
2731
2
        DORIS_CLOUD_DEFER {
2732
2
            keys.clear();
2733
2
        };
2734
4
        const size_t num_keys = keys.size();
2735
4
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2736
0
            LOG_WARNING("failed to delete table stream offsets")
2737
0
                    .tag("instance_id", instance_id_)
2738
0
                    .tag("num_keys", num_keys);
2739
0
            return -1;
2740
0
        }
2741
4
        metrics_context->total_recycled_num += num_keys;
2742
4
        metrics_context->report();
2743
4
        return 0;
2744
4
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2727
2
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2728
2
        if (keys.empty()) {
2729
0
            return 0;
2730
0
        }
2731
2
        DORIS_CLOUD_DEFER {
2732
2
            keys.clear();
2733
2
        };
2734
2
        const size_t num_keys = keys.size();
2735
2
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2736
0
            LOG_WARNING("failed to delete table stream offsets")
2737
0
                    .tag("instance_id", instance_id_)
2738
0
                    .tag("num_keys", num_keys);
2739
0
            return -1;
2740
0
        }
2741
2
        metrics_context->total_recycled_num += num_keys;
2742
2
        metrics_context->report();
2743
2
        return 0;
2744
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2727
2
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2728
2
        if (keys.empty()) {
2729
0
            return 0;
2730
0
        }
2731
2
        DORIS_CLOUD_DEFER {
2732
2
            keys.clear();
2733
2
        };
2734
2
        const size_t num_keys = keys.size();
2735
2
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2736
0
            LOG_WARNING("failed to delete table stream offsets")
2737
0
                    .tag("instance_id", instance_id_)
2738
0
                    .tag("num_keys", num_keys);
2739
0
            return -1;
2740
0
        }
2741
2
        metrics_context->total_recycled_num += num_keys;
2742
2
        metrics_context->report();
2743
2
        return 0;
2744
2
    };
2745
6
    return scan_and_recycle(std::move(prefix), end, std::move(collect_key), std::move(remove_keys));
2746
6
}
2747
2748
int InstanceRecycler::finalize_recycle_stream(int64_t stream_id,
2749
                                              const RecycleIndexPB& recycle_index,
2750
3
                                              std::string_view recycle_key) {
2751
3
    std::unique_ptr<Transaction> txn;
2752
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2753
3
    if (err != TxnErrorCode::TXN_OK) {
2754
0
        LOG_WARNING("failed to create transaction for final table stream cleanup")
2755
0
                .tag("instance_id", instance_id_)
2756
0
                .tag("stream_id", stream_id)
2757
0
                .tag("err", err);
2758
0
        return -1;
2759
0
    }
2760
2761
3
    std::string current_recycle_value;
2762
3
    err = txn->get(recycle_key, &current_recycle_value);
2763
3
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2764
0
        return 0;
2765
0
    }
2766
3
    if (err != TxnErrorCode::TXN_OK) {
2767
0
        LOG_WARNING("failed to read table stream recycle index")
2768
0
                .tag("instance_id", instance_id_)
2769
0
                .tag("stream_id", stream_id)
2770
0
                .tag("err", err);
2771
0
        return -1;
2772
0
    }
2773
3
    RecycleIndexPB current_recycle_index;
2774
3
    if (!current_recycle_index.ParseFromString(current_recycle_value) ||
2775
3
        current_recycle_index.state() != RecycleIndexPB::RECYCLING ||
2776
3
        current_recycle_index.object_type() != IndexObjectTypePB::TABLE_STREAM ||
2777
3
        current_recycle_index.db_id() != recycle_index.db_id() ||
2778
3
        current_recycle_index.table_id() != recycle_index.table_id() ||
2779
3
        current_recycle_index.stream_db_id() != recycle_index.stream_db_id()) {
2780
0
        LOG_WARNING("table stream recycle index changed during recycling")
2781
0
                .tag("instance_id", instance_id_)
2782
0
                .tag("stream_id", stream_id);
2783
0
        return -1;
2784
0
    }
2785
2786
3
    txn->remove(recycle_key);
2787
3
    err = txn->commit();
2788
3
    if (err != TxnErrorCode::TXN_OK) {
2789
0
        LOG_WARNING("failed to commit final table stream cleanup")
2790
0
                .tag("instance_id", instance_id_)
2791
0
                .tag("stream_id", stream_id)
2792
0
                .tag("err", err);
2793
0
        return -1;
2794
0
    }
2795
3
    return 0;
2796
3
}
2797
2798
int InstanceRecycler::recycle_stream(int64_t stream_id, const RecycleIndexPB& recycle_index,
2799
3
                                     std::string_view recycle_key) {
2800
3
    if (!recycle_index.has_db_id() || !recycle_index.has_stream_db_id()) {
2801
0
        LOG_WARNING("table stream recycle index is missing binding")
2802
0
                .tag("instance_id", instance_id_)
2803
0
                .tag("stream_id", stream_id);
2804
0
        return -1;
2805
0
    }
2806
2807
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stream");
2808
3
    DORIS_CLOUD_DEFER {
2809
3
        metrics_context.finish_report();
2810
3
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_streamElRKNS0_14RecycleIndexPBESt17basic_string_viewIcSt11char_traitsIcEEENK3$_0clEv
Line
Count
Source
2808
2
    DORIS_CLOUD_DEFER {
2809
2
        metrics_context.finish_report();
2810
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_streamElRKNS0_14RecycleIndexPBESt17basic_string_viewIcSt11char_traitsIcEEENK3$_0clEv
Line
Count
Source
2808
1
    DORIS_CLOUD_DEFER {
2809
1
        metrics_context.finish_report();
2810
1
    };
2811
3
    const std::string latest_offset_prefix = table_stream_offset_key_prefix(
2812
3
            instance_id_, recycle_index.db_id(), recycle_index.table_id(),
2813
3
            recycle_index.stream_db_id(), stream_id);
2814
3
    if (recycle_table_stream_offset_prefix(latest_offset_prefix, &metrics_context) != 0) {
2815
0
        return -1;
2816
0
    }
2817
3
    const std::string versioned_offset_prefix = versioned::table_stream_offset_key_prefix(
2818
3
            instance_id_, recycle_index.db_id(), recycle_index.table_id(),
2819
3
            recycle_index.stream_db_id(), stream_id);
2820
3
    if (recycle_table_stream_offset_prefix(versioned_offset_prefix, &metrics_context) != 0 ||
2821
3
        stopped()) {
2822
0
        return -1;
2823
0
    }
2824
3
    return finalize_recycle_stream(stream_id, recycle_index, recycle_key);
2825
3
}
2826
2827
int InstanceRecycler::recycle_partition_table_stream_offsets(
2828
        int64_t db_id, int64_t table_id, int64_t partition_id,
2829
10
        const google::protobuf::RepeatedPtrField<TableStreamIdentityPB>& table_streams) {
2830
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stream_partition_offsets");
2831
10
    DORIS_CLOUD_DEFER {
2832
10
        metrics_context.finish_report();
2833
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler38recycle_partition_table_stream_offsetsElllRKN6google8protobuf16RepeatedPtrFieldINS0_21TableStreamIdentityPBEEEENK3$_0clEv
Line
Count
Source
2831
1
    DORIS_CLOUD_DEFER {
2832
1
        metrics_context.finish_report();
2833
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler38recycle_partition_table_stream_offsetsElllRKN6google8protobuf16RepeatedPtrFieldINS0_21TableStreamIdentityPBEEEENK3$_0clEv
Line
Count
Source
2831
9
    DORIS_CLOUD_DEFER {
2832
9
        metrics_context.finish_report();
2833
9
    };
2834
10
    const size_t batch_size = std::max(1, config::recycler_max_tasks_per_batch);
2835
12
    for (size_t begin_index = 0; begin_index < table_streams.size(); begin_index += batch_size) {
2836
2
        const size_t end_index =
2837
2
                std::min(static_cast<size_t>(table_streams.size()), begin_index + batch_size);
2838
2
        std::unique_ptr<Transaction> txn;
2839
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2840
2
        if (err != TxnErrorCode::TXN_OK) {
2841
0
            LOG_WARNING("failed to create transaction for partition stream offset cleanup")
2842
0
                    .tag("instance_id", instance_id_)
2843
0
                    .tag("partition_id", partition_id)
2844
0
                    .tag("err", err);
2845
0
            return -1;
2846
0
        }
2847
4
        for (size_t i = begin_index; i < end_index; ++i) {
2848
2
            const TableStreamIdentityPB& stream = table_streams.Get(i);
2849
2
            if (stream.base_db_id() != db_id || stream.base_table_id() != table_id ||
2850
2
                stream.stream_db_id() <= 0 || stream.stream_id() <= 0) {
2851
0
                LOG_WARNING("invalid table stream binding in recycle partition")
2852
0
                        .tag("instance_id", instance_id_)
2853
0
                        .tag("partition_id", partition_id)
2854
0
                        .tag("stream_id", stream.stream_id());
2855
0
                return -1;
2856
0
            }
2857
2
            txn->remove(table_stream_offset_key({instance_id_, stream.base_db_id(),
2858
2
                                                 stream.base_table_id(), stream.stream_db_id(),
2859
2
                                                 stream.stream_id(), partition_id}));
2860
2
            versioned_remove_all(
2861
2
                    txn.get(), versioned::table_stream_offset_key(
2862
2
                                       {instance_id_, stream.base_db_id(), stream.base_table_id(),
2863
2
                                        stream.stream_db_id(), stream.stream_id(), partition_id}));
2864
2
        }
2865
2
        err = txn->commit();
2866
2
        if (err != TxnErrorCode::TXN_OK) {
2867
0
            LOG_WARNING("failed to commit partition stream offset cleanup")
2868
0
                    .tag("instance_id", instance_id_)
2869
0
                    .tag("partition_id", partition_id)
2870
0
                    .tag("err", err);
2871
0
            return -1;
2872
0
        }
2873
2
        metrics_context.total_recycled_num += end_index - begin_index;
2874
2
        metrics_context.report();
2875
2
    }
2876
10
    return 0;
2877
10
}
2878
2879
19
int InstanceRecycler::recycle_indexes() {
2880
19
    const std::string task_name = "recycle_indexes";
2881
19
    int64_t num_scanned = 0;
2882
19
    int64_t num_expired = 0;
2883
19
    int64_t num_recycled = 0;
2884
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2885
2886
19
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2887
19
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2888
19
    std::string index_key0;
2889
19
    std::string index_key1;
2890
19
    recycle_index_key(index_key_info0, &index_key0);
2891
19
    recycle_index_key(index_key_info1, &index_key1);
2892
2893
19
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2894
2895
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2896
19
    register_recycle_task(task_name, start_time);
2897
2898
19
    DORIS_CLOUD_DEFER {
2899
19
        unregister_recycle_task(task_name);
2900
19
        int64_t cost =
2901
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2902
19
        metrics_context.finish_report();
2903
19
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2904
19
                .tag("instance_id", instance_id_)
2905
19
                .tag("num_scanned", num_scanned)
2906
19
                .tag("num_expired", num_expired)
2907
19
                .tag("num_recycled", num_recycled);
2908
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2898
3
    DORIS_CLOUD_DEFER {
2899
3
        unregister_recycle_task(task_name);
2900
3
        int64_t cost =
2901
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2902
3
        metrics_context.finish_report();
2903
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2904
3
                .tag("instance_id", instance_id_)
2905
3
                .tag("num_scanned", num_scanned)
2906
3
                .tag("num_expired", num_expired)
2907
3
                .tag("num_recycled", num_recycled);
2908
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2898
16
    DORIS_CLOUD_DEFER {
2899
16
        unregister_recycle_task(task_name);
2900
16
        int64_t cost =
2901
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2902
16
        metrics_context.finish_report();
2903
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2904
16
                .tag("instance_id", instance_id_)
2905
16
                .tag("num_scanned", num_scanned)
2906
16
                .tag("num_expired", num_expired)
2907
16
                .tag("num_recycled", num_recycled);
2908
16
    };
2909
2910
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2911
2912
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2913
19
    std::vector<std::string_view> index_keys;
2914
19
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2915
13
        ++num_scanned;
2916
13
        RecycleIndexPB index_pb;
2917
13
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2918
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2919
0
            return -1;
2920
0
        }
2921
13
        int64_t current_time = ::time(nullptr);
2922
13
        if (current_time <
2923
13
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2924
0
            return 0;
2925
0
        }
2926
13
        ++num_expired;
2927
        // decode index_id
2928
13
        auto k1 = k;
2929
13
        k1.remove_prefix(1);
2930
13
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2931
13
        decode_key(&k1, &out);
2932
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2933
13
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2934
13
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2935
13
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2936
13
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2937
        // Change state to RECYCLING
2938
13
        std::unique_ptr<Transaction> txn;
2939
13
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2940
13
        if (err != TxnErrorCode::TXN_OK) {
2941
0
            LOG_WARNING("failed to create txn").tag("err", err);
2942
0
            return -1;
2943
0
        }
2944
13
        std::string val;
2945
13
        err = txn->get(k, &val);
2946
13
        if (err ==
2947
13
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2948
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2949
0
            return 0;
2950
0
        }
2951
13
        if (err != TxnErrorCode::TXN_OK) {
2952
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2953
0
            return -1;
2954
0
        }
2955
13
        index_pb.Clear();
2956
13
        if (!index_pb.ParseFromString(val)) {
2957
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2958
0
            return -1;
2959
0
        }
2960
13
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2961
12
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2962
12
            txn->put(k, index_pb.SerializeAsString());
2963
12
            err = txn->commit();
2964
12
            if (err != TxnErrorCode::TXN_OK) {
2965
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2966
0
                return -1;
2967
0
            }
2968
12
        }
2969
13
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
2970
3
            if (recycle_stream(index_id, index_pb, k) != 0) {
2971
0
                LOG_WARNING("failed to recycle table stream")
2972
0
                        .tag("instance_id", instance_id_)
2973
0
                        .tag("stream_id", index_id);
2974
0
                return -1;
2975
0
            }
2976
3
            metrics_context.total_recycled_num = ++num_recycled;
2977
3
            metrics_context.report();
2978
3
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2979
3
            return 0;
2980
3
        }
2981
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2982
1
            LOG_WARNING("failed to recycle tablets under index")
2983
1
                    .tag("table_id", index_pb.table_id())
2984
1
                    .tag("instance_id", instance_id_)
2985
1
                    .tag("index_id", index_id);
2986
1
            return -1;
2987
1
        }
2988
2989
9
        if (index_pb.has_db_id()) {
2990
            // Recycle the versioned keys
2991
3
            std::unique_ptr<Transaction> txn;
2992
3
            err = txn_kv_->create_txn(&txn);
2993
3
            if (err != TxnErrorCode::TXN_OK) {
2994
0
                LOG_WARNING("failed to create txn").tag("err", err);
2995
0
                return -1;
2996
0
            }
2997
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2998
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2999
3
            std::string index_inverted_key = versioned::index_inverted_key(
3000
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
3001
3
            versioned_remove_all(txn.get(), meta_key);
3002
3
            txn->remove(index_key);
3003
3
            txn->remove(index_inverted_key);
3004
3
            err = txn->commit();
3005
3
            if (err != TxnErrorCode::TXN_OK) {
3006
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3007
0
                return -1;
3008
0
            }
3009
3
        }
3010
3011
9
        metrics_context.total_recycled_num = ++num_recycled;
3012
9
        metrics_context.report();
3013
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3014
9
        index_keys.push_back(k);
3015
9
        return 0;
3016
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2914
4
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2915
4
        ++num_scanned;
2916
4
        RecycleIndexPB index_pb;
2917
4
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2918
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2919
0
            return -1;
2920
0
        }
2921
4
        int64_t current_time = ::time(nullptr);
2922
4
        if (current_time <
2923
4
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2924
0
            return 0;
2925
0
        }
2926
4
        ++num_expired;
2927
        // decode index_id
2928
4
        auto k1 = k;
2929
4
        k1.remove_prefix(1);
2930
4
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2931
4
        decode_key(&k1, &out);
2932
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2933
4
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2934
4
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2935
4
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2936
4
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2937
        // Change state to RECYCLING
2938
4
        std::unique_ptr<Transaction> txn;
2939
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2940
4
        if (err != TxnErrorCode::TXN_OK) {
2941
0
            LOG_WARNING("failed to create txn").tag("err", err);
2942
0
            return -1;
2943
0
        }
2944
4
        std::string val;
2945
4
        err = txn->get(k, &val);
2946
4
        if (err ==
2947
4
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2948
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2949
0
            return 0;
2950
0
        }
2951
4
        if (err != TxnErrorCode::TXN_OK) {
2952
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2953
0
            return -1;
2954
0
        }
2955
4
        index_pb.Clear();
2956
4
        if (!index_pb.ParseFromString(val)) {
2957
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2958
0
            return -1;
2959
0
        }
2960
4
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2961
3
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2962
3
            txn->put(k, index_pb.SerializeAsString());
2963
3
            err = txn->commit();
2964
3
            if (err != TxnErrorCode::TXN_OK) {
2965
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2966
0
                return -1;
2967
0
            }
2968
3
        }
2969
4
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
2970
2
            if (recycle_stream(index_id, index_pb, k) != 0) {
2971
0
                LOG_WARNING("failed to recycle table stream")
2972
0
                        .tag("instance_id", instance_id_)
2973
0
                        .tag("stream_id", index_id);
2974
0
                return -1;
2975
0
            }
2976
2
            metrics_context.total_recycled_num = ++num_recycled;
2977
2
            metrics_context.report();
2978
2
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2979
2
            return 0;
2980
2
        }
2981
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2982
1
            LOG_WARNING("failed to recycle tablets under index")
2983
1
                    .tag("table_id", index_pb.table_id())
2984
1
                    .tag("instance_id", instance_id_)
2985
1
                    .tag("index_id", index_id);
2986
1
            return -1;
2987
1
        }
2988
2989
1
        if (index_pb.has_db_id()) {
2990
            // Recycle the versioned keys
2991
1
            std::unique_ptr<Transaction> txn;
2992
1
            err = txn_kv_->create_txn(&txn);
2993
1
            if (err != TxnErrorCode::TXN_OK) {
2994
0
                LOG_WARNING("failed to create txn").tag("err", err);
2995
0
                return -1;
2996
0
            }
2997
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2998
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2999
1
            std::string index_inverted_key = versioned::index_inverted_key(
3000
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
3001
1
            versioned_remove_all(txn.get(), meta_key);
3002
1
            txn->remove(index_key);
3003
1
            txn->remove(index_inverted_key);
3004
1
            err = txn->commit();
3005
1
            if (err != TxnErrorCode::TXN_OK) {
3006
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3007
0
                return -1;
3008
0
            }
3009
1
        }
3010
3011
1
        metrics_context.total_recycled_num = ++num_recycled;
3012
1
        metrics_context.report();
3013
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3014
1
        index_keys.push_back(k);
3015
1
        return 0;
3016
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2914
9
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2915
9
        ++num_scanned;
2916
9
        RecycleIndexPB index_pb;
2917
9
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2918
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2919
0
            return -1;
2920
0
        }
2921
9
        int64_t current_time = ::time(nullptr);
2922
9
        if (current_time <
2923
9
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2924
0
            return 0;
2925
0
        }
2926
9
        ++num_expired;
2927
        // decode index_id
2928
9
        auto k1 = k;
2929
9
        k1.remove_prefix(1);
2930
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2931
9
        decode_key(&k1, &out);
2932
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2933
9
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2934
9
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2935
9
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2936
9
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2937
        // Change state to RECYCLING
2938
9
        std::unique_ptr<Transaction> txn;
2939
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2940
9
        if (err != TxnErrorCode::TXN_OK) {
2941
0
            LOG_WARNING("failed to create txn").tag("err", err);
2942
0
            return -1;
2943
0
        }
2944
9
        std::string val;
2945
9
        err = txn->get(k, &val);
2946
9
        if (err ==
2947
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2948
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2949
0
            return 0;
2950
0
        }
2951
9
        if (err != TxnErrorCode::TXN_OK) {
2952
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2953
0
            return -1;
2954
0
        }
2955
9
        index_pb.Clear();
2956
9
        if (!index_pb.ParseFromString(val)) {
2957
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2958
0
            return -1;
2959
0
        }
2960
9
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2961
9
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2962
9
            txn->put(k, index_pb.SerializeAsString());
2963
9
            err = txn->commit();
2964
9
            if (err != TxnErrorCode::TXN_OK) {
2965
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2966
0
                return -1;
2967
0
            }
2968
9
        }
2969
9
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
2970
1
            if (recycle_stream(index_id, index_pb, k) != 0) {
2971
0
                LOG_WARNING("failed to recycle table stream")
2972
0
                        .tag("instance_id", instance_id_)
2973
0
                        .tag("stream_id", index_id);
2974
0
                return -1;
2975
0
            }
2976
1
            metrics_context.total_recycled_num = ++num_recycled;
2977
1
            metrics_context.report();
2978
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2979
1
            return 0;
2980
1
        }
2981
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2982
0
            LOG_WARNING("failed to recycle tablets under index")
2983
0
                    .tag("table_id", index_pb.table_id())
2984
0
                    .tag("instance_id", instance_id_)
2985
0
                    .tag("index_id", index_id);
2986
0
            return -1;
2987
0
        }
2988
2989
8
        if (index_pb.has_db_id()) {
2990
            // Recycle the versioned keys
2991
2
            std::unique_ptr<Transaction> txn;
2992
2
            err = txn_kv_->create_txn(&txn);
2993
2
            if (err != TxnErrorCode::TXN_OK) {
2994
0
                LOG_WARNING("failed to create txn").tag("err", err);
2995
0
                return -1;
2996
0
            }
2997
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2998
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2999
2
            std::string index_inverted_key = versioned::index_inverted_key(
3000
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
3001
2
            versioned_remove_all(txn.get(), meta_key);
3002
2
            txn->remove(index_key);
3003
2
            txn->remove(index_inverted_key);
3004
2
            err = txn->commit();
3005
2
            if (err != TxnErrorCode::TXN_OK) {
3006
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3007
0
                return -1;
3008
0
            }
3009
2
        }
3010
3011
8
        metrics_context.total_recycled_num = ++num_recycled;
3012
8
        metrics_context.report();
3013
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3014
8
        index_keys.push_back(k);
3015
8
        return 0;
3016
8
    };
3017
3018
19
    auto loop_done = [&index_keys, this]() -> int {
3019
8
        if (index_keys.empty()) return 0;
3020
5
        DORIS_CLOUD_DEFER {
3021
5
            index_keys.clear();
3022
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3020
1
        DORIS_CLOUD_DEFER {
3021
1
            index_keys.clear();
3022
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3020
4
        DORIS_CLOUD_DEFER {
3021
4
            index_keys.clear();
3022
4
        };
3023
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
3024
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
3025
0
            return -1;
3026
0
        }
3027
5
        return 0;
3028
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
3018
3
    auto loop_done = [&index_keys, this]() -> int {
3019
3
        if (index_keys.empty()) return 0;
3020
1
        DORIS_CLOUD_DEFER {
3021
1
            index_keys.clear();
3022
1
        };
3023
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
3024
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
3025
0
            return -1;
3026
0
        }
3027
1
        return 0;
3028
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
3018
5
    auto loop_done = [&index_keys, this]() -> int {
3019
5
        if (index_keys.empty()) return 0;
3020
4
        DORIS_CLOUD_DEFER {
3021
4
            index_keys.clear();
3022
4
        };
3023
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
3024
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
3025
0
            return -1;
3026
0
        }
3027
4
        return 0;
3028
4
    };
3029
3030
19
    if (config::enable_recycler_stats_metrics) {
3031
0
        scan_and_statistics_indexes();
3032
0
    }
3033
    // recycle_func and loop_done for scan and recycle
3034
19
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
3035
19
}
3036
3037
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
3038
8.25k
                             int64_t tablet_id) {
3039
8.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
3040
3041
8.25k
    std::unique_ptr<Transaction> txn;
3042
8.25k
    TxnErrorCode err = txn_kv->create_txn(&txn);
3043
8.25k
    if (err != TxnErrorCode::TXN_OK) {
3044
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
3045
0
                     << " tablet_id=" << tablet_id << " err=" << err;
3046
0
        return false;
3047
0
    }
3048
3049
8.25k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
3050
8.25k
    std::string tablet_idx_val;
3051
8.25k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
3052
8.25k
    if (TxnErrorCode::TXN_OK != err) {
3053
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
3054
0
                     << " tablet_id=" << tablet_id << " err=" << err
3055
0
                     << " key=" << hex(tablet_idx_key);
3056
0
        return false;
3057
0
    }
3058
3059
8.25k
    TabletIndexPB tablet_idx_pb;
3060
8.25k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
3061
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
3062
0
                     << " tablet_id=" << tablet_id;
3063
0
        return false;
3064
0
    }
3065
3066
8.25k
    if (!tablet_idx_pb.has_db_id()) {
3067
        // In the previous version, the db_id was not set in the index_pb.
3068
        // If updating to the version which enable txn lazy commit, the db_id will be set.
3069
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
3070
0
                  << " instance_id=" << instance_id
3071
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
3072
0
        return true;
3073
0
    }
3074
3075
8.25k
    std::string ver_val;
3076
8.25k
    std::string ver_key =
3077
8.25k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
3078
8.25k
                                   tablet_idx_pb.partition_id()});
3079
8.25k
    err = txn->get(ver_key, &ver_val);
3080
3081
8.25k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
3082
214
        LOG(INFO) << ""
3083
214
                     "partition version not found, instance_id="
3084
214
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
3085
214
                  << " table_id=" << tablet_idx_pb.table_id()
3086
214
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
3087
214
                  << " key=" << hex(ver_key);
3088
214
        return true;
3089
214
    }
3090
3091
8.03k
    if (TxnErrorCode::TXN_OK != err) {
3092
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
3093
0
                     << " db_id=" << tablet_idx_pb.db_id()
3094
0
                     << " table_id=" << tablet_idx_pb.table_id()
3095
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
3096
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
3097
0
        return false;
3098
0
    }
3099
3100
8.03k
    VersionPB version_pb;
3101
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
3102
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
3103
0
                     << " db_id=" << tablet_idx_pb.db_id()
3104
0
                     << " table_id=" << tablet_idx_pb.table_id()
3105
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
3106
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
3107
0
        return false;
3108
0
    }
3109
3110
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
3111
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
3112
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
3113
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
3114
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
3115
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
3116
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
3117
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
3118
4.00k
                     << " key=" << hex(ver_key);
3119
4.00k
        return false;
3120
4.00k
    }
3121
4.03k
    return true;
3122
8.03k
}
3123
3124
17
int InstanceRecycler::recycle_partitions() {
3125
17
    const std::string task_name = "recycle_partitions";
3126
17
    int64_t num_scanned = 0;
3127
17
    int64_t num_expired = 0;
3128
17
    int64_t num_recycled = 0;
3129
17
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
3130
3131
17
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
3132
17
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
3133
17
    std::string part_key0;
3134
17
    std::string part_key1;
3135
17
    recycle_partition_key(part_key_info0, &part_key0);
3136
17
    recycle_partition_key(part_key_info1, &part_key1);
3137
3138
17
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
3139
3140
17
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
3141
17
    register_recycle_task(task_name, start_time);
3142
3143
17
    DORIS_CLOUD_DEFER {
3144
17
        unregister_recycle_task(task_name);
3145
17
        int64_t cost =
3146
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3147
17
        metrics_context.finish_report();
3148
17
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3149
17
                .tag("instance_id", instance_id_)
3150
17
                .tag("num_scanned", num_scanned)
3151
17
                .tag("num_expired", num_expired)
3152
17
                .tag("num_recycled", num_recycled);
3153
17
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
3143
2
    DORIS_CLOUD_DEFER {
3144
2
        unregister_recycle_task(task_name);
3145
2
        int64_t cost =
3146
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3147
2
        metrics_context.finish_report();
3148
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3149
2
                .tag("instance_id", instance_id_)
3150
2
                .tag("num_scanned", num_scanned)
3151
2
                .tag("num_expired", num_expired)
3152
2
                .tag("num_recycled", num_recycled);
3153
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
3143
15
    DORIS_CLOUD_DEFER {
3144
15
        unregister_recycle_task(task_name);
3145
15
        int64_t cost =
3146
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3147
15
        metrics_context.finish_report();
3148
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3149
15
                .tag("instance_id", instance_id_)
3150
15
                .tag("num_scanned", num_scanned)
3151
15
                .tag("num_expired", num_expired)
3152
15
                .tag("num_recycled", num_recycled);
3153
15
    };
3154
3155
17
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
3156
3157
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
3158
17
    std::vector<std::string_view> partition_keys;
3159
17
    std::vector<std::string> partition_version_keys;
3160
17
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3161
11
        ++num_scanned;
3162
11
        RecyclePartitionPB part_pb;
3163
11
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3164
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3165
0
            return -1;
3166
0
        }
3167
11
        int64_t current_time = ::time(nullptr);
3168
11
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3169
11
                                                            &earlest_ts)) { // not expired
3170
0
            return 0;
3171
0
        }
3172
11
        ++num_expired;
3173
        // decode partition_id
3174
11
        auto k1 = k;
3175
11
        k1.remove_prefix(1);
3176
11
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3177
11
        decode_key(&k1, &out);
3178
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3179
11
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3180
11
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3181
11
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3182
11
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3183
        // Change state to RECYCLING
3184
11
        std::unique_ptr<Transaction> txn;
3185
11
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3186
11
        if (err != TxnErrorCode::TXN_OK) {
3187
0
            LOG_WARNING("failed to create txn").tag("err", err);
3188
0
            return -1;
3189
0
        }
3190
11
        std::string val;
3191
11
        err = txn->get(k, &val);
3192
11
        if (err ==
3193
11
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3194
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3195
0
            return 0;
3196
0
        }
3197
11
        if (err != TxnErrorCode::TXN_OK) {
3198
0
            LOG_WARNING("failed to get kv");
3199
0
            return -1;
3200
0
        }
3201
11
        part_pb.Clear();
3202
11
        if (!part_pb.ParseFromString(val)) {
3203
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3204
0
            return -1;
3205
0
        }
3206
        // Partitions with PREPARED state MUST have no data
3207
11
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3208
10
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3209
10
            txn->put(k, part_pb.SerializeAsString());
3210
10
            err = txn->commit();
3211
10
            if (err != TxnErrorCode::TXN_OK) {
3212
0
                LOG_WARNING("failed to commit txn: {}", err);
3213
0
                return -1;
3214
0
            }
3215
10
        }
3216
3217
11
        int ret = 0;
3218
35
        for (int64_t index_id : part_pb.index_id()) {
3219
35
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3220
1
                LOG_WARNING("failed to recycle tablets under partition")
3221
1
                        .tag("table_id", part_pb.table_id())
3222
1
                        .tag("instance_id", instance_id_)
3223
1
                        .tag("index_id", index_id)
3224
1
                        .tag("partition_id", partition_id);
3225
1
                ret = -1;
3226
1
            }
3227
35
        }
3228
11
        if (ret == 0 && part_pb.has_db_id() &&
3229
11
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
3230
10
                                                   partition_id, part_pb.table_streams()) != 0) {
3231
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
3232
0
                    .tag("instance_id", instance_id_)
3233
0
                    .tag("table_id", part_pb.table_id())
3234
0
                    .tag("partition_id", partition_id);
3235
0
            ret = -1;
3236
0
        }
3237
11
        if (ret == 0 && part_pb.has_db_id()) {
3238
            // Recycle the versioned keys
3239
10
            std::unique_ptr<Transaction> txn;
3240
10
            err = txn_kv_->create_txn(&txn);
3241
10
            if (err != TxnErrorCode::TXN_OK) {
3242
0
                LOG_WARNING("failed to create txn").tag("err", err);
3243
0
                return -1;
3244
0
            }
3245
10
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3246
10
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3247
10
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3248
10
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3249
10
            std::string partition_version_key =
3250
10
                    versioned::partition_version_key({instance_id_, partition_id});
3251
10
            versioned_remove_all(txn.get(), meta_key);
3252
10
            txn->remove(index_key);
3253
10
            txn->remove(inverted_index_key);
3254
10
            versioned_remove_all(txn.get(), partition_version_key);
3255
10
            err = txn->commit();
3256
10
            if (err != TxnErrorCode::TXN_OK) {
3257
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3258
0
                return -1;
3259
0
            }
3260
10
        }
3261
3262
11
        if (ret == 0) {
3263
10
            ++num_recycled;
3264
10
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3265
10
            partition_keys.push_back(k);
3266
10
            if (part_pb.db_id() > 0) {
3267
10
                partition_version_keys.push_back(partition_version_key(
3268
10
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3269
10
            }
3270
10
            metrics_context.total_recycled_num = num_recycled;
3271
10
            metrics_context.report();
3272
10
        }
3273
11
        return ret;
3274
11
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3160
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3161
2
        ++num_scanned;
3162
2
        RecyclePartitionPB part_pb;
3163
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3164
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3165
0
            return -1;
3166
0
        }
3167
2
        int64_t current_time = ::time(nullptr);
3168
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3169
2
                                                            &earlest_ts)) { // not expired
3170
0
            return 0;
3171
0
        }
3172
2
        ++num_expired;
3173
        // decode partition_id
3174
2
        auto k1 = k;
3175
2
        k1.remove_prefix(1);
3176
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3177
2
        decode_key(&k1, &out);
3178
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3179
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3180
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3181
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3182
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3183
        // Change state to RECYCLING
3184
2
        std::unique_ptr<Transaction> txn;
3185
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3186
2
        if (err != TxnErrorCode::TXN_OK) {
3187
0
            LOG_WARNING("failed to create txn").tag("err", err);
3188
0
            return -1;
3189
0
        }
3190
2
        std::string val;
3191
2
        err = txn->get(k, &val);
3192
2
        if (err ==
3193
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3194
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3195
0
            return 0;
3196
0
        }
3197
2
        if (err != TxnErrorCode::TXN_OK) {
3198
0
            LOG_WARNING("failed to get kv");
3199
0
            return -1;
3200
0
        }
3201
2
        part_pb.Clear();
3202
2
        if (!part_pb.ParseFromString(val)) {
3203
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3204
0
            return -1;
3205
0
        }
3206
        // Partitions with PREPARED state MUST have no data
3207
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3208
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3209
1
            txn->put(k, part_pb.SerializeAsString());
3210
1
            err = txn->commit();
3211
1
            if (err != TxnErrorCode::TXN_OK) {
3212
0
                LOG_WARNING("failed to commit txn: {}", err);
3213
0
                return -1;
3214
0
            }
3215
1
        }
3216
3217
2
        int ret = 0;
3218
2
        for (int64_t index_id : part_pb.index_id()) {
3219
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3220
1
                LOG_WARNING("failed to recycle tablets under partition")
3221
1
                        .tag("table_id", part_pb.table_id())
3222
1
                        .tag("instance_id", instance_id_)
3223
1
                        .tag("index_id", index_id)
3224
1
                        .tag("partition_id", partition_id);
3225
1
                ret = -1;
3226
1
            }
3227
2
        }
3228
2
        if (ret == 0 && part_pb.has_db_id() &&
3229
2
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
3230
1
                                                   partition_id, part_pb.table_streams()) != 0) {
3231
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
3232
0
                    .tag("instance_id", instance_id_)
3233
0
                    .tag("table_id", part_pb.table_id())
3234
0
                    .tag("partition_id", partition_id);
3235
0
            ret = -1;
3236
0
        }
3237
2
        if (ret == 0 && part_pb.has_db_id()) {
3238
            // Recycle the versioned keys
3239
1
            std::unique_ptr<Transaction> txn;
3240
1
            err = txn_kv_->create_txn(&txn);
3241
1
            if (err != TxnErrorCode::TXN_OK) {
3242
0
                LOG_WARNING("failed to create txn").tag("err", err);
3243
0
                return -1;
3244
0
            }
3245
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3246
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3247
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3248
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3249
1
            std::string partition_version_key =
3250
1
                    versioned::partition_version_key({instance_id_, partition_id});
3251
1
            versioned_remove_all(txn.get(), meta_key);
3252
1
            txn->remove(index_key);
3253
1
            txn->remove(inverted_index_key);
3254
1
            versioned_remove_all(txn.get(), partition_version_key);
3255
1
            err = txn->commit();
3256
1
            if (err != TxnErrorCode::TXN_OK) {
3257
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3258
0
                return -1;
3259
0
            }
3260
1
        }
3261
3262
2
        if (ret == 0) {
3263
1
            ++num_recycled;
3264
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3265
1
            partition_keys.push_back(k);
3266
1
            if (part_pb.db_id() > 0) {
3267
1
                partition_version_keys.push_back(partition_version_key(
3268
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3269
1
            }
3270
1
            metrics_context.total_recycled_num = num_recycled;
3271
1
            metrics_context.report();
3272
1
        }
3273
2
        return ret;
3274
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3160
9
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3161
9
        ++num_scanned;
3162
9
        RecyclePartitionPB part_pb;
3163
9
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3164
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3165
0
            return -1;
3166
0
        }
3167
9
        int64_t current_time = ::time(nullptr);
3168
9
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3169
9
                                                            &earlest_ts)) { // not expired
3170
0
            return 0;
3171
0
        }
3172
9
        ++num_expired;
3173
        // decode partition_id
3174
9
        auto k1 = k;
3175
9
        k1.remove_prefix(1);
3176
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3177
9
        decode_key(&k1, &out);
3178
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3179
9
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3180
9
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3181
9
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3182
9
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3183
        // Change state to RECYCLING
3184
9
        std::unique_ptr<Transaction> txn;
3185
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3186
9
        if (err != TxnErrorCode::TXN_OK) {
3187
0
            LOG_WARNING("failed to create txn").tag("err", err);
3188
0
            return -1;
3189
0
        }
3190
9
        std::string val;
3191
9
        err = txn->get(k, &val);
3192
9
        if (err ==
3193
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3194
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3195
0
            return 0;
3196
0
        }
3197
9
        if (err != TxnErrorCode::TXN_OK) {
3198
0
            LOG_WARNING("failed to get kv");
3199
0
            return -1;
3200
0
        }
3201
9
        part_pb.Clear();
3202
9
        if (!part_pb.ParseFromString(val)) {
3203
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3204
0
            return -1;
3205
0
        }
3206
        // Partitions with PREPARED state MUST have no data
3207
9
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3208
9
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3209
9
            txn->put(k, part_pb.SerializeAsString());
3210
9
            err = txn->commit();
3211
9
            if (err != TxnErrorCode::TXN_OK) {
3212
0
                LOG_WARNING("failed to commit txn: {}", err);
3213
0
                return -1;
3214
0
            }
3215
9
        }
3216
3217
9
        int ret = 0;
3218
33
        for (int64_t index_id : part_pb.index_id()) {
3219
33
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3220
0
                LOG_WARNING("failed to recycle tablets under partition")
3221
0
                        .tag("table_id", part_pb.table_id())
3222
0
                        .tag("instance_id", instance_id_)
3223
0
                        .tag("index_id", index_id)
3224
0
                        .tag("partition_id", partition_id);
3225
0
                ret = -1;
3226
0
            }
3227
33
        }
3228
9
        if (ret == 0 && part_pb.has_db_id() &&
3229
9
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
3230
9
                                                   partition_id, part_pb.table_streams()) != 0) {
3231
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
3232
0
                    .tag("instance_id", instance_id_)
3233
0
                    .tag("table_id", part_pb.table_id())
3234
0
                    .tag("partition_id", partition_id);
3235
0
            ret = -1;
3236
0
        }
3237
9
        if (ret == 0 && part_pb.has_db_id()) {
3238
            // Recycle the versioned keys
3239
9
            std::unique_ptr<Transaction> txn;
3240
9
            err = txn_kv_->create_txn(&txn);
3241
9
            if (err != TxnErrorCode::TXN_OK) {
3242
0
                LOG_WARNING("failed to create txn").tag("err", err);
3243
0
                return -1;
3244
0
            }
3245
9
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3246
9
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3247
9
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3248
9
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3249
9
            std::string partition_version_key =
3250
9
                    versioned::partition_version_key({instance_id_, partition_id});
3251
9
            versioned_remove_all(txn.get(), meta_key);
3252
9
            txn->remove(index_key);
3253
9
            txn->remove(inverted_index_key);
3254
9
            versioned_remove_all(txn.get(), partition_version_key);
3255
9
            err = txn->commit();
3256
9
            if (err != TxnErrorCode::TXN_OK) {
3257
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3258
0
                return -1;
3259
0
            }
3260
9
        }
3261
3262
9
        if (ret == 0) {
3263
9
            ++num_recycled;
3264
9
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3265
9
            partition_keys.push_back(k);
3266
9
            if (part_pb.db_id() > 0) {
3267
9
                partition_version_keys.push_back(partition_version_key(
3268
9
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3269
9
            }
3270
9
            metrics_context.total_recycled_num = num_recycled;
3271
9
            metrics_context.report();
3272
9
        }
3273
9
        return ret;
3274
9
    };
3275
3276
17
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3277
7
        if (partition_keys.empty()) return 0;
3278
6
        DORIS_CLOUD_DEFER {
3279
6
            partition_keys.clear();
3280
6
            partition_version_keys.clear();
3281
6
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3278
1
        DORIS_CLOUD_DEFER {
3279
1
            partition_keys.clear();
3280
1
            partition_version_keys.clear();
3281
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3278
5
        DORIS_CLOUD_DEFER {
3279
5
            partition_keys.clear();
3280
5
            partition_version_keys.clear();
3281
5
        };
3282
6
        std::unique_ptr<Transaction> txn;
3283
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3284
6
        if (err != TxnErrorCode::TXN_OK) {
3285
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3286
0
            return -1;
3287
0
        }
3288
10
        for (auto& k : partition_keys) {
3289
10
            txn->remove(k);
3290
10
        }
3291
10
        for (auto& k : partition_version_keys) {
3292
10
            txn->remove(k);
3293
10
        }
3294
6
        err = txn->commit();
3295
6
        if (err != TxnErrorCode::TXN_OK) {
3296
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3297
0
                         << " err=" << err;
3298
0
            return -1;
3299
0
        }
3300
6
        return 0;
3301
6
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3276
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3277
2
        if (partition_keys.empty()) return 0;
3278
1
        DORIS_CLOUD_DEFER {
3279
1
            partition_keys.clear();
3280
1
            partition_version_keys.clear();
3281
1
        };
3282
1
        std::unique_ptr<Transaction> txn;
3283
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3284
1
        if (err != TxnErrorCode::TXN_OK) {
3285
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3286
0
            return -1;
3287
0
        }
3288
1
        for (auto& k : partition_keys) {
3289
1
            txn->remove(k);
3290
1
        }
3291
1
        for (auto& k : partition_version_keys) {
3292
1
            txn->remove(k);
3293
1
        }
3294
1
        err = txn->commit();
3295
1
        if (err != TxnErrorCode::TXN_OK) {
3296
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3297
0
                         << " err=" << err;
3298
0
            return -1;
3299
0
        }
3300
1
        return 0;
3301
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3276
5
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3277
5
        if (partition_keys.empty()) return 0;
3278
5
        DORIS_CLOUD_DEFER {
3279
5
            partition_keys.clear();
3280
5
            partition_version_keys.clear();
3281
5
        };
3282
5
        std::unique_ptr<Transaction> txn;
3283
5
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3284
5
        if (err != TxnErrorCode::TXN_OK) {
3285
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3286
0
            return -1;
3287
0
        }
3288
9
        for (auto& k : partition_keys) {
3289
9
            txn->remove(k);
3290
9
        }
3291
9
        for (auto& k : partition_version_keys) {
3292
9
            txn->remove(k);
3293
9
        }
3294
5
        err = txn->commit();
3295
5
        if (err != TxnErrorCode::TXN_OK) {
3296
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3297
0
                         << " err=" << err;
3298
0
            return -1;
3299
0
        }
3300
5
        return 0;
3301
5
    };
3302
3303
17
    if (config::enable_recycler_stats_metrics) {
3304
0
        scan_and_statistics_partitions();
3305
0
    }
3306
    // recycle_func and loop_done for scan and recycle
3307
17
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
3308
17
}
3309
3310
14
int InstanceRecycler::recycle_versions() {
3311
14
    if (should_recycle_versioned_keys()) {
3312
2
        return recycle_orphan_partitions();
3313
2
    }
3314
3315
12
    int64_t num_scanned = 0;
3316
12
    int64_t num_recycled = 0;
3317
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
3318
3319
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
3320
3321
12
    auto start_time = steady_clock::now();
3322
3323
12
    DORIS_CLOUD_DEFER {
3324
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3325
12
        metrics_context.finish_report();
3326
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3327
12
                .tag("instance_id", instance_id_)
3328
12
                .tag("num_scanned", num_scanned)
3329
12
                .tag("num_recycled", num_recycled);
3330
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
3323
12
    DORIS_CLOUD_DEFER {
3324
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3325
12
        metrics_context.finish_report();
3326
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3327
12
                .tag("instance_id", instance_id_)
3328
12
                .tag("num_scanned", num_scanned)
3329
12
                .tag("num_recycled", num_recycled);
3330
12
    };
3331
3332
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
3333
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
3334
12
    int64_t last_scanned_table_id = 0;
3335
12
    bool is_recycled = false; // Is last scanned kv recycled
3336
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
3337
12
                         &metrics_context, this](std::string_view k, std::string_view) {
3338
2
        ++num_scanned;
3339
2
        auto k1 = k;
3340
2
        k1.remove_prefix(1);
3341
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3342
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3343
2
        decode_key(&k1, &out);
3344
2
        DCHECK_EQ(out.size(), 6) << k;
3345
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3346
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3347
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3348
0
            return 0;
3349
0
        }
3350
2
        last_scanned_table_id = table_id;
3351
2
        is_recycled = false;
3352
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3353
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3354
2
        std::unique_ptr<Transaction> txn;
3355
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3356
2
        if (err != TxnErrorCode::TXN_OK) {
3357
0
            return -1;
3358
0
        }
3359
2
        std::unique_ptr<RangeGetIterator> iter;
3360
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3361
2
        if (err != TxnErrorCode::TXN_OK) {
3362
0
            return -1;
3363
0
        }
3364
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3365
1
            return 0;
3366
1
        }
3367
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3368
        // 1. Remove all partition version kvs of this table
3369
1
        auto partition_version_key_begin =
3370
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3371
1
        auto partition_version_key_end =
3372
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3373
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3374
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3375
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3376
1
                     << " table_id=" << table_id;
3377
        // 2. Remove the table version kv of this table
3378
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3379
1
        txn->remove(tbl_version_key);
3380
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3381
        // 3. Remove mow delete bitmap update lock and tablet job lock
3382
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3383
1
        txn->remove(lock_key);
3384
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3385
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3386
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3387
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3388
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3389
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3390
1
                     << " table_id=" << table_id;
3391
1
        err = txn->commit();
3392
1
        if (err != TxnErrorCode::TXN_OK) {
3393
0
            return -1;
3394
0
        }
3395
1
        metrics_context.total_recycled_num = ++num_recycled;
3396
1
        metrics_context.report();
3397
1
        is_recycled = true;
3398
1
        return 0;
3399
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3337
2
                         &metrics_context, this](std::string_view k, std::string_view) {
3338
2
        ++num_scanned;
3339
2
        auto k1 = k;
3340
2
        k1.remove_prefix(1);
3341
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3342
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3343
2
        decode_key(&k1, &out);
3344
2
        DCHECK_EQ(out.size(), 6) << k;
3345
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3346
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3347
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3348
0
            return 0;
3349
0
        }
3350
2
        last_scanned_table_id = table_id;
3351
2
        is_recycled = false;
3352
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3353
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3354
2
        std::unique_ptr<Transaction> txn;
3355
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3356
2
        if (err != TxnErrorCode::TXN_OK) {
3357
0
            return -1;
3358
0
        }
3359
2
        std::unique_ptr<RangeGetIterator> iter;
3360
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3361
2
        if (err != TxnErrorCode::TXN_OK) {
3362
0
            return -1;
3363
0
        }
3364
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3365
1
            return 0;
3366
1
        }
3367
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3368
        // 1. Remove all partition version kvs of this table
3369
1
        auto partition_version_key_begin =
3370
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3371
1
        auto partition_version_key_end =
3372
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3373
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3374
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3375
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3376
1
                     << " table_id=" << table_id;
3377
        // 2. Remove the table version kv of this table
3378
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3379
1
        txn->remove(tbl_version_key);
3380
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3381
        // 3. Remove mow delete bitmap update lock and tablet job lock
3382
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3383
1
        txn->remove(lock_key);
3384
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3385
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3386
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3387
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3388
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3389
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3390
1
                     << " table_id=" << table_id;
3391
1
        err = txn->commit();
3392
1
        if (err != TxnErrorCode::TXN_OK) {
3393
0
            return -1;
3394
0
        }
3395
1
        metrics_context.total_recycled_num = ++num_recycled;
3396
1
        metrics_context.report();
3397
1
        is_recycled = true;
3398
1
        return 0;
3399
1
    };
3400
3401
12
    if (config::enable_recycler_stats_metrics) {
3402
0
        scan_and_statistics_versions();
3403
0
    }
3404
    // recycle_func and loop_done for scan and recycle
3405
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
3406
14
}
3407
3408
3
int InstanceRecycler::recycle_orphan_partitions() {
3409
3
    int64_t num_scanned = 0;
3410
3
    int64_t num_recycled = 0;
3411
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
3412
3413
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
3414
3
            .tag("instance_id", instance_id_);
3415
3416
3
    auto start_time = steady_clock::now();
3417
3418
3
    DORIS_CLOUD_DEFER {
3419
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3420
3
        metrics_context.finish_report();
3421
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3422
3
                .tag("instance_id", instance_id_)
3423
3
                .tag("num_scanned", num_scanned)
3424
3
                .tag("num_recycled", num_recycled);
3425
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
3418
3
    DORIS_CLOUD_DEFER {
3419
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3420
3
        metrics_context.finish_report();
3421
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3422
3
                .tag("instance_id", instance_id_)
3423
3
                .tag("num_scanned", num_scanned)
3424
3
                .tag("num_recycled", num_recycled);
3425
3
    };
3426
3427
3
    bool is_empty_table = false;        // whether the table has no indexes
3428
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
3429
3
    int64_t current_table_id = 0;       // current scanning table id
3430
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
3431
3
                         &current_table_id, &is_table_kvs_recycled,
3432
3
                         this](std::string_view k, std::string_view) {
3433
2
        ++num_scanned;
3434
3435
2
        std::string_view k1(k);
3436
2
        int64_t db_id, table_id, partition_id;
3437
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3438
2
                                                            &partition_id)) {
3439
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3440
0
            return -1;
3441
2
        } else if (table_id != current_table_id) {
3442
2
            current_table_id = table_id;
3443
2
            is_table_kvs_recycled = false;
3444
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3445
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3446
2
            if (err != TxnErrorCode::TXN_OK) {
3447
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3448
0
                             << " table_id=" << table_id << " err=" << err;
3449
0
                return -1;
3450
0
            }
3451
2
        }
3452
3453
2
        if (!is_empty_table) {
3454
            // table is not empty, skip recycle
3455
1
            return 0;
3456
1
        }
3457
3458
1
        std::unique_ptr<Transaction> txn;
3459
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3460
1
        if (err != TxnErrorCode::TXN_OK) {
3461
0
            return -1;
3462
0
        }
3463
3464
        // 1. Remove all partition related kvs
3465
1
        std::string partition_meta_key =
3466
1
                versioned::meta_partition_key({instance_id_, partition_id});
3467
1
        std::string partition_index_key =
3468
1
                versioned::partition_index_key({instance_id_, partition_id});
3469
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3470
1
                {instance_id_, db_id, table_id, partition_id});
3471
1
        std::string partition_version_key =
3472
1
                versioned::partition_version_key({instance_id_, partition_id});
3473
1
        txn->remove(partition_index_key);
3474
1
        txn->remove(partition_inverted_key);
3475
1
        versioned_remove_all(txn.get(), partition_meta_key);
3476
1
        versioned_remove_all(txn.get(), partition_version_key);
3477
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3478
1
                     << " table_id=" << table_id << " db_id=" << db_id
3479
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3480
1
                     << " partition_version_key=" << hex(partition_version_key);
3481
3482
1
        if (!is_table_kvs_recycled) {
3483
1
            is_table_kvs_recycled = true;
3484
3485
            // 2. Remove the table version kv of this table
3486
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3487
1
            versioned_remove_all(txn.get(), table_version_key);
3488
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3489
            // 3. Remove mow delete bitmap update lock and tablet job lock
3490
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3491
1
            txn->remove(lock_key);
3492
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3493
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3494
1
            std::string tablet_job_key_end =
3495
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3496
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3497
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3498
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3499
1
                         << " table_id=" << table_id;
3500
1
        }
3501
3502
1
        err = txn->commit();
3503
1
        if (err != TxnErrorCode::TXN_OK) {
3504
0
            return -1;
3505
0
        }
3506
1
        metrics_context.total_recycled_num = ++num_recycled;
3507
1
        metrics_context.report();
3508
1
        return 0;
3509
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
3432
2
                         this](std::string_view k, std::string_view) {
3433
2
        ++num_scanned;
3434
3435
2
        std::string_view k1(k);
3436
2
        int64_t db_id, table_id, partition_id;
3437
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3438
2
                                                            &partition_id)) {
3439
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3440
0
            return -1;
3441
2
        } else if (table_id != current_table_id) {
3442
2
            current_table_id = table_id;
3443
2
            is_table_kvs_recycled = false;
3444
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3445
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3446
2
            if (err != TxnErrorCode::TXN_OK) {
3447
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3448
0
                             << " table_id=" << table_id << " err=" << err;
3449
0
                return -1;
3450
0
            }
3451
2
        }
3452
3453
2
        if (!is_empty_table) {
3454
            // table is not empty, skip recycle
3455
1
            return 0;
3456
1
        }
3457
3458
1
        std::unique_ptr<Transaction> txn;
3459
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3460
1
        if (err != TxnErrorCode::TXN_OK) {
3461
0
            return -1;
3462
0
        }
3463
3464
        // 1. Remove all partition related kvs
3465
1
        std::string partition_meta_key =
3466
1
                versioned::meta_partition_key({instance_id_, partition_id});
3467
1
        std::string partition_index_key =
3468
1
                versioned::partition_index_key({instance_id_, partition_id});
3469
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3470
1
                {instance_id_, db_id, table_id, partition_id});
3471
1
        std::string partition_version_key =
3472
1
                versioned::partition_version_key({instance_id_, partition_id});
3473
1
        txn->remove(partition_index_key);
3474
1
        txn->remove(partition_inverted_key);
3475
1
        versioned_remove_all(txn.get(), partition_meta_key);
3476
1
        versioned_remove_all(txn.get(), partition_version_key);
3477
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3478
1
                     << " table_id=" << table_id << " db_id=" << db_id
3479
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3480
1
                     << " partition_version_key=" << hex(partition_version_key);
3481
3482
1
        if (!is_table_kvs_recycled) {
3483
1
            is_table_kvs_recycled = true;
3484
3485
            // 2. Remove the table version kv of this table
3486
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3487
1
            versioned_remove_all(txn.get(), table_version_key);
3488
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3489
            // 3. Remove mow delete bitmap update lock and tablet job lock
3490
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3491
1
            txn->remove(lock_key);
3492
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3493
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3494
1
            std::string tablet_job_key_end =
3495
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3496
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3497
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3498
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3499
1
                         << " table_id=" << table_id;
3500
1
        }
3501
3502
1
        err = txn->commit();
3503
1
        if (err != TxnErrorCode::TXN_OK) {
3504
0
            return -1;
3505
0
        }
3506
1
        metrics_context.total_recycled_num = ++num_recycled;
3507
1
        metrics_context.report();
3508
1
        return 0;
3509
1
    };
3510
3511
    // recycle_func and loop_done for scan and recycle
3512
3
    return scan_and_recycle(
3513
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
3514
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
3515
3
            std::move(recycle_func));
3516
3
}
3517
3518
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
3519
                                      RecyclerMetricsContext& metrics_context,
3520
54
                                      int64_t partition_id) {
3521
54
    bool is_multi_version =
3522
54
            instance_info_.has_multi_version_status() &&
3523
54
            instance_info_.multi_version_status() != MultiVersionStatus::MULTI_VERSION_DISABLED;
3524
54
    int64_t num_scanned = 0;
3525
54
    std::atomic_long num_recycled = 0;
3526
3527
54
    std::string tablet_key_begin, tablet_key_end;
3528
54
    std::string stats_key_begin, stats_key_end;
3529
54
    std::string job_key_begin, job_key_end;
3530
3531
54
    std::string tablet_belongs;
3532
54
    if (partition_id > 0) {
3533
        // recycle tablets in a partition belonging to the index
3534
35
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
3535
35
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
3536
35
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
3537
35
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
3538
35
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
3539
35
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
3540
35
        tablet_belongs = "partition";
3541
35
    } else {
3542
        // recycle tablets in the index
3543
19
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
3544
19
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
3545
19
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
3546
19
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
3547
19
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
3548
19
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
3549
19
        tablet_belongs = "index";
3550
19
    }
3551
3552
54
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
3553
54
            .tag("table_id", table_id)
3554
54
            .tag("index_id", index_id)
3555
54
            .tag("partition_id", partition_id);
3556
3557
54
    auto start_time = steady_clock::now();
3558
3559
54
    DORIS_CLOUD_DEFER {
3560
54
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3561
54
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3562
54
                .tag("instance_id", instance_id_)
3563
54
                .tag("table_id", table_id)
3564
54
                .tag("index_id", index_id)
3565
54
                .tag("partition_id", partition_id)
3566
54
                .tag("num_scanned", num_scanned)
3567
54
                .tag("num_recycled", num_recycled);
3568
54
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3559
4
    DORIS_CLOUD_DEFER {
3560
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3561
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3562
4
                .tag("instance_id", instance_id_)
3563
4
                .tag("table_id", table_id)
3564
4
                .tag("index_id", index_id)
3565
4
                .tag("partition_id", partition_id)
3566
4
                .tag("num_scanned", num_scanned)
3567
4
                .tag("num_recycled", num_recycled);
3568
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3559
50
    DORIS_CLOUD_DEFER {
3560
50
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3561
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3562
50
                .tag("instance_id", instance_id_)
3563
50
                .tag("table_id", table_id)
3564
50
                .tag("index_id", index_id)
3565
50
                .tag("partition_id", partition_id)
3566
50
                .tag("num_scanned", num_scanned)
3567
50
                .tag("num_recycled", num_recycled);
3568
50
    };
3569
3570
    // The tablet key and id which have been recycled.
3571
54
    struct TabletInfo {
3572
54
        std::string_view tablet_meta_key;
3573
54
        int64_t tablet_id;
3574
54
    };
3575
54
    SyncExecutor<TabletInfo> sync_executor(
3576
54
            _thread_pool_group.recycle_tablet_pool,
3577
54
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
3578
54
                        index_id, partition_id),
3579
4.24k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3579
4.00k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3579
241
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
3580
3581
    // Elements in `tablets_info` has the same lifetime as `it` in `scan_and_recycle`
3582
54
    std::vector<std::string> init_rs_keys;
3583
54
    bool has_failure = false;
3584
8.25k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3585
8.25k
        ++num_scanned;
3586
8.25k
        doris::TabletMetaCloudPB tablet_meta_pb;
3587
8.25k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3588
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3589
0
            has_failure = true;
3590
0
            return -1;
3591
0
        }
3592
8.25k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3593
3594
8.25k
        if (config::enable_recycler_check_lazy_txn_finished &&
3595
8.25k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3596
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3597
4.00k
            has_failure = true;
3598
4.00k
            return -1;
3599
4.00k
        }
3600
3601
8.25k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3602
4.25k
        sync_executor.add(
3603
4.25k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3604
4.25k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3605
2
                        LOG_WARNING("failed to recycle tablet")
3606
2
                                .tag("instance_id", instance_id_)
3607
2
                                .tag("tablet_id", tid);
3608
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3609
2
                    }
3610
4.25k
                    ++num_recycled;
3611
4.25k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3612
4.25k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3613
4.25k
                });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3603
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3604
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3605
0
                        LOG_WARNING("failed to recycle tablet")
3606
0
                                .tag("instance_id", instance_id_)
3607
0
                                .tag("tablet_id", tid);
3608
0
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3609
0
                    }
3610
4.00k
                    ++num_recycled;
3611
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3612
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3613
4.00k
                });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3603
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3604
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3605
2
                        LOG_WARNING("failed to recycle tablet")
3606
2
                                .tag("instance_id", instance_id_)
3607
2
                                .tag("tablet_id", tid);
3608
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3609
2
                    }
3610
248
                    ++num_recycled;
3611
248
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3612
248
                    return {.tablet_meta_key = k, .tablet_id = tid};
3613
250
                });
3614
4.25k
        return 0;
3615
4.25k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3584
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3585
8.00k
        ++num_scanned;
3586
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
3587
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3588
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3589
0
            has_failure = true;
3590
0
            return -1;
3591
0
        }
3592
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3593
3594
8.00k
        if (config::enable_recycler_check_lazy_txn_finished &&
3595
8.00k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3596
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3597
4.00k
            has_failure = true;
3598
4.00k
            return -1;
3599
4.00k
        }
3600
3601
8.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3602
4.00k
        sync_executor.add(
3603
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3604
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3605
4.00k
                        LOG_WARNING("failed to recycle tablet")
3606
4.00k
                                .tag("instance_id", instance_id_)
3607
4.00k
                                .tag("tablet_id", tid);
3608
4.00k
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3609
4.00k
                    }
3610
4.00k
                    ++num_recycled;
3611
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3612
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3613
4.00k
                });
3614
4.00k
        return 0;
3615
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3584
251
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3585
251
        ++num_scanned;
3586
251
        doris::TabletMetaCloudPB tablet_meta_pb;
3587
251
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3588
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3589
0
            has_failure = true;
3590
0
            return -1;
3591
0
        }
3592
251
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3593
3594
251
        if (config::enable_recycler_check_lazy_txn_finished &&
3595
251
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3596
1
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3597
1
            has_failure = true;
3598
1
            return -1;
3599
1
        }
3600
3601
251
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3602
250
        sync_executor.add(
3603
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3604
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3605
250
                        LOG_WARNING("failed to recycle tablet")
3606
250
                                .tag("instance_id", instance_id_)
3607
250
                                .tag("tablet_id", tid);
3608
250
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3609
250
                    }
3610
250
                    ++num_recycled;
3611
250
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3612
250
                    return {.tablet_meta_key = k, .tablet_id = tid};
3613
250
                });
3614
250
        return 0;
3615
250
    };
3616
3617
54
    auto loop_done = [&, this]() -> int {
3618
52
        int ret = 0;
3619
52
        bool finished = true;
3620
52
        bool has_empty_key = false;
3621
52
        DORIS_CLOUD_DEFER {
3622
52
            init_rs_keys.clear();
3623
52
            has_failure = false;
3624
52
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3621
4
        DORIS_CLOUD_DEFER {
3622
4
            init_rs_keys.clear();
3623
4
            has_failure = false;
3624
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3621
48
        DORIS_CLOUD_DEFER {
3622
48
            init_rs_keys.clear();
3623
48
            has_failure = false;
3624
48
        };
3625
52
        auto tablets_info = sync_executor.when_all(&finished);
3626
52
        if (!finished) {
3627
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3628
1
            return -1;
3629
1
        }
3630
3631
51
        size_t size_before_erase = tablets_info.size();
3632
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
3632
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
3632
249
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3633
51
        if (tablets_info.empty()) {
3634
2
            return size_before_erase == 0 ? 0 : -1;
3635
49
        } else if (size_before_erase != tablets_info.size()) {
3636
1
            has_empty_key = true;
3637
1
        }
3638
3639
49
        ret = has_empty_key ? -1 : 0;
3640
        // sort the vector using key's order
3641
49.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3642
49.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3643
49.4k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3641
48.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3642
48.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3643
48.4k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3641
958
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3642
958
            return prev.tablet_meta_key < last.tablet_meta_key;
3643
958
        });
3644
49
        std::unique_ptr<Transaction> txn;
3645
49
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3646
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3647
0
            return -1;
3648
0
        }
3649
49
        std::string tablet_key_end;
3650
49
        if (!tablets_info.empty()) {
3651
49
            if (!has_empty_key && !has_failure) {
3652
47
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3653
47
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3654
47
            } else {
3655
8
                for (auto& tablet_info : tablets_info) {
3656
8
                    txn->remove(tablet_info.tablet_meta_key);
3657
8
                }
3658
2
            }
3659
49
        }
3660
49
        if (is_multi_version) {
3661
6
            for (auto& tablet_info : tablets_info) {
3662
                // Remove all versions of tablet compact stats for recycled tablet
3663
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3664
6
                LOG_INFO("remove versioned tablet compact stats key")
3665
6
                        .tag("compact_stats_key", hex(k));
3666
6
                versioned_remove_all(txn.get(), k);
3667
6
            }
3668
6
            for (auto& tablet_info : tablets_info) {
3669
                // Remove all versions of tablet load stats for recycled tablet
3670
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3671
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3672
6
                versioned_remove_all(txn.get(), k);
3673
6
            }
3674
6
            for (auto& tablet_info : tablets_info) {
3675
                // Remove all versions of meta tablet for recycled tablet
3676
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3677
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3678
6
                versioned_remove_all(txn.get(), k);
3679
6
            }
3680
5
        }
3681
4.25k
        for (auto& tablet_info : tablets_info) {
3682
4.25k
            std::string k;
3683
4.25k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3684
4.25k
            txn->remove(k);
3685
4.25k
        }
3686
4.25k
        for (auto& tablet_info : tablets_info) {
3687
4.25k
            std::string k;
3688
4.25k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3689
4.25k
            txn->remove(k);
3690
4.25k
        }
3691
49
        for (auto& k : init_rs_keys) {
3692
0
            txn->remove(k);
3693
0
        }
3694
49
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3695
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3696
0
                         << ", err=" << err;
3697
0
            return -1;
3698
0
        }
3699
49
        return ret;
3700
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3617
4
    auto loop_done = [&, this]() -> int {
3618
4
        int ret = 0;
3619
4
        bool finished = true;
3620
4
        bool has_empty_key = false;
3621
4
        DORIS_CLOUD_DEFER {
3622
4
            init_rs_keys.clear();
3623
4
            has_failure = false;
3624
4
        };
3625
4
        auto tablets_info = sync_executor.when_all(&finished);
3626
4
        if (!finished) {
3627
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3628
0
            return -1;
3629
0
        }
3630
3631
4
        size_t size_before_erase = tablets_info.size();
3632
4
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3633
4
        if (tablets_info.empty()) {
3634
2
            return size_before_erase == 0 ? 0 : -1;
3635
2
        } else if (size_before_erase != tablets_info.size()) {
3636
0
            has_empty_key = true;
3637
0
        }
3638
3639
2
        ret = has_empty_key ? -1 : 0;
3640
        // sort the vector using key's order
3641
2
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3642
2
            return prev.tablet_meta_key < last.tablet_meta_key;
3643
2
        });
3644
2
        std::unique_ptr<Transaction> txn;
3645
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3646
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3647
0
            return -1;
3648
0
        }
3649
2
        std::string tablet_key_end;
3650
2
        if (!tablets_info.empty()) {
3651
2
            if (!has_empty_key && !has_failure) {
3652
2
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3653
2
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3654
2
            } else {
3655
0
                for (auto& tablet_info : tablets_info) {
3656
0
                    txn->remove(tablet_info.tablet_meta_key);
3657
0
                }
3658
0
            }
3659
2
        }
3660
2
        if (is_multi_version) {
3661
0
            for (auto& tablet_info : tablets_info) {
3662
                // Remove all versions of tablet compact stats for recycled tablet
3663
0
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3664
0
                LOG_INFO("remove versioned tablet compact stats key")
3665
0
                        .tag("compact_stats_key", hex(k));
3666
0
                versioned_remove_all(txn.get(), k);
3667
0
            }
3668
0
            for (auto& tablet_info : tablets_info) {
3669
                // Remove all versions of tablet load stats for recycled tablet
3670
0
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3671
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3672
0
                versioned_remove_all(txn.get(), k);
3673
0
            }
3674
0
            for (auto& tablet_info : tablets_info) {
3675
                // Remove all versions of meta tablet for recycled tablet
3676
0
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3677
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3678
0
                versioned_remove_all(txn.get(), k);
3679
0
            }
3680
0
        }
3681
4.00k
        for (auto& tablet_info : tablets_info) {
3682
4.00k
            std::string k;
3683
4.00k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3684
4.00k
            txn->remove(k);
3685
4.00k
        }
3686
4.00k
        for (auto& tablet_info : tablets_info) {
3687
4.00k
            std::string k;
3688
4.00k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3689
4.00k
            txn->remove(k);
3690
4.00k
        }
3691
2
        for (auto& k : init_rs_keys) {
3692
0
            txn->remove(k);
3693
0
        }
3694
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3695
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3696
0
                         << ", err=" << err;
3697
0
            return -1;
3698
0
        }
3699
2
        return ret;
3700
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3617
48
    auto loop_done = [&, this]() -> int {
3618
48
        int ret = 0;
3619
48
        bool finished = true;
3620
48
        bool has_empty_key = false;
3621
48
        DORIS_CLOUD_DEFER {
3622
48
            init_rs_keys.clear();
3623
48
            has_failure = false;
3624
48
        };
3625
48
        auto tablets_info = sync_executor.when_all(&finished);
3626
48
        if (!finished) {
3627
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3628
1
            return -1;
3629
1
        }
3630
3631
47
        size_t size_before_erase = tablets_info.size();
3632
47
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3633
47
        if (tablets_info.empty()) {
3634
0
            return size_before_erase == 0 ? 0 : -1;
3635
47
        } else if (size_before_erase != tablets_info.size()) {
3636
1
            has_empty_key = true;
3637
1
        }
3638
3639
47
        ret = has_empty_key ? -1 : 0;
3640
        // sort the vector using key's order
3641
47
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3642
47
            return prev.tablet_meta_key < last.tablet_meta_key;
3643
47
        });
3644
47
        std::unique_ptr<Transaction> txn;
3645
47
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3646
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3647
0
            return -1;
3648
0
        }
3649
47
        std::string tablet_key_end;
3650
47
        if (!tablets_info.empty()) {
3651
47
            if (!has_empty_key && !has_failure) {
3652
45
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3653
45
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3654
45
            } else {
3655
8
                for (auto& tablet_info : tablets_info) {
3656
8
                    txn->remove(tablet_info.tablet_meta_key);
3657
8
                }
3658
2
            }
3659
47
        }
3660
47
        if (is_multi_version) {
3661
6
            for (auto& tablet_info : tablets_info) {
3662
                // Remove all versions of tablet compact stats for recycled tablet
3663
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3664
6
                LOG_INFO("remove versioned tablet compact stats key")
3665
6
                        .tag("compact_stats_key", hex(k));
3666
6
                versioned_remove_all(txn.get(), k);
3667
6
            }
3668
6
            for (auto& tablet_info : tablets_info) {
3669
                // Remove all versions of tablet load stats for recycled tablet
3670
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3671
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3672
6
                versioned_remove_all(txn.get(), k);
3673
6
            }
3674
6
            for (auto& tablet_info : tablets_info) {
3675
                // Remove all versions of meta tablet for recycled tablet
3676
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3677
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3678
6
                versioned_remove_all(txn.get(), k);
3679
6
            }
3680
5
        }
3681
248
        for (auto& tablet_info : tablets_info) {
3682
248
            std::string k;
3683
248
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3684
248
            txn->remove(k);
3685
248
        }
3686
248
        for (auto& tablet_info : tablets_info) {
3687
248
            std::string k;
3688
248
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3689
248
            txn->remove(k);
3690
248
        }
3691
47
        for (auto& k : init_rs_keys) {
3692
0
            txn->remove(k);
3693
0
        }
3694
47
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3695
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3696
0
                         << ", err=" << err;
3697
0
            return -1;
3698
0
        }
3699
47
        return ret;
3700
47
    };
3701
3702
54
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
3703
54
                               std::move(loop_done));
3704
54
    if (ret != 0) {
3705
5
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
3706
5
        return ret;
3707
5
    }
3708
3709
    // directly remove tablet stats and tablet jobs of these dropped index or partition
3710
49
    std::unique_ptr<Transaction> txn;
3711
49
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3712
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
3713
0
        return -1;
3714
0
    }
3715
49
    txn->remove(stats_key_begin, stats_key_end);
3716
49
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
3717
49
                 << " end=" << hex(stats_key_end);
3718
49
    txn->remove(job_key_begin, job_key_end);
3719
49
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
3720
49
    std::string schema_key_begin, schema_key_end;
3721
49
    std::string schema_dict_key;
3722
49
    std::string versioned_schema_key_begin, versioned_schema_key_end;
3723
49
    if (partition_id <= 0) {
3724
        // Delete schema kv of this index
3725
15
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
3726
15
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
3727
15
        txn->remove(schema_key_begin, schema_key_end);
3728
15
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
3729
15
                     << " end=" << hex(schema_key_end);
3730
15
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
3731
15
        txn->remove(schema_dict_key);
3732
15
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
3733
15
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
3734
15
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
3735
15
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
3736
15
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
3737
15
                     << " end=" << hex(versioned_schema_key_end);
3738
15
    }
3739
3740
49
    TxnErrorCode err = txn->commit();
3741
49
    if (err != TxnErrorCode::TXN_OK) {
3742
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
3743
0
                     << " err=" << err;
3744
0
        return -1;
3745
0
    }
3746
3747
49
    return ret;
3748
49
}
3749
3750
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
3751
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
3752
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
3753
5.61k
    if (num_segments <= 0) return 0;
3754
3755
5.61k
    std::vector<std::string> file_paths;
3756
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
3757
0
        return -1;
3758
0
    }
3759
3760
    // Process inverted indexes
3761
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
3762
5.61k
    InvertedIndexStorageFormatPB index_format = rs_meta_pb.has_inverted_index_storage_format()
3763
5.61k
                                                        ? rs_meta_pb.inverted_index_storage_format()
3764
5.61k
                                                        : InvertedIndexStorageFormatPB::V1;
3765
5.61k
    bool delete_rowset_data_by_prefix = false;
3766
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3767
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3768
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3769
0
        delete_rowset_data_by_prefix = true;
3770
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
3771
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
3772
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3773
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3774
10.0k
            }
3775
10.0k
        }
3776
4.80k
        if (!rs_meta_pb.has_inverted_index_storage_format() &&
3777
4.80k
            rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
3778
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
3779
2.00k
        }
3780
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
3781
        // schema version and index id are not found, delete rowset data by prefix directly.
3782
0
        delete_rowset_data_by_prefix = true;
3783
809
    } else {
3784
        // otherwise, try to get schema kv
3785
809
        InvertedIndexInfo index_info;
3786
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
3787
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
3788
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3789
809
                                 &inverted_index_get_ret);
3790
809
        if (inverted_index_get_ret == 0) {
3791
809
            if (!rs_meta_pb.has_inverted_index_storage_format()) {
3792
809
                index_format = index_info.first;
3793
809
            }
3794
809
            index_ids = index_info.second;
3795
809
        } else if (inverted_index_get_ret == 1) {
3796
            // 1. Schema kv not found means tablet has been recycled
3797
            // Maybe some tablet recycle failed by some bugs
3798
            // We need to delete again to double check
3799
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3800
            // because we are uncertain about the inverted index information.
3801
            // If there are inverted indexes, some data might not be deleted,
3802
            // but this is acceptable as we have made our best effort to delete the data.
3803
0
            LOG_INFO(
3804
0
                    "delete rowset data schema kv not found, need to delete again to double "
3805
0
                    "check")
3806
0
                    .tag("instance_id", instance_id_)
3807
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3808
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
3809
            // Currently index_ids is guaranteed to be empty,
3810
            // but we clear it again here as a safeguard against future code changes
3811
            // that might cause index_ids to no longer be empty
3812
0
            index_format = InvertedIndexStorageFormatPB::V2;
3813
0
            index_ids.clear();
3814
0
        } else {
3815
            // failed to get schema kv, delete rowset data by prefix directly.
3816
0
            delete_rowset_data_by_prefix = true;
3817
0
        }
3818
809
    }
3819
3820
5.61k
    if (delete_rowset_data_by_prefix) {
3821
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
3822
0
                                  rs_meta_pb.rowset_id_v2());
3823
0
    }
3824
3825
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
3826
5.61k
    if (it == accessor_map_.end()) {
3827
1.59k
        LOG_WARNING("instance has no such resource id")
3828
1.59k
                .tag("instance_id", instance_id_)
3829
1.59k
                .tag("resource_id", rs_meta_pb.resource_id());
3830
1.59k
        return -1;
3831
1.59k
    }
3832
4.01k
    auto& accessor = it->second;
3833
3834
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
3835
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
3836
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
3837
20.0k
        add_file_to_delete_if_not_packed(rs_meta_pb, segment_path(tablet_id, rowset_id, i),
3838
20.0k
                                         &file_paths);
3839
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
3840
40.0k
            for (const auto& index_id : index_ids) {
3841
40.0k
                add_file_to_delete_if_not_packed(
3842
40.0k
                        rs_meta_pb,
3843
40.0k
                        inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
3844
40.0k
                                               index_id.second),
3845
40.0k
                        &file_paths);
3846
40.0k
            }
3847
20.0k
        } else if (!index_ids.empty()) {
3848
0
            add_file_to_delete_if_not_packed(
3849
0
                    rs_meta_pb, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
3850
0
        }
3851
20.0k
    }
3852
3853
    // Process delete bitmap - check where it's stored.
3854
4.01k
    DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3855
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3856
4.01k
                                                       &delete_bitmap_storage_type) != 0) {
3857
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3858
0
                .tag("instance_id", instance_id_)
3859
0
                .tag("tablet_id", tablet_id)
3860
0
                .tag("rowset_id", rowset_id);
3861
0
        return -1;
3862
0
    }
3863
4.01k
    if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3864
2.00k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3865
2.00k
    }
3866
    // TODO(AlexYue): seems could do do batch
3867
4.01k
    return accessor->delete_files(file_paths);
3868
4.01k
}
3869
3870
62.6k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3871
62.6k
    LOG_INFO("begin process_packed_file_location_index")
3872
62.6k
            .tag("instance_id", instance_id_)
3873
62.6k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3874
62.6k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3875
62.6k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3876
62.6k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3877
62.6k
    if (index_map.empty()) {
3878
62.6k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3879
62.6k
                .tag("instance_id", instance_id_)
3880
62.6k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3881
62.6k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3882
62.6k
        return 0;
3883
62.6k
    }
3884
3885
14
    struct PackedSmallFileInfo {
3886
14
        std::string small_file_path;
3887
14
    };
3888
14
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3889
14
    packed_file_updates.reserve(index_map.size());
3890
27
    for (const auto& [small_path, index_pb] : index_map) {
3891
27
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3892
0
            continue;
3893
0
        }
3894
27
        packed_file_updates[index_pb.packed_file_path()].push_back(
3895
27
                PackedSmallFileInfo {small_path});
3896
27
    }
3897
14
    if (packed_file_updates.empty()) {
3898
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3899
0
                .tag("instance_id", instance_id_)
3900
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3901
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3902
0
                .tag("index_map_size", index_map.size());
3903
0
        return 0;
3904
0
    }
3905
3906
14
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3907
14
    int ret = 0;
3908
24
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3909
24
        if (small_files.empty()) {
3910
0
            continue;
3911
0
        }
3912
3913
24
        bool success = false;
3914
24
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3915
24
            std::unique_ptr<Transaction> txn;
3916
24
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3917
24
            if (err != TxnErrorCode::TXN_OK) {
3918
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3919
0
                        .tag("instance_id", instance_id_)
3920
0
                        .tag("packed_file_path", packed_file_path)
3921
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3922
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3923
0
                        .tag("err", err);
3924
0
                ret = -1;
3925
0
                break;
3926
0
            }
3927
3928
24
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3929
24
            std::string packed_val;
3930
24
            err = txn->get(packed_key, &packed_val);
3931
24
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3932
0
                LOG_WARNING("packed file info not found when recycling rowset")
3933
0
                        .tag("instance_id", instance_id_)
3934
0
                        .tag("packed_file_path", packed_file_path)
3935
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3936
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3937
0
                        .tag("key", hex(packed_key))
3938
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3939
                // Skip this packed file entry and continue with others
3940
0
                success = true;
3941
0
                break;
3942
0
            }
3943
24
            if (err != TxnErrorCode::TXN_OK) {
3944
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
3945
0
                        .tag("instance_id", instance_id_)
3946
0
                        .tag("packed_file_path", packed_file_path)
3947
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3948
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3949
0
                        .tag("err", err);
3950
0
                ret = -1;
3951
0
                break;
3952
0
            }
3953
3954
24
            cloud::PackedFileInfoPB packed_info;
3955
24
            if (!packed_info.ParseFromString(packed_val)) {
3956
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
3957
0
                        .tag("instance_id", instance_id_)
3958
0
                        .tag("packed_file_path", packed_file_path)
3959
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3960
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3961
0
                ret = -1;
3962
0
                break;
3963
0
            }
3964
3965
24
            LOG_INFO("packed file update check")
3966
24
                    .tag("instance_id", instance_id_)
3967
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3968
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3969
24
                    .tag("merged_file_path", packed_file_path)
3970
24
                    .tag("requested_small_files", small_files.size())
3971
24
                    .tag("merge_entries", packed_info.slices_size());
3972
3973
24
            auto* small_file_entries = packed_info.mutable_slices();
3974
24
            int64_t changed_files = 0;
3975
24
            int64_t missing_entries = 0;
3976
24
            int64_t already_deleted = 0;
3977
27
            for (const auto& small_file_info : small_files) {
3978
27
                bool found = false;
3979
87
                for (auto& small_file_entry : *small_file_entries) {
3980
87
                    if (small_file_entry.path() == small_file_info.small_file_path) {
3981
27
                        if (!small_file_entry.deleted()) {
3982
27
                            small_file_entry.set_deleted(true);
3983
27
                            if (!small_file_entry.corrected()) {
3984
27
                                small_file_entry.set_corrected(true);
3985
27
                            }
3986
27
                            ++changed_files;
3987
27
                        } else {
3988
0
                            ++already_deleted;
3989
0
                        }
3990
27
                        found = true;
3991
27
                        break;
3992
27
                    }
3993
87
                }
3994
27
                if (!found) {
3995
0
                    ++missing_entries;
3996
0
                    LOG_WARNING("packed file info missing small file entry")
3997
0
                            .tag("instance_id", instance_id_)
3998
0
                            .tag("packed_file_path", packed_file_path)
3999
0
                            .tag("small_file_path", small_file_info.small_file_path)
4000
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4001
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
4002
0
                }
4003
27
            }
4004
4005
24
            if (changed_files == 0) {
4006
0
                LOG_INFO("skip merge file update: no merge entries changed")
4007
0
                        .tag("instance_id", instance_id_)
4008
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4009
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4010
0
                        .tag("merged_file_path", packed_file_path)
4011
0
                        .tag("missing_entries", missing_entries)
4012
0
                        .tag("already_deleted", already_deleted)
4013
0
                        .tag("requested_small_files", small_files.size())
4014
0
                        .tag("merge_entries", packed_info.slices_size());
4015
0
                success = true;
4016
0
                break;
4017
0
            }
4018
4019
            // Calculate remaining files
4020
24
            int64_t left_file_count = 0;
4021
24
            int64_t left_file_bytes = 0;
4022
141
            for (const auto& small_file_entry : packed_info.slices()) {
4023
141
                if (!small_file_entry.deleted()) {
4024
57
                    ++left_file_count;
4025
57
                    left_file_bytes += small_file_entry.size();
4026
57
                }
4027
141
            }
4028
24
            packed_info.set_remaining_slice_bytes(left_file_bytes);
4029
24
            packed_info.set_ref_cnt(left_file_count);
4030
24
            LOG_INFO("updated packed file reference info")
4031
24
                    .tag("instance_id", instance_id_)
4032
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4033
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
4034
24
                    .tag("packed_file_path", packed_file_path)
4035
24
                    .tag("ref_cnt", left_file_count)
4036
24
                    .tag("left_file_bytes", left_file_bytes);
4037
4038
24
            if (left_file_count == 0) {
4039
7
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
4040
7
            }
4041
4042
24
            std::string updated_val;
4043
24
            if (!packed_info.SerializeToString(&updated_val)) {
4044
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
4045
0
                        .tag("instance_id", instance_id_)
4046
0
                        .tag("packed_file_path", packed_file_path)
4047
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4048
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
4049
0
                ret = -1;
4050
0
                break;
4051
0
            }
4052
4053
24
            txn->put(packed_key, updated_val);
4054
24
            err = txn->commit();
4055
24
            if (err == TxnErrorCode::TXN_OK) {
4056
24
                success = true;
4057
24
                if (left_file_count == 0) {
4058
7
                    LOG_INFO("packed file ready to delete, deleting immediately")
4059
7
                            .tag("instance_id", instance_id_)
4060
7
                            .tag("packed_file_path", packed_file_path);
4061
7
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4062
0
                        ret = -1;
4063
0
                    }
4064
7
                }
4065
24
                break;
4066
24
            }
4067
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
4068
0
                if (attempt >= max_retry_times) {
4069
0
                    LOG_WARNING("packed file info update conflict after max retry")
4070
0
                            .tag("instance_id", instance_id_)
4071
0
                            .tag("packed_file_path", packed_file_path)
4072
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4073
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
4074
0
                            .tag("changed_files", changed_files)
4075
0
                            .tag("attempt", attempt);
4076
0
                    ret = -1;
4077
0
                    break;
4078
0
                }
4079
0
                LOG_WARNING("packed file info update conflict, retrying")
4080
0
                        .tag("instance_id", instance_id_)
4081
0
                        .tag("packed_file_path", packed_file_path)
4082
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4083
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4084
0
                        .tag("changed_files", changed_files)
4085
0
                        .tag("attempt", attempt);
4086
0
                sleep_for_packed_file_retry();
4087
0
                continue;
4088
0
            }
4089
4090
0
            LOG_WARNING("failed to commit packed file info update")
4091
0
                    .tag("instance_id", instance_id_)
4092
0
                    .tag("packed_file_path", packed_file_path)
4093
0
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4094
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
4095
0
                    .tag("err", err)
4096
0
                    .tag("changed_files", changed_files);
4097
0
            ret = -1;
4098
0
            break;
4099
0
        }
4100
4101
24
        if (!success) {
4102
0
            ret = -1;
4103
0
        }
4104
24
    }
4105
4106
14
    return ret;
4107
14
}
4108
4109
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(
4110
        int64_t tablet_id, const std::string& rowset_id,
4111
58.5k
        DeleteBitmapStorageType* out_storage_type) {
4112
58.5k
    if (out_storage_type) {
4113
58.5k
        *out_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4114
58.5k
    }
4115
4116
    // Get delete bitmap storage info from FDB
4117
58.5k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4118
58.5k
    std::unique_ptr<Transaction> txn;
4119
58.5k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
4120
58.5k
    if (err != TxnErrorCode::TXN_OK) {
4121
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
4122
0
                .tag("instance_id", instance_id_)
4123
0
                .tag("tablet_id", tablet_id)
4124
0
                .tag("rowset_id", rowset_id)
4125
0
                .tag("err", err);
4126
0
        return -1;
4127
0
    }
4128
4129
58.5k
    ValueBuf dbm_val;
4130
58.5k
    err = cloud::blob_get(txn.get(), dbm_key, &dbm_val);
4131
58.5k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4132
        // No delete bitmap for this rowset, nothing to do
4133
4.92k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
4134
4.92k
                .tag("instance_id", instance_id_)
4135
4.92k
                .tag("tablet_id", tablet_id)
4136
4.92k
                .tag("rowset_id", rowset_id);
4137
4.92k
        return 0;
4138
4.92k
    }
4139
53.5k
    if (err != TxnErrorCode::TXN_OK) {
4140
0
        LOG_WARNING("failed to get delete bitmap storage")
4141
0
                .tag("instance_id", instance_id_)
4142
0
                .tag("tablet_id", tablet_id)
4143
0
                .tag("rowset_id", rowset_id)
4144
0
                .tag("err", err);
4145
0
        return -1;
4146
0
    }
4147
4148
53.5k
    DeleteBitmapStoragePB storage;
4149
53.5k
    if (!dbm_val.to_pb(&storage)) {
4150
0
        LOG_WARNING("failed to parse delete bitmap storage")
4151
0
                .tag("instance_id", instance_id_)
4152
0
                .tag("tablet_id", tablet_id)
4153
0
                .tag("rowset_id", rowset_id);
4154
0
        return -1;
4155
0
    }
4156
4157
53.5k
    if (storage.store_in_fdb()) {
4158
0
        if (out_storage_type) {
4159
0
            *out_storage_type = DeleteBitmapStorageType::IN_FDB;
4160
0
        }
4161
0
        return 0;
4162
0
    }
4163
4164
    // Check if delete bitmap is stored in standalone file.
4165
53.5k
    if (!storage.has_packed_slice_location() ||
4166
53.5k
        storage.packed_slice_location().packed_file_path().empty()) {
4167
53.5k
        if (out_storage_type) {
4168
53.5k
            *out_storage_type = DeleteBitmapStorageType::STANDALONE_FILE;
4169
53.5k
        }
4170
53.5k
        return 0;
4171
53.5k
    }
4172
4173
18.4E
    if (out_storage_type) {
4174
0
        *out_storage_type = DeleteBitmapStorageType::PACKED_FILE;
4175
0
    }
4176
4177
18.4E
    const auto& packed_loc = storage.packed_slice_location();
4178
18.4E
    const std::string& packed_file_path = packed_loc.packed_file_path();
4179
4180
18.4E
    LOG_INFO("decrementing delete bitmap packed file ref count")
4181
18.4E
            .tag("instance_id", instance_id_)
4182
18.4E
            .tag("tablet_id", tablet_id)
4183
18.4E
            .tag("rowset_id", rowset_id)
4184
18.4E
            .tag("packed_file_path", packed_file_path);
4185
4186
18.4E
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
4187
18.4E
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4188
0
        std::unique_ptr<Transaction> update_txn;
4189
0
        err = txn_kv_->create_txn(&update_txn);
4190
0
        if (err != TxnErrorCode::TXN_OK) {
4191
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
4192
0
                    .tag("instance_id", instance_id_)
4193
0
                    .tag("tablet_id", tablet_id)
4194
0
                    .tag("rowset_id", rowset_id)
4195
0
                    .tag("err", err);
4196
0
            return -1;
4197
0
        }
4198
4199
0
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
4200
0
        std::string packed_val;
4201
0
        err = update_txn->get(packed_key, &packed_val);
4202
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4203
0
            LOG_WARNING("packed file info not found for delete bitmap")
4204
0
                    .tag("instance_id", instance_id_)
4205
0
                    .tag("tablet_id", tablet_id)
4206
0
                    .tag("rowset_id", rowset_id)
4207
0
                    .tag("packed_file_path", packed_file_path);
4208
0
            return 0;
4209
0
        }
4210
0
        if (err != TxnErrorCode::TXN_OK) {
4211
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
4212
0
                    .tag("instance_id", instance_id_)
4213
0
                    .tag("tablet_id", tablet_id)
4214
0
                    .tag("rowset_id", rowset_id)
4215
0
                    .tag("packed_file_path", packed_file_path)
4216
0
                    .tag("err", err);
4217
0
            return -1;
4218
0
        }
4219
4220
0
        cloud::PackedFileInfoPB packed_info;
4221
0
        if (!packed_info.ParseFromString(packed_val)) {
4222
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
4223
0
                    .tag("instance_id", instance_id_)
4224
0
                    .tag("tablet_id", tablet_id)
4225
0
                    .tag("rowset_id", rowset_id)
4226
0
                    .tag("packed_file_path", packed_file_path);
4227
0
            return -1;
4228
0
        }
4229
4230
        // Find and mark the small file entry as deleted
4231
        // Use tablet_id and rowset_id to match entry instead of path,
4232
        // because path format may vary with path_version (with or without shard prefix)
4233
0
        auto* entries = packed_info.mutable_slices();
4234
0
        bool found = false;
4235
0
        bool already_deleted = false;
4236
0
        for (auto& entry : *entries) {
4237
0
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
4238
0
                if (!entry.deleted()) {
4239
0
                    entry.set_deleted(true);
4240
0
                    if (!entry.corrected()) {
4241
0
                        entry.set_corrected(true);
4242
0
                    }
4243
0
                } else {
4244
0
                    already_deleted = true;
4245
0
                }
4246
0
                found = true;
4247
0
                break;
4248
0
            }
4249
0
        }
4250
4251
0
        if (!found) {
4252
0
            LOG_WARNING("delete bitmap entry not found in packed file")
4253
0
                    .tag("instance_id", instance_id_)
4254
0
                    .tag("tablet_id", tablet_id)
4255
0
                    .tag("rowset_id", rowset_id)
4256
0
                    .tag("packed_file_path", packed_file_path);
4257
0
            return 0;
4258
0
        }
4259
4260
0
        if (already_deleted) {
4261
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
4262
0
                    .tag("instance_id", instance_id_)
4263
0
                    .tag("tablet_id", tablet_id)
4264
0
                    .tag("rowset_id", rowset_id)
4265
0
                    .tag("packed_file_path", packed_file_path);
4266
0
            return 0;
4267
0
        }
4268
4269
        // Calculate remaining files
4270
0
        int64_t left_file_count = 0;
4271
0
        int64_t left_file_bytes = 0;
4272
0
        for (const auto& entry : packed_info.slices()) {
4273
0
            if (!entry.deleted()) {
4274
0
                ++left_file_count;
4275
0
                left_file_bytes += entry.size();
4276
0
            }
4277
0
        }
4278
0
        packed_info.set_remaining_slice_bytes(left_file_bytes);
4279
0
        packed_info.set_ref_cnt(left_file_count);
4280
4281
0
        if (left_file_count == 0) {
4282
0
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
4283
0
        }
4284
4285
0
        std::string updated_val;
4286
0
        if (!packed_info.SerializeToString(&updated_val)) {
4287
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
4288
0
                    .tag("instance_id", instance_id_)
4289
0
                    .tag("tablet_id", tablet_id)
4290
0
                    .tag("rowset_id", rowset_id)
4291
0
                    .tag("packed_file_path", packed_file_path);
4292
0
            return -1;
4293
0
        }
4294
4295
0
        update_txn->put(packed_key, updated_val);
4296
0
        err = update_txn->commit();
4297
0
        if (err == TxnErrorCode::TXN_OK) {
4298
0
            LOG_INFO("delete bitmap packed file ref count decremented")
4299
0
                    .tag("instance_id", instance_id_)
4300
0
                    .tag("tablet_id", tablet_id)
4301
0
                    .tag("rowset_id", rowset_id)
4302
0
                    .tag("packed_file_path", packed_file_path)
4303
0
                    .tag("left_file_count", left_file_count);
4304
0
            if (left_file_count == 0) {
4305
0
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4306
0
                    return -1;
4307
0
                }
4308
0
            }
4309
0
            return 0;
4310
0
        }
4311
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4312
0
            if (attempt >= max_retry_times) {
4313
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
4314
0
                        .tag("instance_id", instance_id_)
4315
0
                        .tag("tablet_id", tablet_id)
4316
0
                        .tag("rowset_id", rowset_id)
4317
0
                        .tag("packed_file_path", packed_file_path)
4318
0
                        .tag("attempt", attempt);
4319
0
                return -1;
4320
0
            }
4321
0
            sleep_for_packed_file_retry();
4322
0
            continue;
4323
0
        }
4324
4325
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
4326
0
                .tag("instance_id", instance_id_)
4327
0
                .tag("tablet_id", tablet_id)
4328
0
                .tag("rowset_id", rowset_id)
4329
0
                .tag("packed_file_path", packed_file_path)
4330
0
                .tag("err", err);
4331
0
        return -1;
4332
0
    }
4333
4334
18.4E
    return -1;
4335
18.4E
}
4336
4337
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
4338
                                                const std::string& packed_key,
4339
7
                                                const cloud::PackedFileInfoPB& packed_info) {
4340
7
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
4341
0
        LOG_WARNING("packed file missing resource id when recycling")
4342
0
                .tag("instance_id", instance_id_)
4343
0
                .tag("packed_file_path", packed_file_path);
4344
0
        return -1;
4345
0
    }
4346
4347
7
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
4348
7
    if (!accessor) {
4349
0
        LOG_WARNING("no accessor available to delete packed file")
4350
0
                .tag("instance_id", instance_id_)
4351
0
                .tag("packed_file_path", packed_file_path)
4352
0
                .tag("resource_id", packed_info.resource_id());
4353
0
        return -1;
4354
0
    }
4355
4356
7
    int del_ret = accessor->delete_file(packed_file_path);
4357
7
    if (del_ret != 0 && del_ret != 1) {
4358
0
        LOG_WARNING("failed to delete packed file")
4359
0
                .tag("instance_id", instance_id_)
4360
0
                .tag("packed_file_path", packed_file_path)
4361
0
                .tag("resource_id", resource_id)
4362
0
                .tag("ret", del_ret);
4363
0
        return -1;
4364
0
    }
4365
7
    if (del_ret == 1) {
4366
0
        LOG_INFO("packed file already removed")
4367
0
                .tag("instance_id", instance_id_)
4368
0
                .tag("packed_file_path", packed_file_path)
4369
0
                .tag("resource_id", resource_id);
4370
7
    } else {
4371
7
        LOG_INFO("deleted packed file")
4372
7
                .tag("instance_id", instance_id_)
4373
7
                .tag("packed_file_path", packed_file_path)
4374
7
                .tag("resource_id", resource_id);
4375
7
    }
4376
4377
7
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
4378
7
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4379
7
        std::unique_ptr<Transaction> del_txn;
4380
7
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
4381
7
        if (err != TxnErrorCode::TXN_OK) {
4382
0
            LOG_WARNING("failed to create txn when removing packed file kv")
4383
0
                    .tag("instance_id", instance_id_)
4384
0
                    .tag("packed_file_path", packed_file_path)
4385
0
                    .tag("attempt", attempt)
4386
0
                    .tag("err", err);
4387
0
            return -1;
4388
0
        }
4389
4390
7
        std::string latest_val;
4391
7
        err = del_txn->get(packed_key, &latest_val);
4392
7
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4393
0
            return 0;
4394
0
        }
4395
7
        if (err != TxnErrorCode::TXN_OK) {
4396
0
            LOG_WARNING("failed to re-read packed file kv before removal")
4397
0
                    .tag("instance_id", instance_id_)
4398
0
                    .tag("packed_file_path", packed_file_path)
4399
0
                    .tag("attempt", attempt)
4400
0
                    .tag("err", err);
4401
0
            return -1;
4402
0
        }
4403
4404
7
        cloud::PackedFileInfoPB latest_info;
4405
7
        if (!latest_info.ParseFromString(latest_val)) {
4406
0
            LOG_WARNING("failed to parse packed file info before removal")
4407
0
                    .tag("instance_id", instance_id_)
4408
0
                    .tag("packed_file_path", packed_file_path)
4409
0
                    .tag("attempt", attempt);
4410
0
            return -1;
4411
0
        }
4412
4413
7
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
4414
7
              latest_info.ref_cnt() == 0)) {
4415
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
4416
0
                    .tag("instance_id", instance_id_)
4417
0
                    .tag("packed_file_path", packed_file_path)
4418
0
                    .tag("attempt", attempt);
4419
0
            return 0;
4420
0
        }
4421
4422
7
        del_txn->remove(packed_key);
4423
7
        err = del_txn->commit();
4424
7
        if (err == TxnErrorCode::TXN_OK) {
4425
7
            LOG_INFO("removed packed file metadata")
4426
7
                    .tag("instance_id", instance_id_)
4427
7
                    .tag("packed_file_path", packed_file_path);
4428
7
            return 0;
4429
7
        }
4430
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4431
0
            if (attempt >= max_retry_times) {
4432
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
4433
0
                        .tag("instance_id", instance_id_)
4434
0
                        .tag("packed_file_path", packed_file_path)
4435
0
                        .tag("attempt", attempt);
4436
0
                return -1;
4437
0
            }
4438
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
4439
0
                    .tag("instance_id", instance_id_)
4440
0
                    .tag("packed_file_path", packed_file_path)
4441
0
                    .tag("attempt", attempt);
4442
0
            sleep_for_packed_file_retry();
4443
0
            continue;
4444
0
        }
4445
0
        LOG_WARNING("failed to remove packed file kv")
4446
0
                .tag("instance_id", instance_id_)
4447
0
                .tag("packed_file_path", packed_file_path)
4448
0
                .tag("attempt", attempt)
4449
0
                .tag("err", err);
4450
0
        return -1;
4451
0
    }
4452
0
    return -1;
4453
7
}
4454
4455
int InstanceRecycler::delete_rowset_data(
4456
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
4457
65
        RecyclerMetricsContext& metrics_context) {
4458
65
    int ret = 0;
4459
    // resource_id -> file_paths
4460
65
    std::map<std::string, std::vector<std::string>> resource_file_paths;
4461
    // (resource_id, tablet_id, rowset_id)
4462
65
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
4463
65
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
4464
4465
56.4k
    for (const auto& [_, rs] : rowsets) {
4466
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
4467
        // due to aborted schema change.
4468
56.4k
        if (is_formal_rowset) {
4469
3.19k
            std::lock_guard lock(recycled_tablets_mtx_);
4470
3.19k
            if (recycled_tablets_.count(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
4471
                // Tablet has been recycled and this rowset has no packed slices, so file data
4472
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
4473
                // slice info must still run to decrement packed file ref counts.
4474
0
                continue;
4475
0
            }
4476
3.19k
        }
4477
4478
56.4k
        int64_t num_segments = rs.num_segments();
4479
        // Check num_segments before accessor lookup, because empty rowsets
4480
        // (e.g. base compaction output of empty rowsets) may have no resource_id
4481
        // set. Skipping them early avoids a spurious "no such resource id" error
4482
        // that marks the entire batch as failed and prevents txn_remove from
4483
        // cleaning up recycle KV keys.
4484
56.4k
        if (num_segments <= 0) {
4485
0
            metrics_context.total_recycled_num++;
4486
0
            metrics_context.total_recycled_data_size += rs.total_disk_size();
4487
0
            continue;
4488
0
        }
4489
4490
56.4k
        auto it = accessor_map_.find(rs.resource_id());
4491
        // possible if the accessor is not initilized correctly
4492
56.4k
        if (it == accessor_map_.end()) [[unlikely]] {
4493
2.00k
            LOG_WARNING("instance has no such resource id")
4494
2.00k
                    .tag("instance_id", instance_id_)
4495
2.00k
                    .tag("resource_id", rs.resource_id());
4496
2.00k
            ret = -1;
4497
2.00k
            continue;
4498
2.00k
        }
4499
4500
54.4k
        auto& file_paths = resource_file_paths[rs.resource_id()];
4501
54.4k
        const auto& rowset_id = rs.rowset_id_v2();
4502
54.4k
        int64_t tablet_id = rs.tablet_id();
4503
54.4k
        LOG_INFO("recycle rowset merge index size")
4504
54.4k
                .tag("instance_id", instance_id_)
4505
54.4k
                .tag("tablet_id", tablet_id)
4506
54.4k
                .tag("rowset_id", rowset_id)
4507
54.4k
                .tag("merge_index_size", rs.packed_slice_locations_size());
4508
54.4k
        if (decrement_packed_file_ref_counts(rs) != 0) {
4509
0
            ret = -1;
4510
0
            continue;
4511
0
        }
4512
4513
        // Process delete bitmap - check where it's stored.
4514
54.4k
        DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4515
54.4k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
4516
54.4k
                                                           &delete_bitmap_storage_type) != 0) {
4517
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
4518
0
                    .tag("instance_id", instance_id_)
4519
0
                    .tag("tablet_id", tablet_id)
4520
0
                    .tag("rowset_id", rowset_id);
4521
0
            ret = -1;
4522
0
            continue;
4523
0
        }
4524
54.4k
        if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
4525
51.5k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
4526
51.5k
        }
4527
4528
        // Process inverted indexes
4529
54.4k
        std::vector<std::pair<int64_t, std::string>> index_ids;
4530
        // default format as v1.
4531
54.4k
        InvertedIndexStorageFormatPB index_format = rs.has_inverted_index_storage_format()
4532
54.4k
                                                            ? rs.inverted_index_storage_format()
4533
54.4k
                                                            : InvertedIndexStorageFormatPB::V1;
4534
54.4k
        int inverted_index_get_ret = 0;
4535
54.4k
        if (rs.has_tablet_schema()) {
4536
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
4537
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
4538
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
4539
53.5k
                }
4540
53.5k
            }
4541
26.8k
            if (!rs.has_inverted_index_storage_format() &&
4542
26.8k
                rs.tablet_schema().has_inverted_index_storage_format()) {
4543
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
4544
26.5k
            }
4545
27.6k
        } else {
4546
27.6k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
4547
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
4548
0
                                "instance_id="
4549
0
                             << instance_id_ << " tablet_id=" << tablet_id
4550
0
                             << " rowset_id=" << rowset_id;
4551
0
                ret = -1;
4552
0
                continue;
4553
0
            }
4554
27.6k
            InvertedIndexInfo index_info;
4555
27.6k
            inverted_index_get_ret =
4556
27.6k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
4557
27.6k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
4558
27.6k
                                     &inverted_index_get_ret);
4559
27.6k
            if (inverted_index_get_ret == 0) {
4560
27.1k
                if (!rs.has_inverted_index_storage_format()) {
4561
27.1k
                    index_format = index_info.first;
4562
27.1k
                }
4563
27.1k
                index_ids = index_info.second;
4564
27.1k
            } else if (inverted_index_get_ret == 1) {
4565
                // 1. Schema kv not found means tablet has been recycled
4566
                // Maybe some tablet recycle failed by some bugs
4567
                // We need to delete again to double check
4568
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
4569
                // because we are uncertain about the inverted index information.
4570
                // If there are inverted indexes, some data might not be deleted,
4571
                // but this is acceptable as we have made our best effort to delete the data.
4572
503
                LOG_INFO(
4573
503
                        "delete rowset data schema kv not found, need to delete again to "
4574
503
                        "double "
4575
503
                        "check")
4576
503
                        .tag("instance_id", instance_id_)
4577
503
                        .tag("tablet_id", tablet_id)
4578
503
                        .tag("rowset", rs.ShortDebugString());
4579
                // Currently index_ids is guaranteed to be empty,
4580
                // but we clear it again here as a safeguard against future code changes
4581
                // that might cause index_ids to no longer be empty
4582
503
                index_format = InvertedIndexStorageFormatPB::V2;
4583
503
                index_ids.clear();
4584
18.4E
            } else {
4585
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
4586
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4587
18.4E
                ret = -1;
4588
18.4E
                continue;
4589
18.4E
            }
4590
27.6k
        }
4591
54.4k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
4592
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
4593
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
4594
10
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
4595
10
            continue;
4596
10
        }
4597
325k
        for (int64_t i = 0; i < num_segments; ++i) {
4598
270k
            add_file_to_delete_if_not_packed(rs, segment_path(tablet_id, rowset_id, i),
4599
270k
                                             &file_paths);
4600
270k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
4601
537k
                for (const auto& index_id : index_ids) {
4602
537k
                    add_file_to_delete_if_not_packed(
4603
537k
                            rs,
4604
537k
                            inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
4605
537k
                                                   index_id.second),
4606
537k
                            &file_paths);
4607
537k
                }
4608
268k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
4609
                // try to recycle inverted index v2 when get_ret == 1
4610
                // we treat schema not found as if it has a v2 format inverted index
4611
                // to reduce chance of data leakage
4612
2.50k
                if (inverted_index_get_ret == 1) {
4613
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
4614
2.50k
                            .tag("instance_id", instance_id_)
4615
2.50k
                            .tag("inverted index v2 path",
4616
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, i));
4617
2.50k
                }
4618
2.50k
                add_file_to_delete_if_not_packed(
4619
2.50k
                        rs, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
4620
2.50k
            }
4621
270k
        }
4622
54.4k
    }
4623
4624
65
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
4625
65
                                                 "delete_rowset_data",
4626
65
                                                 [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clERKi
Line
Count
Source
4626
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
4626
56
                                                 [](const int& ret) { return ret != 0; });
4627
65
    for (auto& [resource_id, file_paths] : resource_file_paths) {
4628
52
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4629
52
            DCHECK(accessor_map_.count(*rid))
4630
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4631
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4632
52
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4633
52
                                     &accessor_map_);
4634
52
            if (!accessor_map_.contains(*rid)) {
4635
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4636
0
                        .tag("resource_id", resource_id)
4637
0
                        .tag("instance_id", instance_id_);
4638
0
                return -1;
4639
0
            }
4640
52
            auto& accessor = accessor_map_[*rid];
4641
52
            int ret = accessor->delete_files(*paths);
4642
52
            if (!ret) {
4643
                // deduplication of different files with the same rowset id
4644
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4645
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4646
52
                std::set<std::string> deleted_rowset_id;
4647
4648
52
                std::for_each(paths->begin(), paths->end(),
4649
52
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4650
862k
                               this](const std::string& path) {
4651
862k
                                  std::vector<std::string> str;
4652
862k
                                  butil::SplitString(path, '/', &str);
4653
862k
                                  std::string rowset_id;
4654
862k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4655
856k
                                      rowset_id = str.back().substr(0, pos);
4656
856k
                                  } else {
4657
6.85k
                                      if (path.find("packed_file/") != std::string::npos) {
4658
0
                                          return; // packed files do not have rowset_id encoded
4659
0
                                      }
4660
6.85k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4661
6.85k
                                      return;
4662
6.85k
                                  }
4663
856k
                                  auto rs_meta = rowsets.find(rowset_id);
4664
856k
                                  if (rs_meta != rowsets.end() &&
4665
858k
                                      !deleted_rowset_id.contains(rowset_id)) {
4666
54.4k
                                      deleted_rowset_id.emplace(rowset_id);
4667
54.4k
                                      metrics_context.total_recycled_data_size +=
4668
54.4k
                                              rs_meta->second.total_disk_size();
4669
54.4k
                                      segment_metrics_context_.total_recycled_num +=
4670
54.4k
                                              rs_meta->second.num_segments();
4671
54.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4672
54.4k
                                              rs_meta->second.total_disk_size();
4673
54.4k
                                      metrics_context.total_recycled_num++;
4674
54.4k
                                  }
4675
856k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clEvENKUlRSD_E_clESN_
Line
Count
Source
4650
7
                               this](const std::string& path) {
4651
7
                                  std::vector<std::string> str;
4652
7
                                  butil::SplitString(path, '/', &str);
4653
7
                                  std::string rowset_id;
4654
7
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4655
7
                                      rowset_id = str.back().substr(0, pos);
4656
7
                                  } else {
4657
0
                                      if (path.find("packed_file/") != std::string::npos) {
4658
0
                                          return; // packed files do not have rowset_id encoded
4659
0
                                      }
4660
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4661
0
                                      return;
4662
0
                                  }
4663
7
                                  auto rs_meta = rowsets.find(rowset_id);
4664
7
                                  if (rs_meta != rowsets.end() &&
4665
7
                                      !deleted_rowset_id.contains(rowset_id)) {
4666
7
                                      deleted_rowset_id.emplace(rowset_id);
4667
7
                                      metrics_context.total_recycled_data_size +=
4668
7
                                              rs_meta->second.total_disk_size();
4669
7
                                      segment_metrics_context_.total_recycled_num +=
4670
7
                                              rs_meta->second.num_segments();
4671
7
                                      segment_metrics_context_.total_recycled_data_size +=
4672
7
                                              rs_meta->second.total_disk_size();
4673
7
                                      metrics_context.total_recycled_num++;
4674
7
                                  }
4675
7
                              });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clEvENKUlRSD_E_clESN_
Line
Count
Source
4650
862k
                               this](const std::string& path) {
4651
862k
                                  std::vector<std::string> str;
4652
862k
                                  butil::SplitString(path, '/', &str);
4653
862k
                                  std::string rowset_id;
4654
862k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4655
856k
                                      rowset_id = str.back().substr(0, pos);
4656
856k
                                  } else {
4657
6.85k
                                      if (path.find("packed_file/") != std::string::npos) {
4658
0
                                          return; // packed files do not have rowset_id encoded
4659
0
                                      }
4660
6.85k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4661
6.85k
                                      return;
4662
6.85k
                                  }
4663
856k
                                  auto rs_meta = rowsets.find(rowset_id);
4664
856k
                                  if (rs_meta != rowsets.end() &&
4665
858k
                                      !deleted_rowset_id.contains(rowset_id)) {
4666
54.4k
                                      deleted_rowset_id.emplace(rowset_id);
4667
54.4k
                                      metrics_context.total_recycled_data_size +=
4668
54.4k
                                              rs_meta->second.total_disk_size();
4669
54.4k
                                      segment_metrics_context_.total_recycled_num +=
4670
54.4k
                                              rs_meta->second.num_segments();
4671
54.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4672
54.4k
                                              rs_meta->second.total_disk_size();
4673
54.4k
                                      metrics_context.total_recycled_num++;
4674
54.4k
                                  }
4675
856k
                              });
4676
52
            }
4677
52
            return ret;
4678
52
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clEv
Line
Count
Source
4628
6
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4629
6
            DCHECK(accessor_map_.count(*rid))
4630
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4631
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4632
6
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4633
6
                                     &accessor_map_);
4634
6
            if (!accessor_map_.contains(*rid)) {
4635
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4636
0
                        .tag("resource_id", resource_id)
4637
0
                        .tag("instance_id", instance_id_);
4638
0
                return -1;
4639
0
            }
4640
6
            auto& accessor = accessor_map_[*rid];
4641
6
            int ret = accessor->delete_files(*paths);
4642
6
            if (!ret) {
4643
                // deduplication of different files with the same rowset id
4644
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4645
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4646
6
                std::set<std::string> deleted_rowset_id;
4647
4648
6
                std::for_each(paths->begin(), paths->end(),
4649
6
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4650
6
                               this](const std::string& path) {
4651
6
                                  std::vector<std::string> str;
4652
6
                                  butil::SplitString(path, '/', &str);
4653
6
                                  std::string rowset_id;
4654
6
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4655
6
                                      rowset_id = str.back().substr(0, pos);
4656
6
                                  } else {
4657
6
                                      if (path.find("packed_file/") != std::string::npos) {
4658
6
                                          return; // packed files do not have rowset_id encoded
4659
6
                                      }
4660
6
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4661
6
                                      return;
4662
6
                                  }
4663
6
                                  auto rs_meta = rowsets.find(rowset_id);
4664
6
                                  if (rs_meta != rowsets.end() &&
4665
6
                                      !deleted_rowset_id.contains(rowset_id)) {
4666
6
                                      deleted_rowset_id.emplace(rowset_id);
4667
6
                                      metrics_context.total_recycled_data_size +=
4668
6
                                              rs_meta->second.total_disk_size();
4669
6
                                      segment_metrics_context_.total_recycled_num +=
4670
6
                                              rs_meta->second.num_segments();
4671
6
                                      segment_metrics_context_.total_recycled_data_size +=
4672
6
                                              rs_meta->second.total_disk_size();
4673
6
                                      metrics_context.total_recycled_num++;
4674
6
                                  }
4675
6
                              });
4676
6
            }
4677
6
            return ret;
4678
6
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clEv
Line
Count
Source
4628
46
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4629
46
            DCHECK(accessor_map_.count(*rid))
4630
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4631
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4632
46
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4633
46
                                     &accessor_map_);
4634
46
            if (!accessor_map_.contains(*rid)) {
4635
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4636
0
                        .tag("resource_id", resource_id)
4637
0
                        .tag("instance_id", instance_id_);
4638
0
                return -1;
4639
0
            }
4640
46
            auto& accessor = accessor_map_[*rid];
4641
46
            int ret = accessor->delete_files(*paths);
4642
46
            if (!ret) {
4643
                // deduplication of different files with the same rowset id
4644
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4645
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4646
46
                std::set<std::string> deleted_rowset_id;
4647
4648
46
                std::for_each(paths->begin(), paths->end(),
4649
46
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4650
46
                               this](const std::string& path) {
4651
46
                                  std::vector<std::string> str;
4652
46
                                  butil::SplitString(path, '/', &str);
4653
46
                                  std::string rowset_id;
4654
46
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4655
46
                                      rowset_id = str.back().substr(0, pos);
4656
46
                                  } else {
4657
46
                                      if (path.find("packed_file/") != std::string::npos) {
4658
46
                                          return; // packed files do not have rowset_id encoded
4659
46
                                      }
4660
46
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4661
46
                                      return;
4662
46
                                  }
4663
46
                                  auto rs_meta = rowsets.find(rowset_id);
4664
46
                                  if (rs_meta != rowsets.end() &&
4665
46
                                      !deleted_rowset_id.contains(rowset_id)) {
4666
46
                                      deleted_rowset_id.emplace(rowset_id);
4667
46
                                      metrics_context.total_recycled_data_size +=
4668
46
                                              rs_meta->second.total_disk_size();
4669
46
                                      segment_metrics_context_.total_recycled_num +=
4670
46
                                              rs_meta->second.num_segments();
4671
46
                                      segment_metrics_context_.total_recycled_data_size +=
4672
46
                                              rs_meta->second.total_disk_size();
4673
46
                                      metrics_context.total_recycled_num++;
4674
46
                                  }
4675
46
                              });
4676
46
            }
4677
46
            return ret;
4678
46
        });
4679
52
    }
4680
65
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
4681
10
        LOG_INFO(
4682
10
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
4683
10
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
4684
10
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
4685
10
        concurrent_delete_executor.add([&]() -> int {
4686
10
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4687
10
            if (!ret) {
4688
10
                auto rs = rowsets.at(rowset_id);
4689
10
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4690
10
                metrics_context.total_recycled_num++;
4691
10
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4692
10
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4693
10
            }
4694
10
            return ret;
4695
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
4685
10
        concurrent_delete_executor.add([&]() -> int {
4686
10
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4687
10
            if (!ret) {
4688
10
                auto rs = rowsets.at(rowset_id);
4689
10
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4690
10
                metrics_context.total_recycled_num++;
4691
10
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4692
10
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4693
10
            }
4694
10
            return ret;
4695
10
        });
4696
10
    }
4697
4698
65
    bool finished = true;
4699
65
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4700
65
    for (int r : rets) {
4701
62
        if (r != 0) {
4702
0
            ret = -1;
4703
0
            break;
4704
0
        }
4705
62
    }
4706
65
    ret = finished ? ret : -1;
4707
65
    return ret;
4708
65
}
4709
4710
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
4711
3.58k
                                         const std::string& rowset_id) {
4712
3.58k
    auto it = accessor_map_.find(resource_id);
4713
3.58k
    if (it == accessor_map_.end()) {
4714
400
        LOG_WARNING("instance has no such resource id")
4715
400
                .tag("instance_id", instance_id_)
4716
400
                .tag("resource_id", resource_id)
4717
400
                .tag("tablet_id", tablet_id)
4718
400
                .tag("rowset_id", rowset_id);
4719
400
        return -1;
4720
400
    }
4721
3.18k
    auto& accessor = it->second;
4722
3.18k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
4723
3.58k
}
4724
4725
int InstanceRecycler::delete_versioned_delete_bitmap_kvs(int64_t tablet_id,
4726
55.5k
                                                         const std::string& rowset_id) {
4727
55.5k
    std::string dbm_start_key =
4728
55.5k
            versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4729
55.5k
    std::string dbm_end_key = dbm_start_key;
4730
55.5k
    encode_int64(INT64_MAX, &dbm_end_key);
4731
55.5k
    int ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4732
55.5k
    if (ret != 0) {
4733
0
        LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id=" << instance_id_
4734
0
                     << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4735
0
    }
4736
55.5k
    return ret;
4737
55.5k
}
4738
4739
51.2k
int InstanceRecycler::delete_delete_bitmap_kvs(int64_t tablet_id, const std::string& rowset_id) {
4740
51.2k
    std::string delete_bitmap_start =
4741
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
4742
51.2k
    std::string delete_bitmap_end =
4743
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
4744
51.2k
    int ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
4745
51.2k
    if (ret != 0) {
4746
0
        LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
4747
0
                     << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4748
0
    }
4749
51.2k
    return ret;
4750
51.2k
}
4751
4752
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
4753
4
    if (key.empty()) {
4754
0
        return false;
4755
0
    }
4756
4
    std::string_view key_view = key;
4757
4
    key_view.remove_prefix(1); // remove keyspace prefix
4758
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
4759
4
    if (decode_key(&key_view, &decoded) != 0) {
4760
0
        return false;
4761
0
    }
4762
4
    if (decoded.size() < 4) {
4763
0
        return false;
4764
0
    }
4765
4
    try {
4766
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
4767
4
    } catch (const std::bad_variant_access&) {
4768
0
        return false;
4769
0
    }
4770
4
    return true;
4771
4
}
4772
4773
14
int InstanceRecycler::recycle_packed_files() {
4774
14
    const std::string task_name = "recycle_packed_files";
4775
14
    auto start_tp = steady_clock::now();
4776
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
4777
14
    int ret = 0;
4778
14
    PackedFileRecycleStats stats;
4779
4780
14
    register_recycle_task(task_name, start_time);
4781
14
    DORIS_CLOUD_DEFER {
4782
14
        unregister_recycle_task(task_name);
4783
14
        int64_t cost =
4784
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4785
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4786
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4787
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4788
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4789
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4790
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4791
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4792
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4793
14
                                                             stats.bytes_object_deleted);
4794
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4795
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4796
14
                .tag("instance_id", instance_id_)
4797
14
                .tag("num_scanned", stats.num_scanned)
4798
14
                .tag("num_corrected", stats.num_corrected)
4799
14
                .tag("num_deleted", stats.num_deleted)
4800
14
                .tag("num_failed", stats.num_failed)
4801
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4802
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4803
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4804
14
                .tag("bytes_deleted", stats.bytes_deleted)
4805
14
                .tag("ret", ret);
4806
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
4781
14
    DORIS_CLOUD_DEFER {
4782
14
        unregister_recycle_task(task_name);
4783
14
        int64_t cost =
4784
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4785
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4786
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4787
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4788
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4789
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4790
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4791
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4792
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4793
14
                                                             stats.bytes_object_deleted);
4794
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4795
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4796
14
                .tag("instance_id", instance_id_)
4797
14
                .tag("num_scanned", stats.num_scanned)
4798
14
                .tag("num_corrected", stats.num_corrected)
4799
14
                .tag("num_deleted", stats.num_deleted)
4800
14
                .tag("num_failed", stats.num_failed)
4801
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4802
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4803
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4804
14
                .tag("bytes_deleted", stats.bytes_deleted)
4805
14
                .tag("ret", ret);
4806
14
    };
4807
4808
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4809
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4810
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4811
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
4808
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4809
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4810
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4811
4
    };
4812
4813
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
4814
4815
14
    std::string begin = packed_file_key({instance_id_, ""});
4816
14
    std::string end = packed_file_key({instance_id_, "\xff"});
4817
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
4818
0
        ret = -1;
4819
0
    }
4820
4821
14
    return ret;
4822
14
}
4823
4824
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
4825
                                                  RecyclerMetricsContext& metrics_context,
4826
0
                                                  int64_t partition_id, bool is_empty_tablet) {
4827
0
    std::string tablet_key_begin, tablet_key_end;
4828
4829
0
    if (partition_id > 0) {
4830
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
4831
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
4832
0
    } else {
4833
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
4834
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
4835
0
    }
4836
    // for calculate the total num or bytes of recyled objects
4837
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
4838
0
                                                          std::string_view v) -> int {
4839
0
        doris::TabletMetaCloudPB tablet_meta_pb;
4840
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
4841
0
            return 0;
4842
0
        }
4843
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
4844
4845
0
        if (config::enable_recycler_check_lazy_txn_finished &&
4846
0
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
4847
0
            return 0;
4848
0
        }
4849
4850
0
        if (!is_empty_tablet) {
4851
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
4852
0
                return 0;
4853
0
            }
4854
0
            tablet_metrics_context_.total_need_recycle_num++;
4855
0
        }
4856
0
        return 0;
4857
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_
4858
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
4859
0
    metrics_context.report(true);
4860
0
    tablet_metrics_context_.report(true);
4861
0
    segment_metrics_context_.report(true);
4862
0
    return ret;
4863
0
}
4864
4865
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
4866
0
                                                 RecyclerMetricsContext& metrics_context) {
4867
0
    int ret = 0;
4868
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
4869
0
    std::unique_ptr<Transaction> txn;
4870
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4871
0
        LOG_WARNING("failed to recycle tablet ")
4872
0
                .tag("tablet id", tablet_id)
4873
0
                .tag("instance_id", instance_id_)
4874
0
                .tag("reason", "failed to create txn");
4875
0
        ret = -1;
4876
0
    }
4877
0
    GetRowsetResponse resp;
4878
0
    std::string msg;
4879
0
    MetaServiceCode code = MetaServiceCode::OK;
4880
    // get rowsets in tablet
4881
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4882
0
                        tablet_id, code, msg, &resp);
4883
0
    if (code != MetaServiceCode::OK) {
4884
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4885
0
                .tag("tablet id", tablet_id)
4886
0
                .tag("msg", msg)
4887
0
                .tag("code", code)
4888
0
                .tag("instance id", instance_id_);
4889
0
        ret = -1;
4890
0
    }
4891
0
    for (const auto& rs_meta : resp.rowset_meta()) {
4892
        /*
4893
        * For compatibility, we skip the loop for [0-1] here.
4894
        * The purpose of this loop is to delete object files,
4895
        * and since [0-1] only has meta and doesn't have object files,
4896
        * skipping it doesn't affect system correctness.
4897
        *
4898
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
4899
        * would return error -1 directly, causing the recycle operation to fail.
4900
        *
4901
        * [0-1] doesn't have resource id is a bug.
4902
        * In the future, we will fix this problem, after that,
4903
        * we can remove this if statement.
4904
        *
4905
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
4906
        */
4907
4908
0
        if (rs_meta.end_version() == 1) {
4909
            // Assert that [0-1] has no resource_id to make sure
4910
            // this if statement will not be forgetted to remove
4911
            // when the resource id bug is fixed
4912
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4913
0
            continue;
4914
0
        }
4915
0
        if (!rs_meta.has_resource_id()) {
4916
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4917
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4918
0
                    .tag("instance_id", instance_id_)
4919
0
                    .tag("tablet_id", tablet_id);
4920
0
            continue;
4921
0
        }
4922
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4923
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4924
        // possible if the accessor is not initilized correctly
4925
0
        if (it == accessor_map_.end()) [[unlikely]] {
4926
0
            LOG_WARNING(
4927
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4928
0
                    "recycle process")
4929
0
                    .tag("tablet id", tablet_id)
4930
0
                    .tag("instance_id", instance_id_)
4931
0
                    .tag("resource_id", rs_meta.resource_id())
4932
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4933
0
            continue;
4934
0
        }
4935
4936
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
4937
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4938
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4939
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
4940
0
    }
4941
0
    return ret;
4942
0
}
4943
4944
4.26k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
4945
4.26k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
4946
4.26k
            .tag("instance_id", instance_id_)
4947
4.26k
            .tag("tablet_id", tablet_id);
4948
4949
4.26k
    if (should_recycle_versioned_keys()) {
4950
14
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
4951
14
        if (ret != 0) {
4952
0
            return ret;
4953
0
        }
4954
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
4955
        // during the recycle_versioned_tablet process.
4956
        //
4957
        // .. And remove restore job rowsets of this tablet too
4958
14
    }
4959
4960
4.26k
    int ret = 0;
4961
4.26k
    auto start_time = steady_clock::now();
4962
4963
4.26k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4964
4965
    // collect resource ids
4966
260
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4967
260
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4968
260
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4969
260
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4970
260
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
4971
260
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
4972
4973
260
    std::set<std::string> resource_ids;
4974
260
    int64_t recycle_rowsets_number = 0;
4975
260
    int64_t recycle_segments_number = 0;
4976
260
    int64_t recycle_rowsets_data_size = 0;
4977
260
    int64_t recycle_rowsets_index_size = 0;
4978
260
    int64_t recycle_restore_job_rowsets_number = 0;
4979
260
    int64_t recycle_restore_job_segments_number = 0;
4980
260
    int64_t recycle_restore_job_rowsets_data_size = 0;
4981
260
    int64_t recycle_restore_job_rowsets_index_size = 0;
4982
260
    int64_t max_rowset_version = 0;
4983
260
    int64_t min_rowset_creation_time = INT64_MAX;
4984
260
    int64_t max_rowset_creation_time = 0;
4985
260
    int64_t min_rowset_expiration_time = INT64_MAX;
4986
260
    int64_t max_rowset_expiration_time = 0;
4987
4988
260
    DORIS_CLOUD_DEFER {
4989
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4990
260
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4991
260
                .tag("instance_id", instance_id_)
4992
260
                .tag("tablet_id", tablet_id)
4993
260
                .tag("recycle rowsets number", recycle_rowsets_number)
4994
260
                .tag("recycle segments number", recycle_segments_number)
4995
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4996
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4997
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4998
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4999
260
                .tag("all restore job rowsets recycle data size",
5000
260
                     recycle_restore_job_rowsets_data_size)
5001
260
                .tag("all restore job rowsets recycle index size",
5002
260
                     recycle_restore_job_rowsets_index_size)
5003
260
                .tag("max rowset version", max_rowset_version)
5004
260
                .tag("min rowset creation time", min_rowset_creation_time)
5005
260
                .tag("max rowset creation time", max_rowset_creation_time)
5006
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
5007
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
5008
260
                .tag("task type", metrics_context.operation_type)
5009
260
                .tag("ret", ret);
5010
260
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4988
260
    DORIS_CLOUD_DEFER {
4989
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4990
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4991
260
                .tag("instance_id", instance_id_)
4992
260
                .tag("tablet_id", tablet_id)
4993
260
                .tag("recycle rowsets number", recycle_rowsets_number)
4994
260
                .tag("recycle segments number", recycle_segments_number)
4995
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4996
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4997
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4998
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4999
260
                .tag("all restore job rowsets recycle data size",
5000
260
                     recycle_restore_job_rowsets_data_size)
5001
260
                .tag("all restore job rowsets recycle index size",
5002
260
                     recycle_restore_job_rowsets_index_size)
5003
260
                .tag("max rowset version", max_rowset_version)
5004
260
                .tag("min rowset creation time", min_rowset_creation_time)
5005
260
                .tag("max rowset creation time", max_rowset_creation_time)
5006
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
5007
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
5008
260
                .tag("task type", metrics_context.operation_type)
5009
260
                .tag("ret", ret);
5010
260
    };
5011
5012
260
    std::unique_ptr<Transaction> txn;
5013
260
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5014
0
        LOG_WARNING("failed to recycle tablet ")
5015
0
                .tag("tablet id", tablet_id)
5016
0
                .tag("instance_id", instance_id_)
5017
0
                .tag("reason", "failed to create txn");
5018
0
        ret = -1;
5019
0
    }
5020
260
    GetRowsetResponse resp;
5021
260
    std::string msg;
5022
260
    MetaServiceCode code = MetaServiceCode::OK;
5023
    // get rowsets in tablet
5024
260
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
5025
260
                        tablet_id, code, msg, &resp);
5026
260
    if (code != MetaServiceCode::OK) {
5027
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5028
0
                .tag("tablet id", tablet_id)
5029
0
                .tag("msg", msg)
5030
0
                .tag("code", code)
5031
0
                .tag("instance id", instance_id_);
5032
0
        ret = -1;
5033
0
    }
5034
260
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
5035
5036
2.55k
    for (const auto& rs_meta : resp.rowset_meta()) {
5037
2.55k
        if (!rs_meta.has_resource_id() || rs_meta.resource_id().empty()) {
5038
3
            if (rs_meta.num_segments() <= 0) {
5039
2
                LOG_INFO("rowset meta has no segments and no resource id, skip this rowset")
5040
2
                        .tag("rs_meta", rs_meta.ShortDebugString())
5041
2
                        .tag("instance_id", instance_id_)
5042
2
                        .tag("tablet_id", tablet_id);
5043
2
                recycle_rowsets_number += 1;
5044
2
                continue;
5045
2
            }
5046
1
            LOG_WARNING("rowset meta has a missing or empty resource id, impossible!")
5047
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
5048
1
                    .tag("instance_id", instance_id_)
5049
1
                    .tag("tablet_id", tablet_id);
5050
1
            return -1;
5051
3
        }
5052
2.55k
        DCHECK(rs_meta.has_resource_id() && !rs_meta.resource_id().empty())
5053
1
                << "rs_meta" << rs_meta.ShortDebugString();
5054
2.54k
        auto it = accessor_map_.find(rs_meta.resource_id());
5055
        // possible if the accessor is not initilized correctly
5056
2.54k
        if (it == accessor_map_.end()) [[unlikely]] {
5057
1
            LOG_WARNING(
5058
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5059
1
                    "recycle process")
5060
1
                    .tag("tablet id", tablet_id)
5061
1
                    .tag("instance_id", instance_id_)
5062
1
                    .tag("resource_id", rs_meta.resource_id())
5063
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5064
1
            return -1;
5065
1
        }
5066
2.54k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5067
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
5068
0
                    .tag("instance_id", instance_id_)
5069
0
                    .tag("tablet_id", tablet_id)
5070
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5071
0
            return -1;
5072
0
        }
5073
2.54k
        recycle_rowsets_number += 1;
5074
2.54k
        recycle_segments_number += rs_meta.num_segments();
5075
2.54k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5076
2.54k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5077
2.54k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5078
2.54k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5079
2.54k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5080
2.54k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5081
2.54k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5082
2.54k
        resource_ids.emplace(rs_meta.resource_id());
5083
2.54k
    }
5084
5085
    // get restore job rowset in tablet
5086
258
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
5087
258
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
5088
258
    if (code != MetaServiceCode::OK) {
5089
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
5090
0
                .tag("tablet id", tablet_id)
5091
0
                .tag("msg", msg)
5092
0
                .tag("code", code)
5093
0
                .tag("instance id", instance_id_);
5094
0
        return -1;
5095
0
    }
5096
5097
258
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
5098
0
        if (!rs_meta.has_resource_id()) {
5099
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
5100
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
5101
0
                    .tag("instance_id", instance_id_)
5102
0
                    .tag("tablet_id", tablet_id);
5103
0
            return -1;
5104
0
        }
5105
5106
0
        auto it = accessor_map_.find(rs_meta.resource_id());
5107
        // possible if the accessor is not initilized correctly
5108
0
        if (it == accessor_map_.end()) [[unlikely]] {
5109
0
            LOG_WARNING(
5110
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5111
0
                    "recycle process")
5112
0
                    .tag("tablet id", tablet_id)
5113
0
                    .tag("instance_id", instance_id_)
5114
0
                    .tag("resource_id", rs_meta.resource_id())
5115
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5116
0
            return -1;
5117
0
        }
5118
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5119
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
5120
0
                    .tag("instance_id", instance_id_)
5121
0
                    .tag("tablet_id", tablet_id)
5122
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5123
0
            return -1;
5124
0
        }
5125
0
        recycle_restore_job_rowsets_number += 1;
5126
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
5127
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
5128
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
5129
0
        resource_ids.emplace(rs_meta.resource_id());
5130
0
    }
5131
5132
258
    LOG_INFO("recycle tablet start to delete object")
5133
258
            .tag("instance id", instance_id_)
5134
258
            .tag("tablet id", tablet_id)
5135
258
            .tag("recycle tablet resource ids are",
5136
258
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
5137
258
                                 [](std::string rs_id, const auto& it) {
5138
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5139
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
5137
217
                                 [](std::string rs_id, const auto& it) {
5138
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5139
217
                                 }));
5140
5141
258
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
5142
258
            _thread_pool_group.s3_producer_pool,
5143
258
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5144
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
5144
208
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
5145
5146
    // delete all rowset data in this tablet
5147
    // ATTN: there may be data leak if not all accessor initilized successfully
5148
    //       partial data deleted if the tablet is stored cross-storage vault
5149
    //       vault id is not attached to TabletMeta...
5150
258
    for (const auto& resource_id : resource_ids) {
5151
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
5152
217
        concurrent_delete_executor.add(
5153
217
                [&, rs_id = resource_id,
5154
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5155
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5156
217
                    if (res != 0) {
5157
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5158
3
                                     << " path=" << accessor_ptr->uri()
5159
3
                                     << " task type=" << metrics_context.operation_type;
5160
3
                        return std::make_pair(-1, rs_id);
5161
3
                    }
5162
214
                    return std::make_pair(0, rs_id);
5163
217
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
5154
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5155
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5156
217
                    if (res != 0) {
5157
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5158
3
                                     << " path=" << accessor_ptr->uri()
5159
3
                                     << " task type=" << metrics_context.operation_type;
5160
3
                        return std::make_pair(-1, rs_id);
5161
3
                    }
5162
214
                    return std::make_pair(0, rs_id);
5163
217
                });
5164
217
    }
5165
5166
258
    bool finished = true;
5167
258
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
5168
258
    for (auto& r : rets) {
5169
217
        if (r.first != 0) {
5170
3
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
5171
3
            ret = -1;
5172
3
        }
5173
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
5174
217
    }
5175
258
    ret = finished ? ret : -1;
5176
5177
258
    if (ret != 0) { // failed recycle tablet data
5178
3
        LOG_WARNING("ret!=0")
5179
3
                .tag("finished", finished)
5180
3
                .tag("ret", ret)
5181
3
                .tag("instance_id", instance_id_)
5182
3
                .tag("tablet_id", tablet_id);
5183
3
        return ret;
5184
3
    }
5185
5186
255
    tablet_metrics_context_.total_recycled_data_size +=
5187
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5188
255
    tablet_metrics_context_.total_recycled_num += 1;
5189
255
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5190
255
    segment_metrics_context_.total_recycled_data_size +=
5191
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5192
255
    metrics_context.total_recycled_data_size +=
5193
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5194
255
    tablet_metrics_context_.report();
5195
255
    segment_metrics_context_.report();
5196
255
    metrics_context.report();
5197
5198
255
    txn.reset();
5199
255
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5200
0
        LOG_WARNING("failed to recycle tablet ")
5201
0
                .tag("tablet id", tablet_id)
5202
0
                .tag("instance_id", instance_id_)
5203
0
                .tag("reason", "failed to create txn");
5204
0
        ret = -1;
5205
0
    }
5206
    // delete all rowset kv in this tablet
5207
255
    txn->remove(rs_key0, rs_key1);
5208
255
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5209
255
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5210
5211
    // remove delete bitmap for MoW table
5212
255
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5213
255
    txn->remove(pending_key);
5214
255
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5215
255
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5216
255
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5217
5218
255
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5219
255
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5220
255
    txn->remove(dbm_start_key, dbm_end_key);
5221
255
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5222
255
              << " end=" << hex(dbm_end_key);
5223
5224
255
    TxnErrorCode err = txn->commit();
5225
255
    if (err != TxnErrorCode::TXN_OK) {
5226
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5227
0
        ret = -1;
5228
0
    }
5229
5230
255
    if (ret == 0) {
5231
        // All object files under tablet have been deleted
5232
255
        std::lock_guard lock(recycled_tablets_mtx_);
5233
255
        recycled_tablets_.insert(tablet_id);
5234
255
    }
5235
5236
255
    return ret;
5237
258
}
5238
5239
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
5240
14
                                               RecyclerMetricsContext& metrics_context) {
5241
14
    int ret = 0;
5242
14
    auto start_time = steady_clock::now();
5243
5244
14
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
5245
5246
    // collect resource ids
5247
11
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
5248
11
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
5249
11
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
5250
11
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
5251
5252
11
    int64_t recycle_rowsets_number = 0;
5253
11
    int64_t recycle_segments_number = 0;
5254
11
    int64_t recycle_rowsets_data_size = 0;
5255
11
    int64_t recycle_rowsets_index_size = 0;
5256
11
    int64_t max_rowset_version = 0;
5257
11
    int64_t min_rowset_creation_time = INT64_MAX;
5258
11
    int64_t max_rowset_creation_time = 0;
5259
11
    int64_t min_rowset_expiration_time = INT64_MAX;
5260
11
    int64_t max_rowset_expiration_time = 0;
5261
5262
11
    DORIS_CLOUD_DEFER {
5263
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5264
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5265
11
                .tag("instance_id", instance_id_)
5266
11
                .tag("tablet_id", tablet_id)
5267
11
                .tag("recycle rowsets number", recycle_rowsets_number)
5268
11
                .tag("recycle segments number", recycle_segments_number)
5269
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5270
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5271
11
                .tag("max rowset version", max_rowset_version)
5272
11
                .tag("min rowset creation time", min_rowset_creation_time)
5273
11
                .tag("max rowset creation time", max_rowset_creation_time)
5274
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
5275
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
5276
11
                .tag("ret", ret);
5277
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
5262
11
    DORIS_CLOUD_DEFER {
5263
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5264
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5265
11
                .tag("instance_id", instance_id_)
5266
11
                .tag("tablet_id", tablet_id)
5267
11
                .tag("recycle rowsets number", recycle_rowsets_number)
5268
11
                .tag("recycle segments number", recycle_segments_number)
5269
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5270
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5271
11
                .tag("max rowset version", max_rowset_version)
5272
11
                .tag("min rowset creation time", min_rowset_creation_time)
5273
11
                .tag("max rowset creation time", max_rowset_creation_time)
5274
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
5275
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
5276
11
                .tag("ret", ret);
5277
11
    };
5278
5279
11
    std::unique_ptr<Transaction> txn;
5280
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5281
0
        LOG_WARNING("failed to recycle tablet ")
5282
0
                .tag("tablet id", tablet_id)
5283
0
                .tag("instance_id", instance_id_)
5284
0
                .tag("reason", "failed to create txn");
5285
0
        ret = -1;
5286
0
    }
5287
5288
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
5289
    // by the related operation logs.
5290
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
5291
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
5292
11
    MetaReader meta_reader(instance_id_);
5293
11
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
5294
11
    if (err == TxnErrorCode::TXN_OK) {
5295
11
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
5296
11
    }
5297
11
    if (err != TxnErrorCode::TXN_OK) {
5298
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5299
0
                .tag("tablet id", tablet_id)
5300
0
                .tag("err", err)
5301
0
                .tag("instance id", instance_id_);
5302
0
        ret = -1;
5303
0
    }
5304
5305
11
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
5306
11
             load_rowset_metas.size(), compact_rowset_metas.size())
5307
11
            .tag("instance_id", instance_id_)
5308
11
            .tag("tablet_id", tablet_id);
5309
5310
11
    SyncExecutor<int> concurrent_delete_executor(
5311
11
            _thread_pool_group.s3_producer_pool,
5312
11
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5313
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
5314
5315
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5316
60
        recycle_rowsets_number += 1;
5317
60
        recycle_segments_number += rs_meta.num_segments();
5318
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5319
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5320
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5321
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5322
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5323
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5324
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5325
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
5315
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5316
60
        recycle_rowsets_number += 1;
5317
60
        recycle_segments_number += rs_meta.num_segments();
5318
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5319
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5320
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5321
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5322
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5323
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5324
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5325
60
    };
5326
5327
11
    std::vector<RowsetDeleteTask> all_tasks;
5328
60
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
5329
60
        update_rowset_stats(rs_meta);
5330
        // Version 0-1 rowset has no resource_id and no actual data files,
5331
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5332
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5333
60
        RowsetDeleteTask task;
5334
60
        task.rowset_meta = rs_meta;
5335
60
        task.versioned_rowset_key =
5336
60
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
5337
60
        task.non_versioned_rowset_key =
5338
60
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5339
60
        task.versionstamp = versionstamp;
5340
60
        all_tasks.push_back(std::move(task));
5341
60
    }
5342
5343
11
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
5344
0
        update_rowset_stats(rs_meta);
5345
        // Version 0-1 rowset has no resource_id and no actual data files,
5346
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5347
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5348
0
        RowsetDeleteTask task;
5349
0
        task.rowset_meta = rs_meta;
5350
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
5351
0
                {instance_id_, tablet_id, rs_meta.end_version()});
5352
0
        task.non_versioned_rowset_key =
5353
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5354
0
        task.versionstamp = versionstamp;
5355
0
        all_tasks.push_back(std::move(task));
5356
0
    }
5357
5358
11
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
5359
0
        RecycleRowsetPB recycle_rowset;
5360
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
5361
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5362
0
            return -1;
5363
0
        }
5364
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
5365
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
5366
                // in old version, keep this key-value pair and it needs to be checked manually
5367
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5368
0
                return -1;
5369
0
            }
5370
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
5371
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5372
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5373
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
5374
0
                return -1;
5375
0
            }
5376
            // decode rowset_id
5377
0
            auto k1 = k;
5378
0
            k1.remove_prefix(1);
5379
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5380
0
            decode_key(&k1, &out);
5381
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5382
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5383
0
            LOG_INFO("delete old-version rowset data")
5384
0
                    .tag("instance_id", instance_id_)
5385
0
                    .tag("tablet_id", tablet_id)
5386
0
                    .tag("rowset_id", rowset_id);
5387
5388
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
5389
            // so we must use prefix deletion directly instead of batch delete.
5390
0
            concurrent_delete_executor.add(
5391
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
5392
                        // delete by prefix, the recycle rowset key will be deleted by range later.
5393
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
5394
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
5395
0
        } else {
5396
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
5397
            // Version 0-1 rowset has no resource_id and no actual data files,
5398
            // but still needs ref_count key cleanup, so we add it to all_tasks.
5399
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
5400
0
            RowsetDeleteTask task;
5401
0
            task.rowset_meta = rowset_meta;
5402
0
            task.recycle_rowset_key = k;
5403
0
            all_tasks.push_back(std::move(task));
5404
0
        }
5405
0
        return 0;
5406
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_
5407
5408
11
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
5409
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
5410
0
                .tag("tablet id", tablet_id)
5411
0
                .tag("instance_id", instance_id_)
5412
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
5413
0
        ret = -1;
5414
0
    }
5415
5416
    // Phase 1: Classify tasks by ref_count
5417
11
    std::vector<RowsetDeleteTask> batch_delete_tasks;
5418
60
    for (auto& task : all_tasks) {
5419
60
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
5420
60
        if (classify_ret < 0) {
5421
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
5422
0
                    .tag("instance_id", instance_id_)
5423
0
                    .tag("tablet_id", tablet_id)
5424
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5425
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
5426
0
                return recycle_rowset_meta_and_data(t);
5427
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
5428
0
        }
5429
60
    }
5430
5431
11
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
5432
5433
11
    LOG_INFO("batch delete plan created")
5434
11
            .tag("instance_id", instance_id_)
5435
11
            .tag("tablet_id", tablet_id)
5436
11
            .tag("plan_count", batch_delete_tasks.size());
5437
5438
    // Phase 2: Execute batch delete using existing delete_rowset_data
5439
11
    if (!batch_delete_tasks.empty()) {
5440
10
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
5441
49
        for (const auto& task : batch_delete_tasks) {
5442
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
5443
49
            if (task.rowset_meta.resource_id().empty()) {
5444
10
                LOG_INFO("skip rowset with empty resource_id in batch delete")
5445
10
                        .tag("instance_id", instance_id_)
5446
10
                        .tag("tablet_id", tablet_id)
5447
10
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5448
10
                continue;
5449
10
            }
5450
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
5451
39
        }
5452
5453
        // Only call delete_rowset_data if there are rowsets with actual data to delete
5454
10
        bool delete_success = true;
5455
10
        if (!rowsets_to_delete.empty()) {
5456
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
5457
9
                                                         "batch_delete_versioned_tablet");
5458
9
            int delete_ret = delete_rowset_data(
5459
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
5460
9
            if (delete_ret != 0) {
5461
0
                LOG_WARNING("batch delete execution failed")
5462
0
                        .tag("instance_id", instance_id_)
5463
0
                        .tag("tablet_id", tablet_id);
5464
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
5465
0
                ret = -1;
5466
0
                delete_success = false;
5467
0
            }
5468
9
        }
5469
5470
        // Phase 3: Only cleanup metadata if data deletion succeeded.
5471
        // If deletion failed, keep recycle_rowset_key so next round will retry.
5472
10
        if (delete_success) {
5473
10
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
5474
10
            if (cleanup_ret != 0) {
5475
0
                LOG_WARNING("batch delete cleanup failed")
5476
0
                        .tag("instance_id", instance_id_)
5477
0
                        .tag("tablet_id", tablet_id);
5478
0
                ret = -1;
5479
0
            }
5480
10
        }
5481
10
    }
5482
5483
    // Always wait for fallback tasks to complete before returning
5484
11
    bool finished = true;
5485
11
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
5486
11
    for (int r : rets) {
5487
0
        if (r != 0) {
5488
0
            ret = -1;
5489
0
        }
5490
0
    }
5491
5492
11
    ret = finished ? ret : -1;
5493
5494
11
    if (ret != 0) { // failed recycle tablet data
5495
0
        LOG_WARNING("recycle versioned tablet failed")
5496
0
                .tag("finished", finished)
5497
0
                .tag("ret", ret)
5498
0
                .tag("instance_id", instance_id_)
5499
0
                .tag("tablet_id", tablet_id);
5500
0
        return ret;
5501
0
    }
5502
5503
11
    tablet_metrics_context_.total_recycled_data_size +=
5504
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5505
11
    tablet_metrics_context_.total_recycled_num += 1;
5506
11
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5507
11
    segment_metrics_context_.total_recycled_data_size +=
5508
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5509
11
    metrics_context.total_recycled_data_size +=
5510
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5511
11
    tablet_metrics_context_.report();
5512
11
    segment_metrics_context_.report();
5513
11
    metrics_context.report();
5514
5515
11
    txn.reset();
5516
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5517
0
        LOG_WARNING("failed to recycle tablet ")
5518
0
                .tag("tablet id", tablet_id)
5519
0
                .tag("instance_id", instance_id_)
5520
0
                .tag("reason", "failed to create txn");
5521
0
        ret = -1;
5522
0
    }
5523
    // delete all rowset kv in this tablet
5524
11
    txn->remove(rs_key0, rs_key1);
5525
11
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5526
5527
    // remove delete bitmap for MoW table
5528
11
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5529
11
    txn->remove(pending_key);
5530
11
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5531
11
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5532
11
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5533
5534
11
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5535
11
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5536
11
    txn->remove(dbm_start_key, dbm_end_key);
5537
11
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5538
11
              << " end=" << hex(dbm_end_key);
5539
5540
11
    std::string versioned_idx_key = versioned::tablet_index_key({instance_id_, tablet_id});
5541
11
    std::string tablet_index_val;
5542
11
    err = txn->get(versioned_idx_key, &tablet_index_val);
5543
11
    if (err != TxnErrorCode::TXN_KEY_NOT_FOUND && err != TxnErrorCode::TXN_OK) {
5544
0
        LOG_WARNING("failed to get tablet index kv")
5545
0
                .tag("instance_id", instance_id_)
5546
0
                .tag("tablet_id", tablet_id)
5547
0
                .tag("err", err);
5548
0
        ret = -1;
5549
11
    } else if (err == TxnErrorCode::TXN_OK) {
5550
        // If the tablet index kv exists, we need to delete it
5551
10
        TabletIndexPB tablet_index_pb;
5552
10
        if (!tablet_index_pb.ParseFromString(tablet_index_val)) {
5553
0
            LOG_WARNING("failed to parse tablet index pb")
5554
0
                    .tag("instance_id", instance_id_)
5555
0
                    .tag("tablet_id", tablet_id);
5556
0
            ret = -1;
5557
10
        } else {
5558
10
            std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
5559
10
                    {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
5560
10
                     tablet_index_pb.index_id(), tablet_index_pb.partition_id(), tablet_id});
5561
10
            txn->remove(versioned_inverted_idx_key);
5562
10
            txn->remove(versioned_idx_key);
5563
10
        }
5564
10
    }
5565
5566
11
    err = txn->commit();
5567
11
    if (err != TxnErrorCode::TXN_OK) {
5568
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5569
0
        ret = -1;
5570
0
    }
5571
5572
11
    if (ret == 0) {
5573
        // All object files under tablet have been deleted
5574
11
        std::lock_guard lock(recycled_tablets_mtx_);
5575
11
        recycled_tablets_.insert(tablet_id);
5576
11
    }
5577
5578
11
    return ret;
5579
11
}
5580
5581
87
int InstanceRecycler::recycle_rowsets() {
5582
87
    if (should_recycle_versioned_keys()) {
5583
5
        return recycle_versioned_rowsets();
5584
5
    }
5585
5586
82
    const std::string task_name = "recycle_rowsets";
5587
82
    int64_t num_scanned = 0;
5588
82
    int64_t num_expired = 0;
5589
82
    int64_t num_prepare = 0;
5590
82
    int64_t num_compacted = 0;
5591
82
    int64_t num_empty_rowset = 0;
5592
82
    size_t total_rowset_key_size = 0;
5593
82
    size_t total_rowset_value_size = 0;
5594
82
    size_t expired_rowset_size = 0;
5595
82
    std::atomic_long num_recycled = 0;
5596
82
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5597
5598
82
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5599
82
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5600
82
    std::string recyc_rs_key0;
5601
82
    std::string recyc_rs_key1;
5602
82
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5603
82
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5604
5605
82
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5606
5607
82
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5608
82
    register_recycle_task(task_name, start_time);
5609
5610
82
    DORIS_CLOUD_DEFER {
5611
82
        unregister_recycle_task(task_name);
5612
82
        int64_t cost =
5613
82
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5614
82
        metrics_context.finish_report();
5615
82
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5616
82
                .tag("instance_id", instance_id_)
5617
82
                .tag("num_scanned", num_scanned)
5618
82
                .tag("num_expired", num_expired)
5619
82
                .tag("num_recycled", num_recycled)
5620
82
                .tag("num_recycled.prepare", num_prepare)
5621
82
                .tag("num_recycled.compacted", num_compacted)
5622
82
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5623
82
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5624
82
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5625
82
                .tag("expired_rowset_meta_size", expired_rowset_size);
5626
82
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5610
7
    DORIS_CLOUD_DEFER {
5611
7
        unregister_recycle_task(task_name);
5612
7
        int64_t cost =
5613
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5614
7
        metrics_context.finish_report();
5615
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5616
7
                .tag("instance_id", instance_id_)
5617
7
                .tag("num_scanned", num_scanned)
5618
7
                .tag("num_expired", num_expired)
5619
7
                .tag("num_recycled", num_recycled)
5620
7
                .tag("num_recycled.prepare", num_prepare)
5621
7
                .tag("num_recycled.compacted", num_compacted)
5622
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5623
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5624
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5625
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
5626
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5610
75
    DORIS_CLOUD_DEFER {
5611
75
        unregister_recycle_task(task_name);
5612
75
        int64_t cost =
5613
75
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5614
75
        metrics_context.finish_report();
5615
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5616
75
                .tag("instance_id", instance_id_)
5617
75
                .tag("num_scanned", num_scanned)
5618
75
                .tag("num_expired", num_expired)
5619
75
                .tag("num_recycled", num_recycled)
5620
75
                .tag("num_recycled.prepare", num_prepare)
5621
75
                .tag("num_recycled.compacted", num_compacted)
5622
75
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5623
75
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5624
75
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5625
75
                .tag("expired_rowset_meta_size", expired_rowset_size);
5626
75
    };
5627
5628
82
    struct RecycleRowsetEntry {
5629
82
        std::string key;
5630
82
        doris::RowsetMetaCloudPB meta;
5631
82
    };
5632
82
    struct RecycleRowsetDeleteJob {
5633
82
        std::vector<std::string> keys;
5634
82
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
5635
82
    };
5636
    // Store the scanned recycle key with rowset meta. The scanned key is the actual KV key to delete.
5637
82
    std::vector<RecycleRowsetEntry> rowsets;
5638
82
    int64_t current_tablet_id = -1;
5639
82
    int64_t recycled_rowset_count_for_current_tablet = 0;
5640
82
    bool current_tablet_skip_logged = false;
5641
82
    std::string next_scan_begin;
5642
82
    const int64_t rowset_batch_size_per_tablet =
5643
82
            std::max(1, config::recycle_rowsets_per_tablet_batch_size);
5644
82
    const int64_t delete_rowset_batch_size =
5645
82
            std::min(500000, config::recycle_rowsets_delete_batch_size);
5646
4.33k
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5647
4.33k
        if (current_tablet_id != tablet_id) {
5648
48
            current_tablet_id = tablet_id;
5649
48
            recycled_rowset_count_for_current_tablet = 0;
5650
48
            current_tablet_skip_logged = false;
5651
48
        }
5652
4.33k
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5653
7
            if (!current_tablet_skip_logged) {
5654
7
                LOG_INFO(
5655
7
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5656
7
                        .tag("instance_id", instance_id_)
5657
7
                        .tag("tablet_id", tablet_id)
5658
7
                        .tag("limit", rowset_batch_size_per_tablet);
5659
7
                current_tablet_skip_logged = true;
5660
7
            }
5661
7
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5662
7
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5663
7
            return false;
5664
7
        }
5665
4.32k
        ++recycled_rowset_count_for_current_tablet;
5666
4.32k
        return true;
5667
4.33k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_6clEl
Line
Count
Source
5646
7
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5647
7
        if (current_tablet_id != tablet_id) {
5648
7
            current_tablet_id = tablet_id;
5649
7
            recycled_rowset_count_for_current_tablet = 0;
5650
7
            current_tablet_skip_logged = false;
5651
7
        }
5652
7
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5653
0
            if (!current_tablet_skip_logged) {
5654
0
                LOG_INFO(
5655
0
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5656
0
                        .tag("instance_id", instance_id_)
5657
0
                        .tag("tablet_id", tablet_id)
5658
0
                        .tag("limit", rowset_batch_size_per_tablet);
5659
0
                current_tablet_skip_logged = true;
5660
0
            }
5661
0
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5662
0
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5663
0
            return false;
5664
0
        }
5665
7
        ++recycled_rowset_count_for_current_tablet;
5666
7
        return true;
5667
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_6clEl
Line
Count
Source
5646
4.32k
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5647
4.32k
        if (current_tablet_id != tablet_id) {
5648
41
            current_tablet_id = tablet_id;
5649
41
            recycled_rowset_count_for_current_tablet = 0;
5650
41
            current_tablet_skip_logged = false;
5651
41
        }
5652
4.32k
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5653
7
            if (!current_tablet_skip_logged) {
5654
7
                LOG_INFO(
5655
7
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5656
7
                        .tag("instance_id", instance_id_)
5657
7
                        .tag("tablet_id", tablet_id)
5658
7
                        .tag("limit", rowset_batch_size_per_tablet);
5659
7
                current_tablet_skip_logged = true;
5660
7
            }
5661
7
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5662
7
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5663
7
            return false;
5664
7
        }
5665
4.32k
        ++recycled_rowset_count_for_current_tablet;
5666
4.32k
        return true;
5667
4.32k
    };
5668
4.33k
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5669
4.33k
        if (next_scan_begin.empty()) {
5670
4.32k
            return false;
5671
4.32k
        }
5672
7
        *begin = std::move(next_scan_begin);
5673
7
        next_scan_begin.clear();
5674
7
        return true;
5675
4.33k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clEPNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5668
7
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5669
7
        if (next_scan_begin.empty()) {
5670
7
            return false;
5671
7
        }
5672
0
        *begin = std::move(next_scan_begin);
5673
0
        next_scan_begin.clear();
5674
0
        return true;
5675
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clEPNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5668
4.32k
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5669
4.32k
        if (next_scan_begin.empty()) {
5670
4.32k
            return false;
5671
4.32k
        }
5672
7
        *begin = std::move(next_scan_begin);
5673
7
        next_scan_begin.clear();
5674
7
        return true;
5675
4.32k
    };
5676
5677
82
    std::vector<std::string> rowset_keys_to_mark_recycled;
5678
82
    std::vector<std::string> rowset_keys_to_abort_job;
5679
5680
82
    std::mutex async_recycled_rowset_keys_mutex;
5681
82
    std::vector<std::string> async_recycled_rowset_keys;
5682
82
    std::vector<std::string> rowset_keys_without_data;
5683
82
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5684
82
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5685
82
    worker_pool->start();
5686
82
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5687
903
                                            int64_t tablet_id, const std::string& rowset_id) {
5688
        // Try to delete rowset data in background thread
5689
903
        int ret = worker_pool->submit_with_timeout(
5690
903
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5691
829
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5692
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5693
0
                        return;
5694
0
                    }
5695
829
                    std::vector<std::string> keys;
5696
829
                    {
5697
829
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5698
829
                        async_recycled_rowset_keys.push_back(std::move(key));
5699
829
                        if (async_recycled_rowset_keys.size() > 100) {
5700
5
                            keys.swap(async_recycled_rowset_keys);
5701
5
                        }
5702
829
                    }
5703
829
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5704
829
                    if (keys.empty()) return;
5705
5
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5706
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5707
0
                                     << instance_id_;
5708
5
                    } else {
5709
5
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5710
5
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5711
5
                                           num_recycled, start_time);
5712
5
                    }
5713
5
                },
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
5690
1
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5691
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5692
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5693
0
                        return;
5694
0
                    }
5695
1
                    std::vector<std::string> keys;
5696
1
                    {
5697
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5698
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5699
1
                        if (async_recycled_rowset_keys.size() > 100) {
5700
0
                            keys.swap(async_recycled_rowset_keys);
5701
0
                        }
5702
1
                    }
5703
1
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5704
1
                    if (keys.empty()) return;
5705
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5706
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5707
0
                                     << instance_id_;
5708
0
                    } else {
5709
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5710
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5711
0
                                           num_recycled, start_time);
5712
0
                    }
5713
0
                },
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
5690
828
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5691
828
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5692
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5693
0
                        return;
5694
0
                    }
5695
828
                    std::vector<std::string> keys;
5696
828
                    {
5697
828
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5698
828
                        async_recycled_rowset_keys.push_back(std::move(key));
5699
828
                        if (async_recycled_rowset_keys.size() > 100) {
5700
5
                            keys.swap(async_recycled_rowset_keys);
5701
5
                        }
5702
828
                    }
5703
828
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5704
828
                    if (keys.empty()) return;
5705
5
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5706
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5707
0
                                     << instance_id_;
5708
5
                    } else {
5709
5
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5710
5
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5711
5
                                           num_recycled, start_time);
5712
5
                    }
5713
5
                },
5714
903
                0);
5715
903
        if (ret == 0) return 0;
5716
        // Submit task failed, delete rowset data in current thread
5717
74
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5718
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5719
0
            return -1;
5720
0
        }
5721
74
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5722
0
            return -1;
5723
0
        }
5724
74
        rowset_keys_without_data.push_back(std::move(key));
5725
74
        return 0;
5726
74
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
5687
1
                                            int64_t tablet_id, const std::string& rowset_id) {
5688
        // Try to delete rowset data in background thread
5689
1
        int ret = worker_pool->submit_with_timeout(
5690
1
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5691
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5692
1
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5693
1
                        return;
5694
1
                    }
5695
1
                    std::vector<std::string> keys;
5696
1
                    {
5697
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5698
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5699
1
                        if (async_recycled_rowset_keys.size() > 100) {
5700
1
                            keys.swap(async_recycled_rowset_keys);
5701
1
                        }
5702
1
                    }
5703
1
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5704
1
                    if (keys.empty()) return;
5705
1
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5706
1
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5707
1
                                     << instance_id_;
5708
1
                    } else {
5709
1
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5710
1
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5711
1
                                           num_recycled, start_time);
5712
1
                    }
5713
1
                },
5714
1
                0);
5715
1
        if (ret == 0) return 0;
5716
        // Submit task failed, delete rowset data in current thread
5717
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5718
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5719
0
            return -1;
5720
0
        }
5721
0
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5722
0
            return -1;
5723
0
        }
5724
0
        rowset_keys_without_data.push_back(std::move(key));
5725
0
        return 0;
5726
0
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
5687
902
                                            int64_t tablet_id, const std::string& rowset_id) {
5688
        // Try to delete rowset data in background thread
5689
902
        int ret = worker_pool->submit_with_timeout(
5690
902
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5691
902
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5692
902
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5693
902
                        return;
5694
902
                    }
5695
902
                    std::vector<std::string> keys;
5696
902
                    {
5697
902
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5698
902
                        async_recycled_rowset_keys.push_back(std::move(key));
5699
902
                        if (async_recycled_rowset_keys.size() > 100) {
5700
902
                            keys.swap(async_recycled_rowset_keys);
5701
902
                        }
5702
902
                    }
5703
902
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5704
902
                    if (keys.empty()) return;
5705
902
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5706
902
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5707
902
                                     << instance_id_;
5708
902
                    } else {
5709
902
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5710
902
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5711
902
                                           num_recycled, start_time);
5712
902
                    }
5713
902
                },
5714
902
                0);
5715
902
        if (ret == 0) return 0;
5716
        // Submit task failed, delete rowset data in current thread
5717
74
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5718
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5719
0
            return -1;
5720
0
        }
5721
74
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5722
0
            return -1;
5723
0
        }
5724
74
        rowset_keys_without_data.push_back(std::move(key));
5725
74
        return 0;
5726
74
    };
5727
5728
82
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5729
5730
4.33k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5731
4.33k
        ++num_scanned;
5732
4.33k
        total_rowset_key_size += k.size();
5733
4.33k
        total_rowset_value_size += v.size();
5734
4.33k
        RecycleRowsetPB rowset;
5735
4.33k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5736
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5737
0
            return -1;
5738
0
        }
5739
5740
4.33k
        int64_t current_time = ::time(nullptr);
5741
4.33k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5742
5743
4.33k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5744
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5745
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5746
4.33k
        if (current_time < expiration) { // not expired
5747
0
            return 0;
5748
0
        }
5749
4.33k
        ++num_expired;
5750
4.33k
        expired_rowset_size += v.size();
5751
5752
4.33k
        int64_t tablet_id =
5753
4.33k
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5754
4.33k
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5755
7
            return 0;
5756
7
        }
5757
5758
4.32k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5759
252
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5760
                // in old version, keep this key-value pair and it needs to be checked manually
5761
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5762
0
                return -1;
5763
0
            }
5764
252
            if (rowset.resource_id().empty()) [[unlikely]] {
5765
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5766
2
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5767
2
                          << hex(k) << " value=" << proto_to_json(rowset);
5768
2
                rowset_keys_without_data.emplace_back(k);
5769
2
                return 0;
5770
2
            }
5771
            // decode rowset_id
5772
250
            auto k1 = k;
5773
250
            k1.remove_prefix(1);
5774
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5775
250
            decode_key(&k1, &out);
5776
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5777
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5778
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5779
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5780
250
                      << " task_type=" << metrics_context.operation_type;
5781
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5782
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5783
0
                return -1;
5784
0
            }
5785
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5786
250
            metrics_context.total_recycled_num++;
5787
250
            segment_metrics_context_.total_recycled_data_size +=
5788
250
                    rowset.rowset_meta().total_disk_size();
5789
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5790
250
            return 0;
5791
250
        }
5792
4.07k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5793
5794
        // TODO(plat1ko): check rowset not referenced
5795
4.07k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5796
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5797
0
                LOG_INFO("recycle rowset that has empty resource id");
5798
0
            } else {
5799
                // other situations, keep this key-value pair and it needs to be checked manually
5800
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5801
0
                return -1;
5802
0
            }
5803
0
        }
5804
4.07k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5805
4.07k
                  << " tablet_id=" << rowset_meta->tablet_id()
5806
4.07k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5807
4.07k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5808
4.07k
                  << "] txn_id=" << rowset_meta->txn_id()
5809
4.07k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5810
4.07k
                  << " rowset_meta_size=" << v.size()
5811
4.07k
                  << " creation_time=" << rowset_meta->creation_time()
5812
4.07k
                  << " task_type=" << metrics_context.operation_type;
5813
4.07k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5814
938
            if (config::enable_mark_delete_rowset_before_recycle) {
5815
23
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5816
13
                    rowset_keys_to_mark_recycled.emplace_back(k);
5817
13
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5818
13
                                 "kv "
5819
13
                                 "at next turn, instance_id="
5820
13
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5821
13
                              << " version=[" << rowset_meta->start_version() << '-'
5822
13
                              << rowset_meta->end_version() << "]";
5823
13
                    return 0;
5824
13
                }
5825
23
            }
5826
5827
925
            num_prepare += 1;
5828
925
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5829
925
                rowset_meta->end_version() != 1) {
5830
273
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5831
272
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5832
272
                                 "instance_id="
5833
272
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5834
272
                              << " version=[" << rowset_meta->start_version() << '-'
5835
272
                              << rowset_meta->end_version() << "]";
5836
272
                    rowset_keys_to_abort_job.emplace_back(k);
5837
272
                    return 0;
5838
272
                }
5839
273
            }
5840
653
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5841
653
                                             rowset_meta->tablet_id(),
5842
653
                                             rowset_meta->rowset_id_v2()) != 0) {
5843
0
                return -1;
5844
0
            }
5845
3.13k
        } else {
5846
3.13k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5847
3.13k
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
5848
3.13k
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
5849
3.13k
            } else {
5850
3
                ++num_empty_rowset;
5851
3
                rowset_keys_without_data.emplace_back(k);
5852
3
            }
5853
3.13k
        }
5854
3.79k
        return 0;
5855
4.07k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5730
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5731
7
        ++num_scanned;
5732
7
        total_rowset_key_size += k.size();
5733
7
        total_rowset_value_size += v.size();
5734
7
        RecycleRowsetPB rowset;
5735
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5736
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5737
0
            return -1;
5738
0
        }
5739
5740
7
        int64_t current_time = ::time(nullptr);
5741
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5742
5743
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5744
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5745
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5746
7
        if (current_time < expiration) { // not expired
5747
0
            return 0;
5748
0
        }
5749
7
        ++num_expired;
5750
7
        expired_rowset_size += v.size();
5751
5752
7
        int64_t tablet_id =
5753
7
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5754
7
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5755
0
            return 0;
5756
0
        }
5757
5758
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5759
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5760
                // in old version, keep this key-value pair and it needs to be checked manually
5761
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5762
0
                return -1;
5763
0
            }
5764
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5765
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5766
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5767
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5768
0
                rowset_keys_without_data.emplace_back(k);
5769
0
                return 0;
5770
0
            }
5771
            // decode rowset_id
5772
0
            auto k1 = k;
5773
0
            k1.remove_prefix(1);
5774
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5775
0
            decode_key(&k1, &out);
5776
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5777
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5778
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5779
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5780
0
                      << " task_type=" << metrics_context.operation_type;
5781
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5782
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5783
0
                return -1;
5784
0
            }
5785
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5786
0
            metrics_context.total_recycled_num++;
5787
0
            segment_metrics_context_.total_recycled_data_size +=
5788
0
                    rowset.rowset_meta().total_disk_size();
5789
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5790
0
            return 0;
5791
0
        }
5792
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
5793
5794
        // TODO(plat1ko): check rowset not referenced
5795
7
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5796
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5797
0
                LOG_INFO("recycle rowset that has empty resource id");
5798
0
            } else {
5799
                // other situations, keep this key-value pair and it needs to be checked manually
5800
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5801
0
                return -1;
5802
0
            }
5803
0
        }
5804
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5805
7
                  << " tablet_id=" << rowset_meta->tablet_id()
5806
7
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5807
7
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5808
7
                  << "] txn_id=" << rowset_meta->txn_id()
5809
7
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5810
7
                  << " rowset_meta_size=" << v.size()
5811
7
                  << " creation_time=" << rowset_meta->creation_time()
5812
7
                  << " task_type=" << metrics_context.operation_type;
5813
7
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5814
7
            if (config::enable_mark_delete_rowset_before_recycle) {
5815
6
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5816
4
                    rowset_keys_to_mark_recycled.emplace_back(k);
5817
4
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5818
4
                                 "kv "
5819
4
                                 "at next turn, instance_id="
5820
4
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5821
4
                              << " version=[" << rowset_meta->start_version() << '-'
5822
4
                              << rowset_meta->end_version() << "]";
5823
4
                    return 0;
5824
4
                }
5825
6
            }
5826
5827
3
            num_prepare += 1;
5828
3
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5829
3
                rowset_meta->end_version() != 1) {
5830
2
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5831
2
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5832
2
                                 "instance_id="
5833
2
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5834
2
                              << " version=[" << rowset_meta->start_version() << '-'
5835
2
                              << rowset_meta->end_version() << "]";
5836
2
                    rowset_keys_to_abort_job.emplace_back(k);
5837
2
                    return 0;
5838
2
                }
5839
2
            }
5840
1
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5841
1
                                             rowset_meta->tablet_id(),
5842
1
                                             rowset_meta->rowset_id_v2()) != 0) {
5843
0
                return -1;
5844
0
            }
5845
1
        } else {
5846
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5847
0
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
5848
0
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
5849
0
            } else {
5850
0
                ++num_empty_rowset;
5851
0
                rowset_keys_without_data.emplace_back(k);
5852
0
            }
5853
0
        }
5854
1
        return 0;
5855
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5730
4.32k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5731
4.32k
        ++num_scanned;
5732
4.32k
        total_rowset_key_size += k.size();
5733
4.32k
        total_rowset_value_size += v.size();
5734
4.32k
        RecycleRowsetPB rowset;
5735
4.32k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5736
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5737
0
            return -1;
5738
0
        }
5739
5740
4.32k
        int64_t current_time = ::time(nullptr);
5741
4.32k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5742
5743
4.32k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5744
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5745
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5746
4.32k
        if (current_time < expiration) { // not expired
5747
0
            return 0;
5748
0
        }
5749
4.32k
        ++num_expired;
5750
4.32k
        expired_rowset_size += v.size();
5751
5752
4.32k
        int64_t tablet_id =
5753
4.32k
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5754
4.32k
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5755
7
            return 0;
5756
7
        }
5757
5758
4.32k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5759
252
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5760
                // in old version, keep this key-value pair and it needs to be checked manually
5761
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5762
0
                return -1;
5763
0
            }
5764
252
            if (rowset.resource_id().empty()) [[unlikely]] {
5765
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5766
2
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5767
2
                          << hex(k) << " value=" << proto_to_json(rowset);
5768
2
                rowset_keys_without_data.emplace_back(k);
5769
2
                return 0;
5770
2
            }
5771
            // decode rowset_id
5772
250
            auto k1 = k;
5773
250
            k1.remove_prefix(1);
5774
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5775
250
            decode_key(&k1, &out);
5776
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5777
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5778
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5779
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5780
250
                      << " task_type=" << metrics_context.operation_type;
5781
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5782
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5783
0
                return -1;
5784
0
            }
5785
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5786
250
            metrics_context.total_recycled_num++;
5787
250
            segment_metrics_context_.total_recycled_data_size +=
5788
250
                    rowset.rowset_meta().total_disk_size();
5789
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5790
250
            return 0;
5791
250
        }
5792
4.07k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5793
5794
        // TODO(plat1ko): check rowset not referenced
5795
4.07k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5796
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5797
0
                LOG_INFO("recycle rowset that has empty resource id");
5798
0
            } else {
5799
                // other situations, keep this key-value pair and it needs to be checked manually
5800
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5801
0
                return -1;
5802
0
            }
5803
0
        }
5804
4.07k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5805
4.07k
                  << " tablet_id=" << rowset_meta->tablet_id()
5806
4.07k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5807
4.07k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5808
4.07k
                  << "] txn_id=" << rowset_meta->txn_id()
5809
4.07k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5810
4.07k
                  << " rowset_meta_size=" << v.size()
5811
4.07k
                  << " creation_time=" << rowset_meta->creation_time()
5812
4.07k
                  << " task_type=" << metrics_context.operation_type;
5813
4.07k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5814
931
            if (config::enable_mark_delete_rowset_before_recycle) {
5815
17
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5816
9
                    rowset_keys_to_mark_recycled.emplace_back(k);
5817
9
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5818
9
                                 "kv "
5819
9
                                 "at next turn, instance_id="
5820
9
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5821
9
                              << " version=[" << rowset_meta->start_version() << '-'
5822
9
                              << rowset_meta->end_version() << "]";
5823
9
                    return 0;
5824
9
                }
5825
17
            }
5826
5827
922
            num_prepare += 1;
5828
922
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5829
922
                rowset_meta->end_version() != 1) {
5830
271
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5831
270
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5832
270
                                 "instance_id="
5833
270
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5834
270
                              << " version=[" << rowset_meta->start_version() << '-'
5835
270
                              << rowset_meta->end_version() << "]";
5836
270
                    rowset_keys_to_abort_job.emplace_back(k);
5837
270
                    return 0;
5838
270
                }
5839
271
            }
5840
652
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5841
652
                                             rowset_meta->tablet_id(),
5842
652
                                             rowset_meta->rowset_id_v2()) != 0) {
5843
0
                return -1;
5844
0
            }
5845
3.13k
        } else {
5846
3.13k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5847
3.13k
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
5848
3.13k
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
5849
3.13k
            } else {
5850
3
                ++num_empty_rowset;
5851
3
                rowset_keys_without_data.emplace_back(k);
5852
3
            }
5853
3.13k
        }
5854
3.79k
        return 0;
5855
4.07k
    };
5856
5857
82
    auto submit_delete_rowset_data_job = [&](std::vector<std::string> rowset_keys,
5858
82
                                             std::map<std::string, RowsetMetaCloudPB> rowsets) {
5859
23
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys),
5860
23
                             rowsets_to_delete = std::move(rowsets)]() {
5861
23
            if (!rowsets_to_delete.empty() &&
5862
23
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5863
18
                                   metrics_context) != 0) {
5864
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5865
0
                return;
5866
0
            }
5867
3.13k
            for (const auto& [_, rs] : rowsets_to_delete) {
5868
3.13k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5869
0
                    return;
5870
0
                }
5871
3.13k
            }
5872
23
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5873
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5874
0
                return;
5875
0
            }
5876
5877
23
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5878
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
5860
23
                             rowsets_to_delete = std::move(rowsets)]() {
5861
23
            if (!rowsets_to_delete.empty() &&
5862
23
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5863
18
                                   metrics_context) != 0) {
5864
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5865
0
                return;
5866
0
            }
5867
3.13k
            for (const auto& [_, rs] : rowsets_to_delete) {
5868
3.13k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5869
0
                    return;
5870
0
                }
5871
3.13k
            }
5872
23
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5873
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5874
0
                return;
5875
0
            }
5876
5877
23
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5878
23
        });
5879
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
5858
23
                                             std::map<std::string, RowsetMetaCloudPB> rowsets) {
5859
23
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys),
5860
23
                             rowsets_to_delete = std::move(rowsets)]() {
5861
23
            if (!rowsets_to_delete.empty() &&
5862
23
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5863
23
                                   metrics_context) != 0) {
5864
23
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5865
23
                return;
5866
23
            }
5867
23
            for (const auto& [_, rs] : rowsets_to_delete) {
5868
23
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5869
23
                    return;
5870
23
                }
5871
23
            }
5872
23
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5873
23
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5874
23
                return;
5875
23
            }
5876
5877
23
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5878
23
        });
5879
23
    };
5880
5881
82
    bool scan_finished = false;
5882
144
    auto loop_done = [&]() -> int {
5883
144
        std::vector<std::string> mark_keys_to_process;
5884
144
        std::vector<std::string> abort_job_keys_to_process;
5885
144
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5886
144
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5887
144
        if (!mark_keys_to_process.empty()) {
5888
11
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5889
11
                    *worker_pool, std::move(mark_keys_to_process));
5890
11
        }
5891
144
        if (!abort_job_keys_to_process.empty()) {
5892
15
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5893
15
                                               &num_recycled);
5894
15
        }
5895
144
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
5896
62
            return 0;
5897
62
        }
5898
5899
82
        DORIS_CLOUD_DEFER {
5900
            // if return -1 in loop done, rowset info in memory is not cleared,
5901
            // it can lead to memory accumulation
5902
82
            rowset_keys_without_data.clear();
5903
82
            rowsets.clear();
5904
82
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clEvENKUlvE_clEv
Line
Count
Source
5899
7
        DORIS_CLOUD_DEFER {
5900
            // if return -1 in loop done, rowset info in memory is not cleared,
5901
            // it can lead to memory accumulation
5902
7
            rowset_keys_without_data.clear();
5903
7
            rowsets.clear();
5904
7
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clEvENKUlvE_clEv
Line
Count
Source
5899
75
        DORIS_CLOUD_DEFER {
5900
            // if return -1 in loop done, rowset info in memory is not cleared,
5901
            // it can lead to memory accumulation
5902
75
            rowset_keys_without_data.clear();
5903
75
            rowsets.clear();
5904
75
        };
5905
82
        std::random_device rd;
5906
82
        std::mt19937 g(rd());
5907
82
        std::ranges::shuffle(rowsets, g);
5908
5909
82
        std::vector<std::string> rowset_keys_to_delete;
5910
82
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
5911
        // rowset_id -> rowset_meta
5912
        // store rowset id and meta for statistics rs size when delete
5913
82
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5914
5915
82
        size_t rowsets_per_batch_size = 0;
5916
3.13k
        for (auto& rowset : rowsets) {
5917
3.13k
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
5918
3.13k
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
5919
3.13k
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
5920
3.12k
                continue;
5921
3.12k
            }
5922
5923
8
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5924
8
                                          std::move(rowsets_to_delete));
5925
8
            rowsets_per_batch_size = 0;
5926
8
            rowset_keys_to_delete.clear();
5927
8
            rowsets_to_delete.clear();
5928
8
        }
5929
5930
82
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
5931
10
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5932
10
                                          std::move(rowsets_to_delete));
5933
10
        }
5934
5935
87
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
5936
5
            auto begin = rowset_keys_without_data.begin() + i;
5937
5
            auto end = rowset_keys_without_data.begin() +
5938
5
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
5939
5
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
5940
5
                                                           std::make_move_iterator(end));
5941
5
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
5942
5
        }
5943
5944
82
        return 0;
5945
144
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clEv
Line
Count
Source
5882
14
    auto loop_done = [&]() -> int {
5883
14
        std::vector<std::string> mark_keys_to_process;
5884
14
        std::vector<std::string> abort_job_keys_to_process;
5885
14
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5886
14
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5887
14
        if (!mark_keys_to_process.empty()) {
5888
4
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5889
4
                    *worker_pool, std::move(mark_keys_to_process));
5890
4
        }
5891
14
        if (!abort_job_keys_to_process.empty()) {
5892
2
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5893
2
                                               &num_recycled);
5894
2
        }
5895
14
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
5896
7
            return 0;
5897
7
        }
5898
5899
7
        DORIS_CLOUD_DEFER {
5900
            // if return -1 in loop done, rowset info in memory is not cleared,
5901
            // it can lead to memory accumulation
5902
7
            rowset_keys_without_data.clear();
5903
7
            rowsets.clear();
5904
7
        };
5905
7
        std::random_device rd;
5906
7
        std::mt19937 g(rd());
5907
7
        std::ranges::shuffle(rowsets, g);
5908
5909
7
        std::vector<std::string> rowset_keys_to_delete;
5910
7
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
5911
        // rowset_id -> rowset_meta
5912
        // store rowset id and meta for statistics rs size when delete
5913
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5914
5915
7
        size_t rowsets_per_batch_size = 0;
5916
7
        for (auto& rowset : rowsets) {
5917
0
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
5918
0
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
5919
0
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
5920
0
                continue;
5921
0
            }
5922
5923
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5924
0
                                          std::move(rowsets_to_delete));
5925
0
            rowsets_per_batch_size = 0;
5926
0
            rowset_keys_to_delete.clear();
5927
0
            rowsets_to_delete.clear();
5928
0
        }
5929
5930
7
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
5931
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5932
0
                                          std::move(rowsets_to_delete));
5933
0
        }
5934
5935
7
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
5936
0
            auto begin = rowset_keys_without_data.begin() + i;
5937
0
            auto end = rowset_keys_without_data.begin() +
5938
0
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
5939
0
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
5940
0
                                                           std::make_move_iterator(end));
5941
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
5942
0
        }
5943
5944
7
        return 0;
5945
14
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clEv
Line
Count
Source
5882
130
    auto loop_done = [&]() -> int {
5883
130
        std::vector<std::string> mark_keys_to_process;
5884
130
        std::vector<std::string> abort_job_keys_to_process;
5885
130
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5886
130
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5887
130
        if (!mark_keys_to_process.empty()) {
5888
7
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5889
7
                    *worker_pool, std::move(mark_keys_to_process));
5890
7
        }
5891
130
        if (!abort_job_keys_to_process.empty()) {
5892
13
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5893
13
                                               &num_recycled);
5894
13
        }
5895
130
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
5896
55
            return 0;
5897
55
        }
5898
5899
75
        DORIS_CLOUD_DEFER {
5900
            // if return -1 in loop done, rowset info in memory is not cleared,
5901
            // it can lead to memory accumulation
5902
75
            rowset_keys_without_data.clear();
5903
75
            rowsets.clear();
5904
75
        };
5905
75
        std::random_device rd;
5906
75
        std::mt19937 g(rd());
5907
75
        std::ranges::shuffle(rowsets, g);
5908
5909
75
        std::vector<std::string> rowset_keys_to_delete;
5910
75
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
5911
        // rowset_id -> rowset_meta
5912
        // store rowset id and meta for statistics rs size when delete
5913
75
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5914
5915
75
        size_t rowsets_per_batch_size = 0;
5916
3.13k
        for (auto& rowset : rowsets) {
5917
3.13k
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
5918
3.13k
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
5919
3.13k
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
5920
3.12k
                continue;
5921
3.12k
            }
5922
5923
8
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5924
8
                                          std::move(rowsets_to_delete));
5925
8
            rowsets_per_batch_size = 0;
5926
8
            rowset_keys_to_delete.clear();
5927
8
            rowsets_to_delete.clear();
5928
8
        }
5929
5930
75
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
5931
10
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5932
10
                                          std::move(rowsets_to_delete));
5933
10
        }
5934
5935
80
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
5936
5
            auto begin = rowset_keys_without_data.begin() + i;
5937
5
            auto end = rowset_keys_without_data.begin() +
5938
5
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
5939
5
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
5940
5
                                                           std::make_move_iterator(end));
5941
5
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
5942
5
        }
5943
5944
75
        return 0;
5945
130
    };
5946
5947
82
    if (config::enable_recycler_stats_metrics) {
5948
0
        scan_and_statistics_rowsets();
5949
0
    }
5950
    // recycle_func and loop_done for scan and recycle
5951
82
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv), loop_done,
5952
82
                               std::move(next_scan_begin_getter));
5953
82
    scan_finished = true;
5954
    // if the size of rowsets is always less than delete_rowset_batch_size
5955
    // it need to submit the task directly
5956
    // else if the size of rowsets is greater than delete_rowset_batch_size,
5957
    // but there are residual, whether due to failed or unsuccessful cleanup, this behavior is idempotent
5958
82
    if (loop_done() != 0) {
5959
0
        ret = -1;
5960
0
    }
5961
5962
82
    worker_pool->stop();
5963
5964
82
    if (!async_recycled_rowset_keys.empty()) {
5965
6
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5966
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5967
0
            return -1;
5968
6
        } else {
5969
6
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5970
6
        }
5971
6
    }
5972
5973
    // Report final metrics after all concurrent tasks completed
5974
82
    segment_metrics_context_.report();
5975
82
    metrics_context.report();
5976
5977
82
    return ret;
5978
82
}
5979
5980
int InstanceRecycler::next_recycle_rowset_tablet_key(const std::string& instance_id,
5981
1
                                                     int64_t tablet_id, std::string* next_key) {
5982
1
    DCHECK(next_key != nullptr);
5983
1
    if (tablet_id == std::numeric_limits<int64_t>::max()) {
5984
0
        return -1;
5985
0
    }
5986
1
    *next_key = recycle_rowset_key({instance_id, tablet_id + 1, ""});
5987
1
    return 0;
5988
1
}
5989
5990
13
int InstanceRecycler::recycle_restore_jobs() {
5991
13
    const std::string task_name = "recycle_restore_jobs";
5992
13
    int64_t num_scanned = 0;
5993
13
    int64_t num_expired = 0;
5994
13
    int64_t num_recycled = 0;
5995
13
    int64_t num_aborted = 0;
5996
5997
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5998
5999
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
6000
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
6001
13
    std::string restore_job_key0;
6002
13
    std::string restore_job_key1;
6003
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
6004
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
6005
6006
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
6007
6008
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6009
13
    register_recycle_task(task_name, start_time);
6010
6011
13
    DORIS_CLOUD_DEFER {
6012
13
        unregister_recycle_task(task_name);
6013
13
        int64_t cost =
6014
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6015
13
        metrics_context.finish_report();
6016
6017
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
6018
13
                .tag("instance_id", instance_id_)
6019
13
                .tag("num_scanned", num_scanned)
6020
13
                .tag("num_expired", num_expired)
6021
13
                .tag("num_recycled", num_recycled)
6022
13
                .tag("num_aborted", num_aborted);
6023
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
6011
13
    DORIS_CLOUD_DEFER {
6012
13
        unregister_recycle_task(task_name);
6013
13
        int64_t cost =
6014
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6015
13
        metrics_context.finish_report();
6016
6017
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
6018
13
                .tag("instance_id", instance_id_)
6019
13
                .tag("num_scanned", num_scanned)
6020
13
                .tag("num_expired", num_expired)
6021
13
                .tag("num_recycled", num_recycled)
6022
13
                .tag("num_aborted", num_aborted);
6023
13
    };
6024
6025
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6026
6027
13
    std::vector<std::string_view> restore_job_keys;
6028
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
6029
41
        ++num_scanned;
6030
41
        RestoreJobCloudPB restore_job_pb;
6031
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
6032
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
6033
0
            return -1;
6034
0
        }
6035
41
        int64_t expiration =
6036
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
6037
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
6038
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
6039
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
6040
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
6041
0
                   << " state=" << restore_job_pb.state();
6042
41
        int64_t current_time = ::time(nullptr);
6043
41
        if (current_time < expiration) { // not expired
6044
0
            return 0;
6045
0
        }
6046
41
        ++num_expired;
6047
6048
41
        int64_t tablet_id = restore_job_pb.tablet_id();
6049
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
6050
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
6051
6052
41
        std::unique_ptr<Transaction> txn;
6053
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6054
41
        if (err != TxnErrorCode::TXN_OK) {
6055
0
            LOG_WARNING("failed to recycle restore job")
6056
0
                    .tag("err", err)
6057
0
                    .tag("tablet id", tablet_id)
6058
0
                    .tag("instance_id", instance_id_)
6059
0
                    .tag("reason", "failed to create txn");
6060
0
            return -1;
6061
0
        }
6062
6063
41
        std::string val;
6064
41
        err = txn->get(k, &val);
6065
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
6066
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
6067
0
            return 0;
6068
0
        }
6069
41
        if (err != TxnErrorCode::TXN_OK) {
6070
0
            LOG_WARNING("failed to get kv");
6071
0
            return -1;
6072
0
        }
6073
41
        restore_job_pb.Clear();
6074
41
        if (!restore_job_pb.ParseFromString(val)) {
6075
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
6076
0
            return -1;
6077
0
        }
6078
6079
        // PREPARED or COMMITTED, change state to DROPPED and return
6080
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
6081
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
6082
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
6083
0
            restore_job_pb.set_need_recycle_data(true);
6084
0
            txn->put(k, restore_job_pb.SerializeAsString());
6085
0
            err = txn->commit();
6086
0
            if (err != TxnErrorCode::TXN_OK) {
6087
0
                LOG_WARNING("failed to commit txn: {}", err);
6088
0
                return -1;
6089
0
            }
6090
0
            num_aborted++;
6091
0
            return 0;
6092
0
        }
6093
6094
        // Change state to RECYCLING
6095
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
6096
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
6097
21
            txn->put(k, restore_job_pb.SerializeAsString());
6098
21
            err = txn->commit();
6099
21
            if (err != TxnErrorCode::TXN_OK) {
6100
0
                LOG_WARNING("failed to commit txn: {}", err);
6101
0
                return -1;
6102
0
            }
6103
21
            return 0;
6104
21
        }
6105
6106
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
6107
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
6108
6109
        // Recycle all data associated with the restore job.
6110
        // This includes rowsets, segments, and related resources.
6111
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
6112
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
6113
0
            LOG_WARNING("failed to recycle tablet")
6114
0
                    .tag("tablet_id", tablet_id)
6115
0
                    .tag("instance_id", instance_id_);
6116
0
            return -1;
6117
0
        }
6118
6119
        // delete all restore job rowset kv
6120
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
6121
6122
20
        err = txn->commit();
6123
20
        if (err != TxnErrorCode::TXN_OK) {
6124
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
6125
0
                    .tag("err", err)
6126
0
                    .tag("tablet id", tablet_id)
6127
0
                    .tag("instance_id", instance_id_)
6128
0
                    .tag("reason", "failed to commit txn");
6129
0
            return -1;
6130
0
        }
6131
6132
20
        metrics_context.total_recycled_num = ++num_recycled;
6133
20
        metrics_context.report();
6134
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6135
20
        restore_job_keys.push_back(k);
6136
6137
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
6138
20
                  << " tablet_id=" << tablet_id;
6139
20
        return 0;
6140
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
6028
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
6029
41
        ++num_scanned;
6030
41
        RestoreJobCloudPB restore_job_pb;
6031
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
6032
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
6033
0
            return -1;
6034
0
        }
6035
41
        int64_t expiration =
6036
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
6037
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
6038
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
6039
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
6040
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
6041
0
                   << " state=" << restore_job_pb.state();
6042
41
        int64_t current_time = ::time(nullptr);
6043
41
        if (current_time < expiration) { // not expired
6044
0
            return 0;
6045
0
        }
6046
41
        ++num_expired;
6047
6048
41
        int64_t tablet_id = restore_job_pb.tablet_id();
6049
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
6050
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
6051
6052
41
        std::unique_ptr<Transaction> txn;
6053
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6054
41
        if (err != TxnErrorCode::TXN_OK) {
6055
0
            LOG_WARNING("failed to recycle restore job")
6056
0
                    .tag("err", err)
6057
0
                    .tag("tablet id", tablet_id)
6058
0
                    .tag("instance_id", instance_id_)
6059
0
                    .tag("reason", "failed to create txn");
6060
0
            return -1;
6061
0
        }
6062
6063
41
        std::string val;
6064
41
        err = txn->get(k, &val);
6065
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
6066
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
6067
0
            return 0;
6068
0
        }
6069
41
        if (err != TxnErrorCode::TXN_OK) {
6070
0
            LOG_WARNING("failed to get kv");
6071
0
            return -1;
6072
0
        }
6073
41
        restore_job_pb.Clear();
6074
41
        if (!restore_job_pb.ParseFromString(val)) {
6075
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
6076
0
            return -1;
6077
0
        }
6078
6079
        // PREPARED or COMMITTED, change state to DROPPED and return
6080
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
6081
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
6082
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
6083
0
            restore_job_pb.set_need_recycle_data(true);
6084
0
            txn->put(k, restore_job_pb.SerializeAsString());
6085
0
            err = txn->commit();
6086
0
            if (err != TxnErrorCode::TXN_OK) {
6087
0
                LOG_WARNING("failed to commit txn: {}", err);
6088
0
                return -1;
6089
0
            }
6090
0
            num_aborted++;
6091
0
            return 0;
6092
0
        }
6093
6094
        // Change state to RECYCLING
6095
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
6096
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
6097
21
            txn->put(k, restore_job_pb.SerializeAsString());
6098
21
            err = txn->commit();
6099
21
            if (err != TxnErrorCode::TXN_OK) {
6100
0
                LOG_WARNING("failed to commit txn: {}", err);
6101
0
                return -1;
6102
0
            }
6103
21
            return 0;
6104
21
        }
6105
6106
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
6107
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
6108
6109
        // Recycle all data associated with the restore job.
6110
        // This includes rowsets, segments, and related resources.
6111
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
6112
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
6113
0
            LOG_WARNING("failed to recycle tablet")
6114
0
                    .tag("tablet_id", tablet_id)
6115
0
                    .tag("instance_id", instance_id_);
6116
0
            return -1;
6117
0
        }
6118
6119
        // delete all restore job rowset kv
6120
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
6121
6122
20
        err = txn->commit();
6123
20
        if (err != TxnErrorCode::TXN_OK) {
6124
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
6125
0
                    .tag("err", err)
6126
0
                    .tag("tablet id", tablet_id)
6127
0
                    .tag("instance_id", instance_id_)
6128
0
                    .tag("reason", "failed to commit txn");
6129
0
            return -1;
6130
0
        }
6131
6132
20
        metrics_context.total_recycled_num = ++num_recycled;
6133
20
        metrics_context.report();
6134
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6135
20
        restore_job_keys.push_back(k);
6136
6137
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
6138
20
                  << " tablet_id=" << tablet_id;
6139
20
        return 0;
6140
20
    };
6141
6142
13
    auto loop_done = [&restore_job_keys, this]() -> int {
6143
3
        if (restore_job_keys.empty()) return 0;
6144
1
        DORIS_CLOUD_DEFER {
6145
1
            restore_job_keys.clear();
6146
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6144
1
        DORIS_CLOUD_DEFER {
6145
1
            restore_job_keys.clear();
6146
1
        };
6147
6148
1
        std::unique_ptr<Transaction> txn;
6149
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6150
1
        if (err != TxnErrorCode::TXN_OK) {
6151
0
            LOG_WARNING("failed to recycle restore job")
6152
0
                    .tag("err", err)
6153
0
                    .tag("instance_id", instance_id_)
6154
0
                    .tag("reason", "failed to create txn");
6155
0
            return -1;
6156
0
        }
6157
20
        for (auto& k : restore_job_keys) {
6158
20
            txn->remove(k);
6159
20
        }
6160
1
        err = txn->commit();
6161
1
        if (err != TxnErrorCode::TXN_OK) {
6162
0
            LOG_WARNING("failed to recycle restore job")
6163
0
                    .tag("err", err)
6164
0
                    .tag("instance_id", instance_id_)
6165
0
                    .tag("reason", "failed to commit txn");
6166
0
            return -1;
6167
0
        }
6168
1
        return 0;
6169
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
6142
3
    auto loop_done = [&restore_job_keys, this]() -> int {
6143
3
        if (restore_job_keys.empty()) return 0;
6144
1
        DORIS_CLOUD_DEFER {
6145
1
            restore_job_keys.clear();
6146
1
        };
6147
6148
1
        std::unique_ptr<Transaction> txn;
6149
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6150
1
        if (err != TxnErrorCode::TXN_OK) {
6151
0
            LOG_WARNING("failed to recycle restore job")
6152
0
                    .tag("err", err)
6153
0
                    .tag("instance_id", instance_id_)
6154
0
                    .tag("reason", "failed to create txn");
6155
0
            return -1;
6156
0
        }
6157
20
        for (auto& k : restore_job_keys) {
6158
20
            txn->remove(k);
6159
20
        }
6160
1
        err = txn->commit();
6161
1
        if (err != TxnErrorCode::TXN_OK) {
6162
0
            LOG_WARNING("failed to recycle restore job")
6163
0
                    .tag("err", err)
6164
0
                    .tag("instance_id", instance_id_)
6165
0
                    .tag("reason", "failed to commit txn");
6166
0
            return -1;
6167
0
        }
6168
1
        return 0;
6169
1
    };
6170
6171
13
    if (config::enable_recycler_stats_metrics) {
6172
0
        scan_and_statistics_restore_jobs();
6173
0
    }
6174
6175
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
6176
13
                            std::move(loop_done));
6177
13
}
6178
6179
11
int InstanceRecycler::recycle_versioned_rowsets() {
6180
11
    const std::string task_name = "recycle_rowsets";
6181
11
    int64_t num_scanned = 0;
6182
11
    int64_t num_expired = 0;
6183
11
    int64_t num_prepare = 0;
6184
11
    int64_t num_compacted = 0;
6185
11
    int64_t num_empty_rowset = 0;
6186
11
    size_t total_rowset_key_size = 0;
6187
11
    size_t total_rowset_value_size = 0;
6188
11
    size_t expired_rowset_size = 0;
6189
11
    std::atomic_long num_recycled = 0;
6190
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6191
6192
11
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
6193
11
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
6194
11
    std::string recyc_rs_key0;
6195
11
    std::string recyc_rs_key1;
6196
11
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
6197
11
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
6198
6199
11
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
6200
6201
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6202
11
    register_recycle_task(task_name, start_time);
6203
6204
11
    DORIS_CLOUD_DEFER {
6205
11
        unregister_recycle_task(task_name);
6206
11
        int64_t cost =
6207
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6208
11
        metrics_context.finish_report();
6209
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6210
11
                .tag("instance_id", instance_id_)
6211
11
                .tag("num_scanned", num_scanned)
6212
11
                .tag("num_expired", num_expired)
6213
11
                .tag("num_recycled", num_recycled)
6214
11
                .tag("num_recycled.prepare", num_prepare)
6215
11
                .tag("num_recycled.compacted", num_compacted)
6216
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6217
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6218
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6219
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6220
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
6204
11
    DORIS_CLOUD_DEFER {
6205
11
        unregister_recycle_task(task_name);
6206
11
        int64_t cost =
6207
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6208
11
        metrics_context.finish_report();
6209
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6210
11
                .tag("instance_id", instance_id_)
6211
11
                .tag("num_scanned", num_scanned)
6212
11
                .tag("num_expired", num_expired)
6213
11
                .tag("num_recycled", num_recycled)
6214
11
                .tag("num_recycled.prepare", num_prepare)
6215
11
                .tag("num_recycled.compacted", num_compacted)
6216
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6217
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6218
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6219
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6220
11
    };
6221
6222
11
    std::vector<std::string> orphan_rowset_keys;
6223
6224
    // Store keys of rowset recycled by background workers
6225
11
    std::mutex async_recycled_rowset_keys_mutex;
6226
11
    std::vector<std::string> async_recycled_rowset_keys;
6227
11
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6228
11
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
6229
11
    worker_pool->start();
6230
11
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
6231
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6232
        // Try to delete rowset data in background thread
6233
400
        int ret = worker_pool->submit_with_timeout(
6234
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6235
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6236
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6237
400
                        return;
6238
400
                    }
6239
                    // The async recycled rowsets are staled format or has not been used,
6240
                    // so we don't need to check the rowset ref count key.
6241
0
                    std::vector<std::string> keys;
6242
0
                    {
6243
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6244
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6245
0
                        if (async_recycled_rowset_keys.size() > 100) {
6246
0
                            keys.swap(async_recycled_rowset_keys);
6247
0
                        }
6248
0
                    }
6249
0
                    if (keys.empty()) return;
6250
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6251
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6252
0
                                     << instance_id_;
6253
0
                    } else {
6254
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6255
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6256
0
                                           num_recycled, start_time);
6257
0
                    }
6258
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
6234
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6235
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6236
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6237
400
                        return;
6238
400
                    }
6239
                    // The async recycled rowsets are staled format or has not been used,
6240
                    // so we don't need to check the rowset ref count key.
6241
0
                    std::vector<std::string> keys;
6242
0
                    {
6243
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6244
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6245
0
                        if (async_recycled_rowset_keys.size() > 100) {
6246
0
                            keys.swap(async_recycled_rowset_keys);
6247
0
                        }
6248
0
                    }
6249
0
                    if (keys.empty()) return;
6250
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6251
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6252
0
                                     << instance_id_;
6253
0
                    } else {
6254
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6255
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6256
0
                                           num_recycled, start_time);
6257
0
                    }
6258
0
                },
6259
400
                0);
6260
400
        if (ret == 0) return 0;
6261
        // Submit task failed, delete rowset data in current thread
6262
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6263
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6264
0
            return -1;
6265
0
        }
6266
0
        orphan_rowset_keys.push_back(std::move(key));
6267
0
        return 0;
6268
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
6231
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6232
        // Try to delete rowset data in background thread
6233
400
        int ret = worker_pool->submit_with_timeout(
6234
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6235
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6236
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6237
400
                        return;
6238
400
                    }
6239
                    // The async recycled rowsets are staled format or has not been used,
6240
                    // so we don't need to check the rowset ref count key.
6241
400
                    std::vector<std::string> keys;
6242
400
                    {
6243
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6244
400
                        async_recycled_rowset_keys.push_back(std::move(key));
6245
400
                        if (async_recycled_rowset_keys.size() > 100) {
6246
400
                            keys.swap(async_recycled_rowset_keys);
6247
400
                        }
6248
400
                    }
6249
400
                    if (keys.empty()) return;
6250
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6251
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6252
400
                                     << instance_id_;
6253
400
                    } else {
6254
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6255
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6256
400
                                           num_recycled, start_time);
6257
400
                    }
6258
400
                },
6259
400
                0);
6260
400
        if (ret == 0) return 0;
6261
        // Submit task failed, delete rowset data in current thread
6262
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6263
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6264
0
            return -1;
6265
0
        }
6266
0
        orphan_rowset_keys.push_back(std::move(key));
6267
0
        return 0;
6268
0
    };
6269
6270
11
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6271
6272
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6273
2.01k
        ++num_scanned;
6274
2.01k
        total_rowset_key_size += k.size();
6275
2.01k
        total_rowset_value_size += v.size();
6276
2.01k
        RecycleRowsetPB rowset;
6277
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6278
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6279
0
            return -1;
6280
0
        }
6281
6282
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6283
6284
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6285
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6286
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6287
2.01k
        int64_t current_time = ::time(nullptr);
6288
2.01k
        if (current_time < final_expiration) { // not expired
6289
0
            return 0;
6290
0
        }
6291
2.01k
        ++num_expired;
6292
2.01k
        expired_rowset_size += v.size();
6293
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6294
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6295
                // in old version, keep this key-value pair and it needs to be checked manually
6296
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6297
0
                return -1;
6298
0
            }
6299
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6300
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6301
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6302
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6303
0
                orphan_rowset_keys.emplace_back(k);
6304
0
                return -1;
6305
0
            }
6306
            // decode rowset_id
6307
0
            auto k1 = k;
6308
0
            k1.remove_prefix(1);
6309
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6310
0
            decode_key(&k1, &out);
6311
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6312
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6313
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6314
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6315
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6316
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6317
0
                return -1;
6318
0
            }
6319
0
            return 0;
6320
0
        }
6321
        // TODO(plat1ko): check rowset not referenced
6322
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6323
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6324
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6325
0
                LOG_INFO("recycle rowset that has empty resource id");
6326
0
            } else {
6327
                // other situations, keep this key-value pair and it needs to be checked manually
6328
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6329
0
                return -1;
6330
0
            }
6331
0
        }
6332
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6333
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6334
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6335
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6336
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6337
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6338
2.01k
                  << " rowset_meta_size=" << v.size()
6339
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6340
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6341
            // unable to calculate file path, can only be deleted by rowset id prefix
6342
400
            num_prepare += 1;
6343
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6344
400
                                             rowset_meta->tablet_id(),
6345
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6346
0
                return -1;
6347
0
            }
6348
1.61k
        } else {
6349
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6350
1.61k
            worker_pool->submit(
6351
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6352
                        // The load & compact rowset keys are recycled during recycling operation logs.
6353
1.61k
                        RowsetDeleteTask task;
6354
1.61k
                        task.rowset_meta = rowset_meta;
6355
1.61k
                        task.recycle_rowset_key = k;
6356
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6357
1.59k
                            return;
6358
1.59k
                        }
6359
14
                        num_compacted += is_compacted;
6360
14
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6361
14
                        if (rowset_meta.num_segments() == 0) {
6362
0
                            ++num_empty_rowset;
6363
0
                        }
6364
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
6351
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6352
                        // The load & compact rowset keys are recycled during recycling operation logs.
6353
1.61k
                        RowsetDeleteTask task;
6354
1.61k
                        task.rowset_meta = rowset_meta;
6355
1.61k
                        task.recycle_rowset_key = k;
6356
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6357
1.59k
                            return;
6358
1.59k
                        }
6359
14
                        num_compacted += is_compacted;
6360
14
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6361
14
                        if (rowset_meta.num_segments() == 0) {
6362
0
                            ++num_empty_rowset;
6363
0
                        }
6364
14
                    });
6365
1.61k
        }
6366
2.01k
        return 0;
6367
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
6272
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6273
2.01k
        ++num_scanned;
6274
2.01k
        total_rowset_key_size += k.size();
6275
2.01k
        total_rowset_value_size += v.size();
6276
2.01k
        RecycleRowsetPB rowset;
6277
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6278
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6279
0
            return -1;
6280
0
        }
6281
6282
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6283
6284
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6285
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6286
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6287
2.01k
        int64_t current_time = ::time(nullptr);
6288
2.01k
        if (current_time < final_expiration) { // not expired
6289
0
            return 0;
6290
0
        }
6291
2.01k
        ++num_expired;
6292
2.01k
        expired_rowset_size += v.size();
6293
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6294
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6295
                // in old version, keep this key-value pair and it needs to be checked manually
6296
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6297
0
                return -1;
6298
0
            }
6299
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6300
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6301
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6302
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6303
0
                orphan_rowset_keys.emplace_back(k);
6304
0
                return -1;
6305
0
            }
6306
            // decode rowset_id
6307
0
            auto k1 = k;
6308
0
            k1.remove_prefix(1);
6309
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6310
0
            decode_key(&k1, &out);
6311
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6312
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6313
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6314
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6315
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6316
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6317
0
                return -1;
6318
0
            }
6319
0
            return 0;
6320
0
        }
6321
        // TODO(plat1ko): check rowset not referenced
6322
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6323
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6324
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6325
0
                LOG_INFO("recycle rowset that has empty resource id");
6326
0
            } else {
6327
                // other situations, keep this key-value pair and it needs to be checked manually
6328
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6329
0
                return -1;
6330
0
            }
6331
0
        }
6332
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6333
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6334
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6335
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6336
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6337
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6338
2.01k
                  << " rowset_meta_size=" << v.size()
6339
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6340
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6341
            // unable to calculate file path, can only be deleted by rowset id prefix
6342
400
            num_prepare += 1;
6343
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6344
400
                                             rowset_meta->tablet_id(),
6345
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6346
0
                return -1;
6347
0
            }
6348
1.61k
        } else {
6349
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6350
1.61k
            worker_pool->submit(
6351
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6352
                        // The load & compact rowset keys are recycled during recycling operation logs.
6353
1.61k
                        RowsetDeleteTask task;
6354
1.61k
                        task.rowset_meta = rowset_meta;
6355
1.61k
                        task.recycle_rowset_key = k;
6356
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6357
1.61k
                            return;
6358
1.61k
                        }
6359
1.61k
                        num_compacted += is_compacted;
6360
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6361
1.61k
                        if (rowset_meta.num_segments() == 0) {
6362
1.61k
                            ++num_empty_rowset;
6363
1.61k
                        }
6364
1.61k
                    });
6365
1.61k
        }
6366
2.01k
        return 0;
6367
2.01k
    };
6368
6369
11
    if (config::enable_recycler_stats_metrics) {
6370
0
        scan_and_statistics_rowsets();
6371
0
    }
6372
6373
11
    auto loop_done = [&]() -> int {
6374
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6375
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6376
0
        }
6377
6
        orphan_rowset_keys.clear();
6378
6
        return 0;
6379
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
Line
Count
Source
6373
6
    auto loop_done = [&]() -> int {
6374
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6375
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6376
0
        }
6377
6
        orphan_rowset_keys.clear();
6378
6
        return 0;
6379
6
    };
6380
6381
    // recycle_func and loop_done for scan and recycle
6382
11
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
6383
11
                               std::move(loop_done));
6384
6385
11
    worker_pool->stop();
6386
6387
11
    if (!async_recycled_rowset_keys.empty()) {
6388
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
6389
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6390
0
            return -1;
6391
0
        } else {
6392
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
6393
0
        }
6394
0
    }
6395
6396
    // Report final metrics after all concurrent tasks completed
6397
11
    segment_metrics_context_.report();
6398
11
    metrics_context.report();
6399
6400
11
    return ret;
6401
11
}
6402
6403
1.61k
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task) {
6404
1.61k
    constexpr int MAX_RETRY = 10;
6405
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
6406
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
6407
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
6408
1.61k
    std::string_view reference_instance_id = instance_id_;
6409
1.61k
    if (rowset_meta.has_reference_instance_id()) {
6410
8
        reference_instance_id = rowset_meta.reference_instance_id();
6411
8
    }
6412
6413
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
6414
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
6415
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
6416
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
6417
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
6418
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
6419
1.61k
        std::unique_ptr<Transaction> txn;
6420
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6421
1.61k
        if (err != TxnErrorCode::TXN_OK) {
6422
0
            LOG_WARNING("failed to create txn").tag("err", err);
6423
0
            return -1;
6424
0
        }
6425
6426
1.61k
        std::string rowset_ref_count_key =
6427
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
6428
1.61k
        int64_t ref_count = 0;
6429
1.61k
        {
6430
1.61k
            std::string value;
6431
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
6432
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6433
                // This is the old version rowset, we could recycle it directly.
6434
1.60k
                ref_count = 1;
6435
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
6436
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
6437
0
                return -1;
6438
9
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
6439
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
6440
0
                return -1;
6441
0
            }
6442
1.61k
        }
6443
6444
1.61k
        if (ref_count == 1) {
6445
            // It would not be added since it is recycling.
6446
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
6447
1.60k
                LOG_WARNING("failed to delete rowset data");
6448
1.60k
                return -1;
6449
1.60k
            }
6450
6451
            // Reset the transaction to avoid timeout.
6452
10
            err = txn_kv_->create_txn(&txn);
6453
10
            if (err != TxnErrorCode::TXN_OK) {
6454
0
                LOG_WARNING("failed to create txn").tag("err", err);
6455
0
                return -1;
6456
0
            }
6457
10
            txn->remove(rowset_ref_count_key);
6458
10
            LOG_INFO("delete rowset data ref count key")
6459
10
                    .tag("txn_id", rowset_meta.txn_id())
6460
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6461
6462
10
            std::string dbm_start_key =
6463
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
6464
10
            std::string dbm_end_key = meta_delete_bitmap_key(
6465
10
                    {reference_instance_id, tablet_id, rowset_id,
6466
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
6467
10
            txn->remove(dbm_start_key, dbm_end_key);
6468
10
            LOG_INFO("remove delete bitmap kv")
6469
10
                    .tag("begin", hex(dbm_start_key))
6470
10
                    .tag("end", hex(dbm_end_key));
6471
6472
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
6473
10
                    {reference_instance_id, tablet_id, rowset_id});
6474
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
6475
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
6476
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
6477
10
            LOG_INFO("remove versioned delete bitmap kv")
6478
10
                    .tag("begin", hex(versioned_dbm_start_key))
6479
10
                    .tag("end", hex(versioned_dbm_end_key));
6480
10
        } else {
6481
            // Decrease the rowset ref count.
6482
            //
6483
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
6484
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
6485
1
            txn->atomic_add(rowset_ref_count_key, -1);
6486
1
            LOG_INFO("decrease rowset data ref count")
6487
1
                    .tag("txn_id", rowset_meta.txn_id())
6488
1
                    .tag("ref_count", ref_count - 1)
6489
1
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6490
1
        }
6491
6492
11
        if (!task.versioned_rowset_key.empty()) {
6493
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
6494
0
                                                          task.versionstamp);
6495
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
6496
0
        }
6497
6498
11
        if (!task.non_versioned_rowset_key.empty()) {
6499
0
            txn->remove(task.non_versioned_rowset_key);
6500
0
            LOG_INFO("remove non versioned rowset key")
6501
0
                    .tag("key", hex(task.non_versioned_rowset_key));
6502
0
        }
6503
6504
        // empty when recycle ref rowsets for deleted instance
6505
13
        if (!task.recycle_rowset_key.empty()) {
6506
13
            txn->remove(task.recycle_rowset_key);
6507
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
6508
13
        }
6509
6510
11
        err = txn->commit();
6511
11
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
6512
            // The rowset ref count key has been changed, we need to retry.
6513
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
6514
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
6515
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
6516
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6517
0
            continue;
6518
11
        } else if (err != TxnErrorCode::TXN_OK) {
6519
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
6520
0
            return -1;
6521
0
        }
6522
11
        LOG_INFO("recycle rowset meta and data success");
6523
11
        return 0;
6524
11
    }
6525
2
    LOG_WARNING("failed to recycle rowset meta and data after retry")
6526
2
            .tag("tablet_id", tablet_id)
6527
2
            .tag("rowset_id", rowset_id)
6528
2
            .tag("retry", MAX_RETRY);
6529
2
    return -1;
6530
1.61k
}
6531
6532
37
int InstanceRecycler::recycle_tmp_rowsets() {
6533
37
    const std::string task_name = "recycle_tmp_rowsets";
6534
37
    int64_t num_scanned = 0;
6535
37
    int64_t num_expired = 0;
6536
37
    std::atomic_long num_recycled = 0;
6537
37
    size_t expired_rowset_size = 0;
6538
37
    size_t total_rowset_key_size = 0;
6539
37
    size_t total_rowset_value_size = 0;
6540
37
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6541
6542
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
6543
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
6544
37
    std::string tmp_rs_key0;
6545
37
    std::string tmp_rs_key1;
6546
37
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
6547
37
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
6548
6549
37
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
6550
6551
37
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6552
37
    register_recycle_task(task_name, start_time);
6553
6554
37
    DORIS_CLOUD_DEFER {
6555
37
        unregister_recycle_task(task_name);
6556
37
        int64_t cost =
6557
37
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6558
37
        metrics_context.finish_report();
6559
37
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6560
37
                .tag("instance_id", instance_id_)
6561
37
                .tag("num_scanned", num_scanned)
6562
37
                .tag("num_expired", num_expired)
6563
37
                .tag("num_recycled", num_recycled)
6564
37
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6565
37
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6566
37
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6567
37
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6554
12
    DORIS_CLOUD_DEFER {
6555
12
        unregister_recycle_task(task_name);
6556
12
        int64_t cost =
6557
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6558
12
        metrics_context.finish_report();
6559
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6560
12
                .tag("instance_id", instance_id_)
6561
12
                .tag("num_scanned", num_scanned)
6562
12
                .tag("num_expired", num_expired)
6563
12
                .tag("num_recycled", num_recycled)
6564
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6565
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6566
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6567
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6554
25
    DORIS_CLOUD_DEFER {
6555
25
        unregister_recycle_task(task_name);
6556
25
        int64_t cost =
6557
25
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6558
25
        metrics_context.finish_report();
6559
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6560
25
                .tag("instance_id", instance_id_)
6561
25
                .tag("num_scanned", num_scanned)
6562
25
                .tag("num_expired", num_expired)
6563
25
                .tag("num_recycled", num_recycled)
6564
25
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6565
25
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6566
25
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6567
25
    };
6568
6569
    // Store direct-delete keys separately from keys whose related txn or job must be aborted.
6570
37
    std::vector<std::string> tmp_rowset_keys;
6571
37
    std::vector<std::string> tmp_rowset_ref_count_keys;
6572
37
    std::vector<std::string> tmp_rowset_keys_to_mark_recycled;
6573
37
    std::vector<std::string> tmp_rowset_keys_to_abort;
6574
6575
    // rowset_id -> rowset_meta
6576
    // store tmp_rowset id and meta for statistics rs size when delete
6577
37
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
6578
37
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6579
37
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
6580
37
    worker_pool->start();
6581
6582
37
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6583
6584
37
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &expired_rowset_size,
6585
37
                             &total_rowset_key_size, &total_rowset_value_size, &earlest_ts,
6586
37
                             &tmp_rowset_keys_to_mark_recycled, &tmp_rowset_keys_to_abort, this,
6587
37
                             &metrics_context, &tmp_rowsets, &tmp_rowset_ref_count_keys](
6588
53.2k
                                    std::string_view k, std::string_view v) -> int {
6589
53.2k
        ++num_scanned;
6590
53.2k
        total_rowset_key_size += k.size();
6591
53.2k
        total_rowset_value_size += v.size();
6592
53.2k
        doris::RowsetMetaCloudPB rowset;
6593
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6594
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6595
0
            return -1;
6596
0
        }
6597
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6598
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6599
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6600
0
                   << " txn_expiration=" << rowset.txn_expiration()
6601
0
                   << " rowset_creation_time=" << rowset.creation_time();
6602
53.2k
        int64_t current_time = ::time(nullptr);
6603
53.2k
        if (current_time < expiration) { // not expired
6604
0
            return 0;
6605
0
        }
6606
53.2k
        ++num_expired;
6607
53.2k
        expired_rowset_size += v.size();
6608
53.2k
        if (!rowset.has_resource_id()) {
6609
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6610
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6611
0
                return -1;
6612
0
            }
6613
            // might be a delete pred rowset
6614
0
            tmp_rowset_keys.emplace_back(k);
6615
0
            return 0;
6616
0
        }
6617
6618
        // TODO(plat1ko): check rowset not referenced
6619
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6620
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6621
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6622
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6623
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6624
53.2k
                  << " num_expired=" << num_expired
6625
53.2k
                  << " task_type=" << metrics_context.operation_type;
6626
6627
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6628
16
            if (need_mark_rowset_as_recycled(rowset)) {
6629
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6630
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6631
9
                             "at next turn, instance_id="
6632
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6633
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6634
9
                return 0;
6635
9
            }
6636
16
        }
6637
6638
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6639
265
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6640
261
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6641
261
                             "instance_id="
6642
261
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6643
261
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6644
261
                tmp_rowset_keys_to_abort.emplace_back(k);
6645
261
                return 0;
6646
261
            }
6647
265
        }
6648
6649
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6650
        // Remove the rowset ref count key directly since it has not been used.
6651
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6652
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6653
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6654
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6655
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6656
6657
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6658
53.0k
        return 0;
6659
53.2k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6588
16
                                    std::string_view k, std::string_view v) -> int {
6589
16
        ++num_scanned;
6590
16
        total_rowset_key_size += k.size();
6591
16
        total_rowset_value_size += v.size();
6592
16
        doris::RowsetMetaCloudPB rowset;
6593
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6594
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6595
0
            return -1;
6596
0
        }
6597
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6598
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6599
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6600
0
                   << " txn_expiration=" << rowset.txn_expiration()
6601
0
                   << " rowset_creation_time=" << rowset.creation_time();
6602
16
        int64_t current_time = ::time(nullptr);
6603
16
        if (current_time < expiration) { // not expired
6604
0
            return 0;
6605
0
        }
6606
16
        ++num_expired;
6607
16
        expired_rowset_size += v.size();
6608
16
        if (!rowset.has_resource_id()) {
6609
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6610
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6611
0
                return -1;
6612
0
            }
6613
            // might be a delete pred rowset
6614
0
            tmp_rowset_keys.emplace_back(k);
6615
0
            return 0;
6616
0
        }
6617
6618
        // TODO(plat1ko): check rowset not referenced
6619
16
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6620
16
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6621
16
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6622
16
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6623
16
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6624
16
                  << " num_expired=" << num_expired
6625
16
                  << " task_type=" << metrics_context.operation_type;
6626
6627
16
        if (config::enable_mark_delete_rowset_before_recycle) {
6628
16
            if (need_mark_rowset_as_recycled(rowset)) {
6629
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6630
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6631
9
                             "at next turn, instance_id="
6632
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6633
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6634
9
                return 0;
6635
9
            }
6636
16
        }
6637
6638
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6639
7
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6640
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6641
3
                             "instance_id="
6642
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6643
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6644
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6645
3
                return 0;
6646
3
            }
6647
7
        }
6648
6649
4
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6650
        // Remove the rowset ref count key directly since it has not been used.
6651
4
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6652
4
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6653
4
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6654
4
                  << "key=" << hex(rowset_ref_count_key);
6655
4
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6656
6657
4
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6658
4
        return 0;
6659
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6588
53.2k
                                    std::string_view k, std::string_view v) -> int {
6589
53.2k
        ++num_scanned;
6590
53.2k
        total_rowset_key_size += k.size();
6591
53.2k
        total_rowset_value_size += v.size();
6592
53.2k
        doris::RowsetMetaCloudPB rowset;
6593
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6594
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6595
0
            return -1;
6596
0
        }
6597
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6598
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6599
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6600
0
                   << " txn_expiration=" << rowset.txn_expiration()
6601
0
                   << " rowset_creation_time=" << rowset.creation_time();
6602
53.2k
        int64_t current_time = ::time(nullptr);
6603
53.2k
        if (current_time < expiration) { // not expired
6604
0
            return 0;
6605
0
        }
6606
53.2k
        ++num_expired;
6607
53.2k
        expired_rowset_size += v.size();
6608
53.2k
        if (!rowset.has_resource_id()) {
6609
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6610
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6611
0
                return -1;
6612
0
            }
6613
            // might be a delete pred rowset
6614
0
            tmp_rowset_keys.emplace_back(k);
6615
0
            return 0;
6616
0
        }
6617
6618
        // TODO(plat1ko): check rowset not referenced
6619
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6620
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6621
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6622
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6623
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6624
53.2k
                  << " num_expired=" << num_expired
6625
53.2k
                  << " task_type=" << metrics_context.operation_type;
6626
6627
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6628
0
            if (need_mark_rowset_as_recycled(rowset)) {
6629
0
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6630
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6631
0
                             "at next turn, instance_id="
6632
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6633
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6634
0
                return 0;
6635
0
            }
6636
0
        }
6637
6638
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6639
258
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6640
258
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6641
258
                             "instance_id="
6642
258
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6643
258
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6644
258
                tmp_rowset_keys_to_abort.emplace_back(k);
6645
258
                return 0;
6646
258
            }
6647
258
        }
6648
6649
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6650
        // Remove the rowset ref count key directly since it has not been used.
6651
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6652
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6653
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6654
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6655
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6656
6657
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6658
53.0k
        return 0;
6659
53.2k
    };
6660
6661
37
    auto loop_done = [&]() -> int {
6662
24
        std::vector<std::string> tmp_rowset_keys_to_delete;
6663
24
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6664
24
        std::vector<std::string> mark_keys_to_process;
6665
24
        std::vector<std::string> abort_keys_to_process;
6666
24
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6667
24
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6668
24
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6669
24
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6670
24
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6671
24
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6672
24
        if (!mark_keys_to_process.empty()) {
6673
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6674
7
                    *worker_pool, std::move(mark_keys_to_process));
6675
7
        }
6676
24
        if (!abort_keys_to_process.empty()) {
6677
5
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6678
5
                                           &num_recycled, &metrics_context);
6679
5
        }
6680
24
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6681
24
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6682
24
                             tmp_rowset_ref_count_keys_to_delete =
6683
24
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6684
24
                             mark_keys_to_process = std::move(mark_keys_to_process),
6685
24
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6686
24
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6687
24
                                   metrics_context) != 0) {
6688
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6689
2
                return;
6690
2
            }
6691
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6692
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6693
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6694
0
                                 << rs.ShortDebugString();
6695
0
                    return;
6696
0
                }
6697
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6698
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6699
0
                                 << rs.ShortDebugString();
6700
0
                    return;
6701
0
                }
6702
51.0k
            }
6703
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6704
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6705
0
                return;
6706
0
            }
6707
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6708
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6709
0
                return;
6710
0
            }
6711
22
            num_recycled += tmp_rowset_keys_to_delete.size();
6712
22
            return;
6713
22
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6685
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6686
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6687
12
                                   metrics_context) != 0) {
6688
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6689
0
                return;
6690
0
            }
6691
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6692
4
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6693
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6694
0
                                 << rs.ShortDebugString();
6695
0
                    return;
6696
0
                }
6697
4
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6698
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6699
0
                                 << rs.ShortDebugString();
6700
0
                    return;
6701
0
                }
6702
4
            }
6703
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6704
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6705
0
                return;
6706
0
            }
6707
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6708
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6709
0
                return;
6710
0
            }
6711
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6712
12
            return;
6713
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6685
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6686
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6687
12
                                   metrics_context) != 0) {
6688
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6689
2
                return;
6690
2
            }
6691
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6692
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6693
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6694
0
                                 << rs.ShortDebugString();
6695
0
                    return;
6696
0
                }
6697
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6698
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6699
0
                                 << rs.ShortDebugString();
6700
0
                    return;
6701
0
                }
6702
51.0k
            }
6703
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6704
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6705
0
                return;
6706
0
            }
6707
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6708
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6709
0
                return;
6710
0
            }
6711
10
            num_recycled += tmp_rowset_keys_to_delete.size();
6712
10
            return;
6713
10
        });
6714
24
        return 0;
6715
24
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6661
12
    auto loop_done = [&]() -> int {
6662
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6663
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6664
12
        std::vector<std::string> mark_keys_to_process;
6665
12
        std::vector<std::string> abort_keys_to_process;
6666
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6667
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6668
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6669
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6670
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6671
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6672
12
        if (!mark_keys_to_process.empty()) {
6673
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6674
7
                    *worker_pool, std::move(mark_keys_to_process));
6675
7
        }
6676
12
        if (!abort_keys_to_process.empty()) {
6677
3
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6678
3
                                           &num_recycled, &metrics_context);
6679
3
        }
6680
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6681
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6682
12
                             tmp_rowset_ref_count_keys_to_delete =
6683
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6684
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6685
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6686
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6687
12
                                   metrics_context) != 0) {
6688
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6689
12
                return;
6690
12
            }
6691
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6692
12
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6693
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6694
12
                                 << rs.ShortDebugString();
6695
12
                    return;
6696
12
                }
6697
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6698
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6699
12
                                 << rs.ShortDebugString();
6700
12
                    return;
6701
12
                }
6702
12
            }
6703
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6704
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6705
12
                return;
6706
12
            }
6707
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6708
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6709
12
                return;
6710
12
            }
6711
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6712
12
            return;
6713
12
        });
6714
12
        return 0;
6715
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6661
12
    auto loop_done = [&]() -> int {
6662
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6663
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6664
12
        std::vector<std::string> mark_keys_to_process;
6665
12
        std::vector<std::string> abort_keys_to_process;
6666
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6667
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6668
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6669
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6670
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6671
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6672
12
        if (!mark_keys_to_process.empty()) {
6673
0
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6674
0
                    *worker_pool, std::move(mark_keys_to_process));
6675
0
        }
6676
12
        if (!abort_keys_to_process.empty()) {
6677
2
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6678
2
                                           &num_recycled, &metrics_context);
6679
2
        }
6680
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6681
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6682
12
                             tmp_rowset_ref_count_keys_to_delete =
6683
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6684
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6685
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6686
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6687
12
                                   metrics_context) != 0) {
6688
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6689
12
                return;
6690
12
            }
6691
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6692
12
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6693
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6694
12
                                 << rs.ShortDebugString();
6695
12
                    return;
6696
12
                }
6697
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6698
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6699
12
                                 << rs.ShortDebugString();
6700
12
                    return;
6701
12
                }
6702
12
            }
6703
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6704
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6705
12
                return;
6706
12
            }
6707
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6708
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6709
12
                return;
6710
12
            }
6711
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6712
12
            return;
6713
12
        });
6714
12
        return 0;
6715
12
    };
6716
6717
37
    if (config::enable_recycler_stats_metrics) {
6718
0
        scan_and_statistics_tmp_rowsets();
6719
0
    }
6720
    // recycle_func and loop_done for scan and recycle
6721
37
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
6722
37
                               std::move(loop_done));
6723
6724
37
    worker_pool->stop();
6725
6726
    // Report final metrics after all concurrent tasks completed
6727
37
    segment_metrics_context_.report();
6728
37
    metrics_context.report();
6729
6730
37
    return ret;
6731
37
}
6732
6733
int InstanceRecycler::scan_and_recycle(
6734
        std::string begin, std::string_view end,
6735
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
6736
345
        std::function<int()> loop_done, std::function<bool(std::string*)> next_begin_getter) {
6737
345
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
6738
345
    int ret = 0;
6739
345
    int64_t cnt = 0;
6740
345
    int get_range_retried = 0;
6741
345
    std::string err;
6742
345
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6743
345
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6744
345
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6745
345
                  << " ret=" << ret << " err=" << err;
6746
345
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6742
36
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6743
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6744
36
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6745
36
                  << " ret=" << ret << " err=" << err;
6746
36
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6742
309
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6743
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6744
309
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6745
309
                  << " ret=" << ret << " err=" << err;
6746
309
    };
6747
6748
345
    std::unique_ptr<RangeGetIterator> it;
6749
545
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
6750
380
        if (get_range_retried > 1000) {
6751
0
            err = "txn_get exceeds max retry(1000), may not scan all keys";
6752
0
            ret = -3;
6753
0
            return ret;
6754
0
        }
6755
380
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
6756
380
        if (get_ret != 0) { // txn kv may complain "Request for future version"
6757
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
6758
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
6759
0
                         << " get_range_retried=" << get_range_retried;
6760
0
            ++get_range_retried;
6761
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6762
0
            continue; // try again
6763
0
        }
6764
380
        if (!it->has_next()) {
6765
180
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
6766
180
            break; // scan finished
6767
180
        }
6768
200
        bool begin_updated = false;
6769
200
        LOG(INFO) << "scan_and_recycle iterator key_range=[" << hex(begin) << "," << hex(end)
6770
200
                  << ") iterator->size()=" << it->size();
6771
98.2k
        while (it->has_next()) {
6772
98.0k
            ++cnt;
6773
            // recycle corresponding resources
6774
98.0k
            auto [k, v] = it->next();
6775
98.0k
            if (!it->has_next()) {
6776
194
                begin = k;
6777
194
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
6778
194
            }
6779
            // FIXME(gavin): if we want to continue scanning, the recycle_func should not return non-zero
6780
98.0k
            if (recycle_func(k, v) != 0) {
6781
4.00k
                err = "recycle_func error";
6782
4.00k
                ret = -1;
6783
4.00k
            }
6784
98.0k
            if (next_begin_getter) {
6785
4.33k
                std::string next_begin;
6786
4.33k
                if (next_begin_getter(&next_begin)) {
6787
7
                    if (next_begin > k) {
6788
7
                        begin = std::move(next_begin);
6789
7
                        begin_updated = true;
6790
7
                        VLOG_DEBUG << "scan_and_recycle updates begin to " << hex(begin)
6791
0
                                   << " after key=" << hex(k);
6792
7
                        break;
6793
7
                    }
6794
0
                    LOG_WARNING("ignore invalid next begin in scan_and_recycle")
6795
0
                            .tag("next_begin", hex(next_begin))
6796
0
                            .tag("current_key", hex(k));
6797
0
                }
6798
4.33k
            }
6799
98.0k
        }
6800
200
        if (!begin_updated) {
6801
193
            begin.push_back('\x00'); // Update to next smallest key for iteration
6802
193
        } else {
6803
7
            it.reset();
6804
7
        }
6805
6806
        // FIXME(gavin): if we want to continue scanning, the loop_done should not return non-zero
6807
        // if we want to continue scanning, the recycle_func should not return non-zero
6808
200
        if (loop_done && loop_done() != 0) {
6809
5
            err = "loop_done error";
6810
5
            ret = -1;
6811
5
        }
6812
200
    }
6813
345
    return ret;
6814
345
}
6815
6816
19
int InstanceRecycler::abort_timeout_txn() {
6817
19
    const std::string task_name = "abort_timeout_txn";
6818
19
    int64_t num_scanned = 0;
6819
19
    int64_t num_timeout = 0;
6820
19
    int64_t num_abort = 0;
6821
19
    int64_t num_advance = 0;
6822
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6823
6824
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6825
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6826
19
    std::string begin_txn_running_key;
6827
19
    std::string end_txn_running_key;
6828
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6829
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6830
6831
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
6832
6833
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6834
19
    register_recycle_task(task_name, start_time);
6835
6836
19
    DORIS_CLOUD_DEFER {
6837
19
        unregister_recycle_task(task_name);
6838
19
        int64_t cost =
6839
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6840
19
        metrics_context.finish_report();
6841
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6842
19
                .tag("instance_id", instance_id_)
6843
19
                .tag("num_scanned", num_scanned)
6844
19
                .tag("num_timeout", num_timeout)
6845
19
                .tag("num_abort", num_abort)
6846
19
                .tag("num_advance", num_advance);
6847
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6836
3
    DORIS_CLOUD_DEFER {
6837
3
        unregister_recycle_task(task_name);
6838
3
        int64_t cost =
6839
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6840
3
        metrics_context.finish_report();
6841
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6842
3
                .tag("instance_id", instance_id_)
6843
3
                .tag("num_scanned", num_scanned)
6844
3
                .tag("num_timeout", num_timeout)
6845
3
                .tag("num_abort", num_abort)
6846
3
                .tag("num_advance", num_advance);
6847
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6836
16
    DORIS_CLOUD_DEFER {
6837
16
        unregister_recycle_task(task_name);
6838
16
        int64_t cost =
6839
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6840
16
        metrics_context.finish_report();
6841
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6842
16
                .tag("instance_id", instance_id_)
6843
16
                .tag("num_scanned", num_scanned)
6844
16
                .tag("num_timeout", num_timeout)
6845
16
                .tag("num_abort", num_abort)
6846
16
                .tag("num_advance", num_advance);
6847
16
    };
6848
6849
19
    int64_t current_time =
6850
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6851
6852
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
6853
19
                                  &current_time, &metrics_context,
6854
19
                                  this](std::string_view k, std::string_view v) -> int {
6855
9
        ++num_scanned;
6856
6857
9
        std::unique_ptr<Transaction> txn;
6858
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6859
9
        if (err != TxnErrorCode::TXN_OK) {
6860
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6861
0
            return -1;
6862
0
        }
6863
9
        std::string_view k1 = k;
6864
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6865
9
        k1.remove_prefix(1); // Remove key space
6866
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6867
9
        if (decode_key(&k1, &out) != 0) {
6868
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6869
0
            return -1;
6870
0
        }
6871
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6872
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6873
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6874
        // Update txn_info
6875
9
        std::string txn_inf_key, txn_inf_val;
6876
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6877
9
        err = txn->get(txn_inf_key, &txn_inf_val);
6878
9
        if (err != TxnErrorCode::TXN_OK) {
6879
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6880
0
            return -1;
6881
0
        }
6882
9
        TxnInfoPB txn_info;
6883
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
6884
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6885
0
            return -1;
6886
0
        }
6887
6888
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6889
3
            txn.reset();
6890
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6891
3
            std::shared_ptr<TxnLazyCommitTask> task =
6892
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6893
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6894
3
            if (ret.first != MetaServiceCode::OK) {
6895
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6896
0
                             << "msg=" << ret.second;
6897
0
                return -1;
6898
0
            }
6899
3
            ++num_advance;
6900
3
            return 0;
6901
6
        } else {
6902
6
            TxnRunningPB txn_running_pb;
6903
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6904
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6905
0
                return -1;
6906
0
            }
6907
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6908
4
                return 0;
6909
4
            }
6910
2
            ++num_timeout;
6911
6912
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6913
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6914
2
            txn_info.set_finish_time(current_time);
6915
2
            txn_info.set_reason("timeout");
6916
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6917
2
            txn_inf_val.clear();
6918
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6919
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6920
0
                return -1;
6921
0
            }
6922
2
            txn->put(txn_inf_key, txn_inf_val);
6923
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6924
            // Put recycle txn key
6925
2
            std::string recyc_txn_key, recyc_txn_val;
6926
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6927
2
            RecycleTxnPB recycle_txn_pb;
6928
2
            recycle_txn_pb.set_creation_time(current_time);
6929
2
            recycle_txn_pb.set_label(txn_info.label());
6930
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6931
0
                LOG_WARNING("failed to serialize txn recycle info")
6932
0
                        .tag("key", hex(k))
6933
0
                        .tag("db_id", db_id)
6934
0
                        .tag("txn_id", txn_id);
6935
0
                return -1;
6936
0
            }
6937
2
            txn->put(recyc_txn_key, recyc_txn_val);
6938
            // Remove txn running key
6939
2
            txn->remove(k);
6940
2
            err = txn->commit();
6941
2
            if (err != TxnErrorCode::TXN_OK) {
6942
0
                LOG_WARNING("failed to commit txn err={}", err)
6943
0
                        .tag("key", hex(k))
6944
0
                        .tag("db_id", db_id)
6945
0
                        .tag("txn_id", txn_id);
6946
0
                return -1;
6947
0
            }
6948
2
            metrics_context.total_recycled_num = ++num_abort;
6949
2
            metrics_context.report();
6950
2
        }
6951
6952
2
        return 0;
6953
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6854
3
                                  this](std::string_view k, std::string_view v) -> int {
6855
3
        ++num_scanned;
6856
6857
3
        std::unique_ptr<Transaction> txn;
6858
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6859
3
        if (err != TxnErrorCode::TXN_OK) {
6860
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6861
0
            return -1;
6862
0
        }
6863
3
        std::string_view k1 = k;
6864
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6865
3
        k1.remove_prefix(1); // Remove key space
6866
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6867
3
        if (decode_key(&k1, &out) != 0) {
6868
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6869
0
            return -1;
6870
0
        }
6871
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6872
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6873
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6874
        // Update txn_info
6875
3
        std::string txn_inf_key, txn_inf_val;
6876
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6877
3
        err = txn->get(txn_inf_key, &txn_inf_val);
6878
3
        if (err != TxnErrorCode::TXN_OK) {
6879
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6880
0
            return -1;
6881
0
        }
6882
3
        TxnInfoPB txn_info;
6883
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
6884
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6885
0
            return -1;
6886
0
        }
6887
6888
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6889
3
            txn.reset();
6890
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6891
3
            std::shared_ptr<TxnLazyCommitTask> task =
6892
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6893
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6894
3
            if (ret.first != MetaServiceCode::OK) {
6895
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6896
0
                             << "msg=" << ret.second;
6897
0
                return -1;
6898
0
            }
6899
3
            ++num_advance;
6900
3
            return 0;
6901
3
        } else {
6902
0
            TxnRunningPB txn_running_pb;
6903
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6904
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6905
0
                return -1;
6906
0
            }
6907
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6908
0
                return 0;
6909
0
            }
6910
0
            ++num_timeout;
6911
6912
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6913
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6914
0
            txn_info.set_finish_time(current_time);
6915
0
            txn_info.set_reason("timeout");
6916
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6917
0
            txn_inf_val.clear();
6918
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6919
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6920
0
                return -1;
6921
0
            }
6922
0
            txn->put(txn_inf_key, txn_inf_val);
6923
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6924
            // Put recycle txn key
6925
0
            std::string recyc_txn_key, recyc_txn_val;
6926
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6927
0
            RecycleTxnPB recycle_txn_pb;
6928
0
            recycle_txn_pb.set_creation_time(current_time);
6929
0
            recycle_txn_pb.set_label(txn_info.label());
6930
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6931
0
                LOG_WARNING("failed to serialize txn recycle info")
6932
0
                        .tag("key", hex(k))
6933
0
                        .tag("db_id", db_id)
6934
0
                        .tag("txn_id", txn_id);
6935
0
                return -1;
6936
0
            }
6937
0
            txn->put(recyc_txn_key, recyc_txn_val);
6938
            // Remove txn running key
6939
0
            txn->remove(k);
6940
0
            err = txn->commit();
6941
0
            if (err != TxnErrorCode::TXN_OK) {
6942
0
                LOG_WARNING("failed to commit txn err={}", err)
6943
0
                        .tag("key", hex(k))
6944
0
                        .tag("db_id", db_id)
6945
0
                        .tag("txn_id", txn_id);
6946
0
                return -1;
6947
0
            }
6948
0
            metrics_context.total_recycled_num = ++num_abort;
6949
0
            metrics_context.report();
6950
0
        }
6951
6952
0
        return 0;
6953
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6854
6
                                  this](std::string_view k, std::string_view v) -> int {
6855
6
        ++num_scanned;
6856
6857
6
        std::unique_ptr<Transaction> txn;
6858
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6859
6
        if (err != TxnErrorCode::TXN_OK) {
6860
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6861
0
            return -1;
6862
0
        }
6863
6
        std::string_view k1 = k;
6864
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6865
6
        k1.remove_prefix(1); // Remove key space
6866
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6867
6
        if (decode_key(&k1, &out) != 0) {
6868
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6869
0
            return -1;
6870
0
        }
6871
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6872
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6873
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6874
        // Update txn_info
6875
6
        std::string txn_inf_key, txn_inf_val;
6876
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6877
6
        err = txn->get(txn_inf_key, &txn_inf_val);
6878
6
        if (err != TxnErrorCode::TXN_OK) {
6879
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6880
0
            return -1;
6881
0
        }
6882
6
        TxnInfoPB txn_info;
6883
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
6884
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6885
0
            return -1;
6886
0
        }
6887
6888
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6889
0
            txn.reset();
6890
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6891
0
            std::shared_ptr<TxnLazyCommitTask> task =
6892
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6893
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6894
0
            if (ret.first != MetaServiceCode::OK) {
6895
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6896
0
                             << "msg=" << ret.second;
6897
0
                return -1;
6898
0
            }
6899
0
            ++num_advance;
6900
0
            return 0;
6901
6
        } else {
6902
6
            TxnRunningPB txn_running_pb;
6903
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6904
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6905
0
                return -1;
6906
0
            }
6907
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6908
4
                return 0;
6909
4
            }
6910
2
            ++num_timeout;
6911
6912
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6913
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6914
2
            txn_info.set_finish_time(current_time);
6915
2
            txn_info.set_reason("timeout");
6916
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6917
2
            txn_inf_val.clear();
6918
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6919
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6920
0
                return -1;
6921
0
            }
6922
2
            txn->put(txn_inf_key, txn_inf_val);
6923
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6924
            // Put recycle txn key
6925
2
            std::string recyc_txn_key, recyc_txn_val;
6926
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6927
2
            RecycleTxnPB recycle_txn_pb;
6928
2
            recycle_txn_pb.set_creation_time(current_time);
6929
2
            recycle_txn_pb.set_label(txn_info.label());
6930
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6931
0
                LOG_WARNING("failed to serialize txn recycle info")
6932
0
                        .tag("key", hex(k))
6933
0
                        .tag("db_id", db_id)
6934
0
                        .tag("txn_id", txn_id);
6935
0
                return -1;
6936
0
            }
6937
2
            txn->put(recyc_txn_key, recyc_txn_val);
6938
            // Remove txn running key
6939
2
            txn->remove(k);
6940
2
            err = txn->commit();
6941
2
            if (err != TxnErrorCode::TXN_OK) {
6942
0
                LOG_WARNING("failed to commit txn err={}", err)
6943
0
                        .tag("key", hex(k))
6944
0
                        .tag("db_id", db_id)
6945
0
                        .tag("txn_id", txn_id);
6946
0
                return -1;
6947
0
            }
6948
2
            metrics_context.total_recycled_num = ++num_abort;
6949
2
            metrics_context.report();
6950
2
        }
6951
6952
2
        return 0;
6953
6
    };
6954
6955
19
    if (config::enable_recycler_stats_metrics) {
6956
0
        scan_and_statistics_abort_timeout_txn();
6957
0
    }
6958
    // recycle_func and loop_done for scan and recycle
6959
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
6960
19
                            std::move(handle_txn_running_kv));
6961
19
}
6962
6963
19
int InstanceRecycler::recycle_expired_txn_label() {
6964
19
    const std::string task_name = "recycle_expired_txn_label";
6965
19
    int64_t num_scanned = 0;
6966
19
    int64_t num_expired = 0;
6967
19
    std::atomic_long num_recycled = 0;
6968
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6969
19
    int ret = 0;
6970
6971
19
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
6972
19
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6973
19
    std::string begin_recycle_txn_key;
6974
19
    std::string end_recycle_txn_key;
6975
19
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
6976
19
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
6977
19
    std::vector<std::string> recycle_txn_info_keys;
6978
6979
19
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
6980
6981
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6982
19
    register_recycle_task(task_name, start_time);
6983
19
    DORIS_CLOUD_DEFER {
6984
19
        unregister_recycle_task(task_name);
6985
19
        int64_t cost =
6986
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6987
19
        metrics_context.finish_report();
6988
19
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6989
19
                .tag("instance_id", instance_id_)
6990
19
                .tag("num_scanned", num_scanned)
6991
19
                .tag("num_expired", num_expired)
6992
19
                .tag("num_recycled", num_recycled);
6993
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6983
1
    DORIS_CLOUD_DEFER {
6984
1
        unregister_recycle_task(task_name);
6985
1
        int64_t cost =
6986
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6987
1
        metrics_context.finish_report();
6988
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6989
1
                .tag("instance_id", instance_id_)
6990
1
                .tag("num_scanned", num_scanned)
6991
1
                .tag("num_expired", num_expired)
6992
1
                .tag("num_recycled", num_recycled);
6993
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6983
18
    DORIS_CLOUD_DEFER {
6984
18
        unregister_recycle_task(task_name);
6985
18
        int64_t cost =
6986
18
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6987
18
        metrics_context.finish_report();
6988
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6989
18
                .tag("instance_id", instance_id_)
6990
18
                .tag("num_scanned", num_scanned)
6991
18
                .tag("num_expired", num_expired)
6992
18
                .tag("num_recycled", num_recycled);
6993
18
    };
6994
6995
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6996
6997
19
    SyncExecutor<int> concurrent_delete_executor(
6998
19
            _thread_pool_group.s3_producer_pool,
6999
19
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
7000
23.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
7000
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
7000
23.0k
            [](const int& ret) { return ret != 0; });
7001
7002
19
    int64_t current_time_ms =
7003
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7004
7005
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
7006
30.0k
        ++num_scanned;
7007
30.0k
        RecycleTxnPB recycle_txn_pb;
7008
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7009
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7010
0
            return -1;
7011
0
        }
7012
30.0k
        if ((config::force_immediate_recycle) ||
7013
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7014
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7015
30.0k
             current_time_ms)) {
7016
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
7017
23.0k
            num_expired++;
7018
23.0k
            recycle_txn_info_keys.emplace_back(k);
7019
23.0k
        }
7020
30.0k
        return 0;
7021
30.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7005
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
7006
1
        ++num_scanned;
7007
1
        RecycleTxnPB recycle_txn_pb;
7008
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7009
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7010
0
            return -1;
7011
0
        }
7012
1
        if ((config::force_immediate_recycle) ||
7013
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7014
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7015
1
             current_time_ms)) {
7016
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
7017
1
            num_expired++;
7018
1
            recycle_txn_info_keys.emplace_back(k);
7019
1
        }
7020
1
        return 0;
7021
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7005
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
7006
30.0k
        ++num_scanned;
7007
30.0k
        RecycleTxnPB recycle_txn_pb;
7008
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7009
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7010
0
            return -1;
7011
0
        }
7012
30.0k
        if ((config::force_immediate_recycle) ||
7013
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7014
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7015
30.0k
             current_time_ms)) {
7016
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
7017
23.0k
            num_expired++;
7018
23.0k
            recycle_txn_info_keys.emplace_back(k);
7019
23.0k
        }
7020
30.0k
        return 0;
7021
30.0k
    };
7022
7023
    // int 0 for success, 1 for conflict, -1 for error
7024
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7025
23.0k
        std::string_view k1 = k;
7026
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7027
23.0k
        k1.remove_prefix(1); // Remove key space
7028
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7029
23.0k
        int ret = decode_key(&k1, &out);
7030
23.0k
        if (ret != 0) {
7031
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7032
0
            return -1;
7033
0
        }
7034
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7035
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7036
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7037
23.0k
        std::unique_ptr<Transaction> txn;
7038
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7039
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7040
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7041
0
            return -1;
7042
0
        }
7043
        // Remove txn index kv
7044
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
7045
23.0k
        txn->remove(index_key);
7046
        // Remove txn info kv
7047
23.0k
        std::string info_key, info_val;
7048
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7049
23.0k
        err = txn->get(info_key, &info_val);
7050
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7051
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7052
0
            return -1;
7053
0
        }
7054
23.0k
        TxnInfoPB txn_info;
7055
23.0k
        if (!txn_info.ParseFromString(info_val)) {
7056
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7057
0
            return -1;
7058
0
        }
7059
23.0k
        txn->remove(info_key);
7060
        // Remove sub txn index kvs
7061
23.0k
        std::vector<std::string> sub_txn_index_keys;
7062
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7063
23.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7064
23.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
7065
23.0k
        }
7066
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7067
22.9k
            txn->remove(sub_txn_index_key);
7068
22.9k
        }
7069
        // Update txn label
7070
23.0k
        std::string label_key, label_val;
7071
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7072
23.0k
        err = txn->get(label_key, &label_val);
7073
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7074
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7075
0
                         << " err=" << err;
7076
0
            return -1;
7077
0
        }
7078
23.0k
        TxnLabelPB txn_label;
7079
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7080
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7081
0
            return -1;
7082
0
        }
7083
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7084
23.0k
        if (it != txn_label.txn_ids().end()) {
7085
23.0k
            txn_label.mutable_txn_ids()->erase(it);
7086
23.0k
        }
7087
23.0k
        if (txn_label.txn_ids().empty()) {
7088
23.0k
            txn->remove(label_key);
7089
23.0k
            TEST_SYNC_POINT_CALLBACK(
7090
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7091
23.0k
        } else {
7092
73
            if (!txn_label.SerializeToString(&label_val)) {
7093
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7094
0
                return -1;
7095
0
            }
7096
73
            TEST_SYNC_POINT_CALLBACK(
7097
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7098
73
            txn->atomic_set_ver_value(label_key, label_val);
7099
73
            TEST_SYNC_POINT_CALLBACK(
7100
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7101
73
        }
7102
        // Remove recycle txn kv
7103
23.0k
        txn->remove(k);
7104
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7105
23.0k
        err = txn->commit();
7106
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7107
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
7108
62
                TEST_SYNC_POINT_CALLBACK(
7109
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7110
                // log the txn_id and label
7111
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7112
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7113
62
                             << " txn_label=" << txn_info.label();
7114
62
                return 1;
7115
62
            }
7116
62
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7117
0
            return -1;
7118
62
        }
7119
23.0k
        ++num_recycled;
7120
7121
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7122
23.0k
        return 0;
7123
23.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
7024
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7025
1
        std::string_view k1 = k;
7026
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7027
1
        k1.remove_prefix(1); // Remove key space
7028
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7029
1
        int ret = decode_key(&k1, &out);
7030
1
        if (ret != 0) {
7031
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7032
0
            return -1;
7033
0
        }
7034
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7035
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7036
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7037
1
        std::unique_ptr<Transaction> txn;
7038
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7039
1
        if (err != TxnErrorCode::TXN_OK) {
7040
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7041
0
            return -1;
7042
0
        }
7043
        // Remove txn index kv
7044
1
        auto index_key = txn_index_key({instance_id_, txn_id});
7045
1
        txn->remove(index_key);
7046
        // Remove txn info kv
7047
1
        std::string info_key, info_val;
7048
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7049
1
        err = txn->get(info_key, &info_val);
7050
1
        if (err != TxnErrorCode::TXN_OK) {
7051
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7052
0
            return -1;
7053
0
        }
7054
1
        TxnInfoPB txn_info;
7055
1
        if (!txn_info.ParseFromString(info_val)) {
7056
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7057
0
            return -1;
7058
0
        }
7059
1
        txn->remove(info_key);
7060
        // Remove sub txn index kvs
7061
1
        std::vector<std::string> sub_txn_index_keys;
7062
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7063
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7064
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
7065
0
        }
7066
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7067
0
            txn->remove(sub_txn_index_key);
7068
0
        }
7069
        // Update txn label
7070
1
        std::string label_key, label_val;
7071
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7072
1
        err = txn->get(label_key, &label_val);
7073
1
        if (err != TxnErrorCode::TXN_OK) {
7074
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7075
0
                         << " err=" << err;
7076
0
            return -1;
7077
0
        }
7078
1
        TxnLabelPB txn_label;
7079
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7080
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7081
0
            return -1;
7082
0
        }
7083
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7084
1
        if (it != txn_label.txn_ids().end()) {
7085
1
            txn_label.mutable_txn_ids()->erase(it);
7086
1
        }
7087
1
        if (txn_label.txn_ids().empty()) {
7088
1
            txn->remove(label_key);
7089
1
            TEST_SYNC_POINT_CALLBACK(
7090
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7091
1
        } else {
7092
0
            if (!txn_label.SerializeToString(&label_val)) {
7093
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7094
0
                return -1;
7095
0
            }
7096
0
            TEST_SYNC_POINT_CALLBACK(
7097
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7098
0
            txn->atomic_set_ver_value(label_key, label_val);
7099
0
            TEST_SYNC_POINT_CALLBACK(
7100
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7101
0
        }
7102
        // Remove recycle txn kv
7103
1
        txn->remove(k);
7104
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7105
1
        err = txn->commit();
7106
1
        if (err != TxnErrorCode::TXN_OK) {
7107
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
7108
0
                TEST_SYNC_POINT_CALLBACK(
7109
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7110
                // log the txn_id and label
7111
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7112
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7113
0
                             << " txn_label=" << txn_info.label();
7114
0
                return 1;
7115
0
            }
7116
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7117
0
            return -1;
7118
0
        }
7119
1
        ++num_recycled;
7120
7121
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7122
1
        return 0;
7123
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
7024
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7025
23.0k
        std::string_view k1 = k;
7026
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7027
23.0k
        k1.remove_prefix(1); // Remove key space
7028
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7029
23.0k
        int ret = decode_key(&k1, &out);
7030
23.0k
        if (ret != 0) {
7031
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7032
0
            return -1;
7033
0
        }
7034
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7035
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7036
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7037
23.0k
        std::unique_ptr<Transaction> txn;
7038
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7039
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7040
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7041
0
            return -1;
7042
0
        }
7043
        // Remove txn index kv
7044
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
7045
23.0k
        txn->remove(index_key);
7046
        // Remove txn info kv
7047
23.0k
        std::string info_key, info_val;
7048
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7049
23.0k
        err = txn->get(info_key, &info_val);
7050
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7051
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7052
0
            return -1;
7053
0
        }
7054
23.0k
        TxnInfoPB txn_info;
7055
23.0k
        if (!txn_info.ParseFromString(info_val)) {
7056
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7057
0
            return -1;
7058
0
        }
7059
23.0k
        txn->remove(info_key);
7060
        // Remove sub txn index kvs
7061
23.0k
        std::vector<std::string> sub_txn_index_keys;
7062
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7063
23.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7064
23.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
7065
23.0k
        }
7066
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7067
22.9k
            txn->remove(sub_txn_index_key);
7068
22.9k
        }
7069
        // Update txn label
7070
23.0k
        std::string label_key, label_val;
7071
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7072
23.0k
        err = txn->get(label_key, &label_val);
7073
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7074
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7075
0
                         << " err=" << err;
7076
0
            return -1;
7077
0
        }
7078
23.0k
        TxnLabelPB txn_label;
7079
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7080
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7081
0
            return -1;
7082
0
        }
7083
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7084
23.0k
        if (it != txn_label.txn_ids().end()) {
7085
23.0k
            txn_label.mutable_txn_ids()->erase(it);
7086
23.0k
        }
7087
23.0k
        if (txn_label.txn_ids().empty()) {
7088
23.0k
            txn->remove(label_key);
7089
23.0k
            TEST_SYNC_POINT_CALLBACK(
7090
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7091
23.0k
        } else {
7092
73
            if (!txn_label.SerializeToString(&label_val)) {
7093
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7094
0
                return -1;
7095
0
            }
7096
73
            TEST_SYNC_POINT_CALLBACK(
7097
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7098
73
            txn->atomic_set_ver_value(label_key, label_val);
7099
73
            TEST_SYNC_POINT_CALLBACK(
7100
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7101
73
        }
7102
        // Remove recycle txn kv
7103
23.0k
        txn->remove(k);
7104
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7105
23.0k
        err = txn->commit();
7106
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7107
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
7108
62
                TEST_SYNC_POINT_CALLBACK(
7109
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7110
                // log the txn_id and label
7111
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7112
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7113
62
                             << " txn_label=" << txn_info.label();
7114
62
                return 1;
7115
62
            }
7116
62
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7117
0
            return -1;
7118
62
        }
7119
23.0k
        ++num_recycled;
7120
7121
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7122
23.0k
        return 0;
7123
23.0k
    };
7124
7125
19
    auto loop_done = [&]() -> int {
7126
10
        DORIS_CLOUD_DEFER {
7127
10
            recycle_txn_info_keys.clear();
7128
10
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
7126
1
        DORIS_CLOUD_DEFER {
7127
1
            recycle_txn_info_keys.clear();
7128
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
7126
9
        DORIS_CLOUD_DEFER {
7127
9
            recycle_txn_info_keys.clear();
7128
9
        };
7129
10
        TEST_SYNC_POINT_CALLBACK(
7130
10
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
7131
10
                &recycle_txn_info_keys);
7132
23.0k
        for (const auto& k : recycle_txn_info_keys) {
7133
23.0k
            concurrent_delete_executor.add([&]() {
7134
23.0k
                int ret = delete_recycle_txn_kv(k);
7135
23.0k
                if (ret == 1) {
7136
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7137
54
                    for (int i = 1; i <= max_retry; ++i) {
7138
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7139
54
                        ret = delete_recycle_txn_kv(k);
7140
                        // clang-format off
7141
54
                        TEST_SYNC_POINT_CALLBACK(
7142
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
7143
                        // clang-format off
7144
54
                        if (ret != 1) {
7145
18
                            break;
7146
18
                        }
7147
                        // random sleep 0-100 ms to retry
7148
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7149
36
                    }
7150
18
                }
7151
23.0k
                if (ret != 0) {
7152
9
                    LOG_WARNING("failed to delete recycle txn kv")
7153
9
                            .tag("instance id", instance_id_)
7154
9
                            .tag("key", hex(k));
7155
9
                    return -1;
7156
9
                }
7157
23.0k
                return 0;
7158
23.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
7133
1
            concurrent_delete_executor.add([&]() {
7134
1
                int ret = delete_recycle_txn_kv(k);
7135
1
                if (ret == 1) {
7136
0
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7137
0
                    for (int i = 1; i <= max_retry; ++i) {
7138
0
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7139
0
                        ret = delete_recycle_txn_kv(k);
7140
                        // clang-format off
7141
0
                        TEST_SYNC_POINT_CALLBACK(
7142
0
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
7143
                        // clang-format off
7144
0
                        if (ret != 1) {
7145
0
                            break;
7146
0
                        }
7147
                        // random sleep 0-100 ms to retry
7148
0
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7149
0
                    }
7150
0
                }
7151
1
                if (ret != 0) {
7152
0
                    LOG_WARNING("failed to delete recycle txn kv")
7153
0
                            .tag("instance id", instance_id_)
7154
0
                            .tag("key", hex(k));
7155
0
                    return -1;
7156
0
                }
7157
1
                return 0;
7158
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
7133
23.0k
            concurrent_delete_executor.add([&]() {
7134
23.0k
                int ret = delete_recycle_txn_kv(k);
7135
23.0k
                if (ret == 1) {
7136
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7137
54
                    for (int i = 1; i <= max_retry; ++i) {
7138
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7139
54
                        ret = delete_recycle_txn_kv(k);
7140
                        // clang-format off
7141
54
                        TEST_SYNC_POINT_CALLBACK(
7142
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
7143
                        // clang-format off
7144
54
                        if (ret != 1) {
7145
18
                            break;
7146
18
                        }
7147
                        // random sleep 0-100 ms to retry
7148
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7149
36
                    }
7150
18
                }
7151
23.0k
                if (ret != 0) {
7152
9
                    LOG_WARNING("failed to delete recycle txn kv")
7153
9
                            .tag("instance id", instance_id_)
7154
9
                            .tag("key", hex(k));
7155
9
                    return -1;
7156
9
                }
7157
23.0k
                return 0;
7158
23.0k
            });
7159
23.0k
        }
7160
10
        bool finished = true;
7161
10
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7162
23.0k
        for (int r : rets) {
7163
23.0k
            if (r != 0) {
7164
9
                ret = -1;
7165
9
            }
7166
23.0k
        }
7167
7168
10
        ret = finished ? ret : -1;
7169
7170
        // Update metrics after all concurrent tasks completed
7171
10
        metrics_context.total_recycled_num = num_recycled.load();
7172
10
        metrics_context.report();
7173
7174
10
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7175
7176
10
        if (ret != 0) {
7177
3
            LOG_WARNING("recycle txn kv ret!=0")
7178
3
                    .tag("finished", finished)
7179
3
                    .tag("ret", ret)
7180
3
                    .tag("instance_id", instance_id_);
7181
3
            return ret;
7182
3
        }
7183
7
        return ret;
7184
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
7125
1
    auto loop_done = [&]() -> int {
7126
1
        DORIS_CLOUD_DEFER {
7127
1
            recycle_txn_info_keys.clear();
7128
1
        };
7129
1
        TEST_SYNC_POINT_CALLBACK(
7130
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
7131
1
                &recycle_txn_info_keys);
7132
1
        for (const auto& k : recycle_txn_info_keys) {
7133
1
            concurrent_delete_executor.add([&]() {
7134
1
                int ret = delete_recycle_txn_kv(k);
7135
1
                if (ret == 1) {
7136
1
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7137
1
                    for (int i = 1; i <= max_retry; ++i) {
7138
1
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7139
1
                        ret = delete_recycle_txn_kv(k);
7140
                        // clang-format off
7141
1
                        TEST_SYNC_POINT_CALLBACK(
7142
1
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
7143
                        // clang-format off
7144
1
                        if (ret != 1) {
7145
1
                            break;
7146
1
                        }
7147
                        // random sleep 0-100 ms to retry
7148
1
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7149
1
                    }
7150
1
                }
7151
1
                if (ret != 0) {
7152
1
                    LOG_WARNING("failed to delete recycle txn kv")
7153
1
                            .tag("instance id", instance_id_)
7154
1
                            .tag("key", hex(k));
7155
1
                    return -1;
7156
1
                }
7157
1
                return 0;
7158
1
            });
7159
1
        }
7160
1
        bool finished = true;
7161
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7162
1
        for (int r : rets) {
7163
1
            if (r != 0) {
7164
0
                ret = -1;
7165
0
            }
7166
1
        }
7167
7168
1
        ret = finished ? ret : -1;
7169
7170
        // Update metrics after all concurrent tasks completed
7171
1
        metrics_context.total_recycled_num = num_recycled.load();
7172
1
        metrics_context.report();
7173
7174
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7175
7176
1
        if (ret != 0) {
7177
0
            LOG_WARNING("recycle txn kv ret!=0")
7178
0
                    .tag("finished", finished)
7179
0
                    .tag("ret", ret)
7180
0
                    .tag("instance_id", instance_id_);
7181
0
            return ret;
7182
0
        }
7183
1
        return ret;
7184
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
7125
9
    auto loop_done = [&]() -> int {
7126
9
        DORIS_CLOUD_DEFER {
7127
9
            recycle_txn_info_keys.clear();
7128
9
        };
7129
9
        TEST_SYNC_POINT_CALLBACK(
7130
9
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
7131
9
                &recycle_txn_info_keys);
7132
23.0k
        for (const auto& k : recycle_txn_info_keys) {
7133
23.0k
            concurrent_delete_executor.add([&]() {
7134
23.0k
                int ret = delete_recycle_txn_kv(k);
7135
23.0k
                if (ret == 1) {
7136
23.0k
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7137
23.0k
                    for (int i = 1; i <= max_retry; ++i) {
7138
23.0k
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7139
23.0k
                        ret = delete_recycle_txn_kv(k);
7140
                        // clang-format off
7141
23.0k
                        TEST_SYNC_POINT_CALLBACK(
7142
23.0k
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
7143
                        // clang-format off
7144
23.0k
                        if (ret != 1) {
7145
23.0k
                            break;
7146
23.0k
                        }
7147
                        // random sleep 0-100 ms to retry
7148
23.0k
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7149
23.0k
                    }
7150
23.0k
                }
7151
23.0k
                if (ret != 0) {
7152
23.0k
                    LOG_WARNING("failed to delete recycle txn kv")
7153
23.0k
                            .tag("instance id", instance_id_)
7154
23.0k
                            .tag("key", hex(k));
7155
23.0k
                    return -1;
7156
23.0k
                }
7157
23.0k
                return 0;
7158
23.0k
            });
7159
23.0k
        }
7160
9
        bool finished = true;
7161
9
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7162
23.0k
        for (int r : rets) {
7163
23.0k
            if (r != 0) {
7164
9
                ret = -1;
7165
9
            }
7166
23.0k
        }
7167
7168
9
        ret = finished ? ret : -1;
7169
7170
        // Update metrics after all concurrent tasks completed
7171
9
        metrics_context.total_recycled_num = num_recycled.load();
7172
9
        metrics_context.report();
7173
7174
9
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7175
7176
9
        if (ret != 0) {
7177
3
            LOG_WARNING("recycle txn kv ret!=0")
7178
3
                    .tag("finished", finished)
7179
3
                    .tag("ret", ret)
7180
3
                    .tag("instance_id", instance_id_);
7181
3
            return ret;
7182
3
        }
7183
6
        return ret;
7184
9
    };
7185
7186
19
    if (config::enable_recycler_stats_metrics) {
7187
0
        scan_and_statistics_expired_txn_label();
7188
0
    }
7189
    // recycle_func and loop_done for scan and recycle
7190
19
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
7191
19
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
7192
19
}
7193
7194
struct CopyJobIdTuple {
7195
    std::string instance_id;
7196
    std::string stage_id;
7197
    long table_id;
7198
    std::string copy_id;
7199
    std::string stage_path;
7200
};
7201
struct BatchObjStoreAccessor {
7202
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
7203
                          TxnKv* txn_kv)
7204
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
7205
3
    ~BatchObjStoreAccessor() {
7206
3
        if (!paths_.empty()) {
7207
3
            consume();
7208
3
        }
7209
3
    }
7210
7211
    /**
7212
    * To implicitely do batch work and submit the batch delete task to s3
7213
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
7214
    *
7215
    * @param copy_job The protubuf struct consists of the copy job files.
7216
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
7217
    *            it would last until we finish the delete task, here we need pass one string value
7218
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
7219
    */
7220
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
7221
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
7222
5
        auto& file_keys = copy_file_keys_[key];
7223
5
        file_keys.log_trace =
7224
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
7225
5
                            instance_id, stage_id, table_id, copy_id, path);
7226
5
        std::string_view log_trace = file_keys.log_trace;
7227
2.03k
        for (const auto& file : copy_job.object_files()) {
7228
2.03k
            auto relative_path = file.relative_path();
7229
2.03k
            paths_.push_back(relative_path);
7230
2.03k
            file_keys.keys.push_back(copy_file_key(
7231
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
7232
2.03k
            LOG_INFO(log_trace)
7233
2.03k
                    .tag("relative_path", relative_path)
7234
2.03k
                    .tag("batch_count", batch_count_);
7235
2.03k
        }
7236
5
        LOG_INFO(log_trace)
7237
5
                .tag("objects_num", copy_job.object_files().size())
7238
5
                .tag("batch_count", batch_count_);
7239
        // 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
7240
        // recommend using delete objects when objects num is less than 10)
7241
5
        if (paths_.size() < 1000) {
7242
3
            return;
7243
3
        }
7244
2
        consume();
7245
2
    }
7246
7247
private:
7248
5
    void consume() {
7249
5
        DORIS_CLOUD_DEFER {
7250
5
            paths_.clear();
7251
5
            copy_file_keys_.clear();
7252
5
            batch_count_++;
7253
7254
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
7255
5
                        batch_count_);
7256
5
        };
7257
7258
5
        StopWatch sw;
7259
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
7260
5
        if (0 != accessor_->delete_files(paths_)) {
7261
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
7262
2
                        paths_.size(), batch_count_, sw.elapsed_us());
7263
2
            return;
7264
2
        }
7265
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
7266
3
                    paths_.size(), batch_count_, sw.elapsed_us());
7267
        // delete fdb's keys
7268
3
        for (auto& file_keys : copy_file_keys_) {
7269
3
            auto& [log_trace, keys] = file_keys.second;
7270
3
            std::unique_ptr<Transaction> txn;
7271
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
7272
0
                LOG(WARNING) << "failed to create txn";
7273
0
                continue;
7274
0
            }
7275
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7276
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7277
            // limited, should not cause the txn commit failed.
7278
1.02k
            for (const auto& key : keys) {
7279
1.02k
                txn->remove(key);
7280
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
7281
1.02k
            }
7282
3
            txn->remove(file_keys.first);
7283
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
7284
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
7285
0
                continue;
7286
0
            }
7287
3
        }
7288
3
    }
7289
    std::shared_ptr<StorageVaultAccessor> accessor_;
7290
    // the path of the s3 files to be deleted
7291
    std::vector<std::string> paths_;
7292
    struct CopyFiles {
7293
        std::string log_trace;
7294
        std::vector<std::string> keys;
7295
    };
7296
    // pair<std::string, std::vector<std::string>>
7297
    // first: instance_id_ stage_id table_id query_id
7298
    // second: keys to be deleted
7299
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
7300
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
7301
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
7302
    // which can together uniquely identifies different tasks for tracing log
7303
    uint64_t& batch_count_;
7304
    TxnKv* txn_kv_;
7305
};
7306
7307
13
int InstanceRecycler::recycle_copy_jobs() {
7308
13
    int64_t num_scanned = 0;
7309
13
    int64_t num_finished = 0;
7310
13
    int64_t num_expired = 0;
7311
13
    int64_t num_recycled = 0;
7312
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
7313
13
    uint64_t batch_count = 0;
7314
13
    const std::string task_name = "recycle_copy_jobs";
7315
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7316
7317
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
7318
7319
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7320
13
    register_recycle_task(task_name, start_time);
7321
7322
13
    DORIS_CLOUD_DEFER {
7323
13
        unregister_recycle_task(task_name);
7324
13
        int64_t cost =
7325
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7326
13
        metrics_context.finish_report();
7327
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7328
13
                .tag("instance_id", instance_id_)
7329
13
                .tag("num_scanned", num_scanned)
7330
13
                .tag("num_finished", num_finished)
7331
13
                .tag("num_expired", num_expired)
7332
13
                .tag("num_recycled", num_recycled);
7333
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
7322
13
    DORIS_CLOUD_DEFER {
7323
13
        unregister_recycle_task(task_name);
7324
13
        int64_t cost =
7325
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7326
13
        metrics_context.finish_report();
7327
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7328
13
                .tag("instance_id", instance_id_)
7329
13
                .tag("num_scanned", num_scanned)
7330
13
                .tag("num_finished", num_finished)
7331
13
                .tag("num_expired", num_expired)
7332
13
                .tag("num_recycled", num_recycled);
7333
13
    };
7334
7335
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7336
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7337
13
    std::string key0;
7338
13
    std::string key1;
7339
13
    copy_job_key(key_info0, &key0);
7340
13
    copy_job_key(key_info1, &key1);
7341
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
7342
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
7343
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
7344
16
                         this](std::string_view k, std::string_view v) -> int {
7345
16
        ++num_scanned;
7346
16
        CopyJobPB copy_job;
7347
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7348
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7349
0
            return -1;
7350
0
        }
7351
7352
        // decode copy job key
7353
16
        auto k1 = k;
7354
16
        k1.remove_prefix(1);
7355
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7356
16
        decode_key(&k1, &out);
7357
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7358
        // -> CopyJobPB
7359
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7360
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7361
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7362
7363
16
        bool check_storage = true;
7364
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7365
12
            ++num_finished;
7366
7367
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7368
7
                auto it = stage_accessor_map.find(stage_id);
7369
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7370
7
                std::string_view path;
7371
7
                if (it != stage_accessor_map.end()) {
7372
2
                    accessor = it->second;
7373
5
                } else {
7374
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7375
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7376
5
                                                      &inner_accessor);
7377
5
                    if (ret < 0) { // error
7378
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7379
0
                        return -1;
7380
5
                    } else if (ret == 0) {
7381
3
                        path = inner_accessor->uri();
7382
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7383
3
                                inner_accessor, batch_count, txn_kv_.get());
7384
3
                        stage_accessor_map.emplace(stage_id, accessor);
7385
3
                    } else { // stage not found, skip check storage
7386
2
                        check_storage = false;
7387
2
                    }
7388
5
                }
7389
7
                if (check_storage) {
7390
                    // TODO delete objects with key and etag is not supported
7391
5
                    accessor->add(std::move(copy_job), std::string(k),
7392
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7393
5
                    return 0;
7394
5
                }
7395
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7396
5
                int64_t current_time =
7397
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7398
5
                if (copy_job.finish_time_ms() > 0) {
7399
2
                    if (!config::force_immediate_recycle &&
7400
2
                        current_time < copy_job.finish_time_ms() +
7401
2
                                               config::copy_job_max_retention_second * 1000) {
7402
1
                        return 0;
7403
1
                    }
7404
3
                } else {
7405
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7406
3
                    if (!config::force_immediate_recycle &&
7407
3
                        current_time < copy_job.start_time_ms() +
7408
3
                                               config::copy_job_max_retention_second * 1000) {
7409
1
                        return 0;
7410
1
                    }
7411
3
                }
7412
5
            }
7413
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7414
4
            int64_t current_time =
7415
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7416
            // if copy job is timeout: delete all copy file kvs and copy job kv
7417
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7418
2
                return 0;
7419
2
            }
7420
2
            ++num_expired;
7421
2
        }
7422
7423
        // delete all copy files
7424
7
        std::vector<std::string> copy_file_keys;
7425
70
        for (auto& file : copy_job.object_files()) {
7426
70
            copy_file_keys.push_back(copy_file_key(
7427
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7428
70
        }
7429
7
        std::unique_ptr<Transaction> txn;
7430
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7431
0
            LOG(WARNING) << "failed to create txn";
7432
0
            return -1;
7433
0
        }
7434
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7435
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7436
        // limited, should not cause the txn commit failed.
7437
70
        for (const auto& key : copy_file_keys) {
7438
70
            txn->remove(key);
7439
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7440
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7441
70
                      << ", query_id=" << copy_id;
7442
70
        }
7443
7
        txn->remove(k);
7444
7
        TxnErrorCode err = txn->commit();
7445
7
        if (err != TxnErrorCode::TXN_OK) {
7446
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7447
0
            return -1;
7448
0
        }
7449
7450
7
        metrics_context.total_recycled_num = ++num_recycled;
7451
7
        metrics_context.report();
7452
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7453
7
        return 0;
7454
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
7344
16
                         this](std::string_view k, std::string_view v) -> int {
7345
16
        ++num_scanned;
7346
16
        CopyJobPB copy_job;
7347
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7348
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7349
0
            return -1;
7350
0
        }
7351
7352
        // decode copy job key
7353
16
        auto k1 = k;
7354
16
        k1.remove_prefix(1);
7355
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7356
16
        decode_key(&k1, &out);
7357
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7358
        // -> CopyJobPB
7359
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7360
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7361
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7362
7363
16
        bool check_storage = true;
7364
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7365
12
            ++num_finished;
7366
7367
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7368
7
                auto it = stage_accessor_map.find(stage_id);
7369
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7370
7
                std::string_view path;
7371
7
                if (it != stage_accessor_map.end()) {
7372
2
                    accessor = it->second;
7373
5
                } else {
7374
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7375
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7376
5
                                                      &inner_accessor);
7377
5
                    if (ret < 0) { // error
7378
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7379
0
                        return -1;
7380
5
                    } else if (ret == 0) {
7381
3
                        path = inner_accessor->uri();
7382
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7383
3
                                inner_accessor, batch_count, txn_kv_.get());
7384
3
                        stage_accessor_map.emplace(stage_id, accessor);
7385
3
                    } else { // stage not found, skip check storage
7386
2
                        check_storage = false;
7387
2
                    }
7388
5
                }
7389
7
                if (check_storage) {
7390
                    // TODO delete objects with key and etag is not supported
7391
5
                    accessor->add(std::move(copy_job), std::string(k),
7392
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7393
5
                    return 0;
7394
5
                }
7395
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7396
5
                int64_t current_time =
7397
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7398
5
                if (copy_job.finish_time_ms() > 0) {
7399
2
                    if (!config::force_immediate_recycle &&
7400
2
                        current_time < copy_job.finish_time_ms() +
7401
2
                                               config::copy_job_max_retention_second * 1000) {
7402
1
                        return 0;
7403
1
                    }
7404
3
                } else {
7405
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7406
3
                    if (!config::force_immediate_recycle &&
7407
3
                        current_time < copy_job.start_time_ms() +
7408
3
                                               config::copy_job_max_retention_second * 1000) {
7409
1
                        return 0;
7410
1
                    }
7411
3
                }
7412
5
            }
7413
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7414
4
            int64_t current_time =
7415
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7416
            // if copy job is timeout: delete all copy file kvs and copy job kv
7417
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7418
2
                return 0;
7419
2
            }
7420
2
            ++num_expired;
7421
2
        }
7422
7423
        // delete all copy files
7424
7
        std::vector<std::string> copy_file_keys;
7425
70
        for (auto& file : copy_job.object_files()) {
7426
70
            copy_file_keys.push_back(copy_file_key(
7427
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7428
70
        }
7429
7
        std::unique_ptr<Transaction> txn;
7430
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7431
0
            LOG(WARNING) << "failed to create txn";
7432
0
            return -1;
7433
0
        }
7434
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7435
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7436
        // limited, should not cause the txn commit failed.
7437
70
        for (const auto& key : copy_file_keys) {
7438
70
            txn->remove(key);
7439
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7440
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7441
70
                      << ", query_id=" << copy_id;
7442
70
        }
7443
7
        txn->remove(k);
7444
7
        TxnErrorCode err = txn->commit();
7445
7
        if (err != TxnErrorCode::TXN_OK) {
7446
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7447
0
            return -1;
7448
0
        }
7449
7450
7
        metrics_context.total_recycled_num = ++num_recycled;
7451
7
        metrics_context.report();
7452
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7453
7
        return 0;
7454
7
    };
7455
7456
13
    if (config::enable_recycler_stats_metrics) {
7457
0
        scan_and_statistics_copy_jobs();
7458
0
    }
7459
    // recycle_func and loop_done for scan and recycle
7460
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
7461
13
}
7462
7463
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
7464
                                             const StagePB::StageType& stage_type,
7465
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
7466
5
#ifdef UNIT_TEST
7467
    // In unit test, external use the same accessor as the internal stage
7468
5
    auto it = accessor_map_.find(stage_id);
7469
5
    if (it != accessor_map_.end()) {
7470
3
        *accessor = it->second;
7471
3
    } else {
7472
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
7473
2
        return 1;
7474
2
    }
7475
#else
7476
    // init s3 accessor and add to accessor map
7477
    auto stage_it =
7478
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
7479
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
7480
7481
    if (stage_it == instance_info_.stages().end()) {
7482
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
7483
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
7484
        return 1;
7485
    }
7486
7487
    const auto& object_store_info = stage_it->obj_info();
7488
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
7489
7490
    S3Conf s3_conf;
7491
    if (stage_type == StagePB::EXTERNAL) {
7492
        if (stage_access_type == StagePB::AKSK) {
7493
            auto conf = S3Conf::from_obj_store_info(object_store_info);
7494
            if (!conf) {
7495
                return -1;
7496
            }
7497
7498
            s3_conf = std::move(*conf);
7499
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
7500
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
7501
            if (!conf) {
7502
                return -1;
7503
            }
7504
7505
            s3_conf = std::move(*conf);
7506
            if (instance_info_.ram_user().has_encryption_info()) {
7507
                AkSkPair plain_ak_sk_pair;
7508
                int ret = decrypt_ak_sk_helper(
7509
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
7510
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
7511
                if (ret != 0) {
7512
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
7513
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
7514
                    return -1;
7515
                }
7516
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
7517
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
7518
            } else {
7519
                s3_conf.ak = instance_info_.ram_user().ak();
7520
                s3_conf.sk = instance_info_.ram_user().sk();
7521
            }
7522
        } else {
7523
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
7524
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
7525
            return -1;
7526
        }
7527
    } else if (stage_type == StagePB::INTERNAL) {
7528
        int idx = stoi(object_store_info.id());
7529
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7530
            LOG(WARNING) << "invalid idx: " << idx;
7531
            return -1;
7532
        }
7533
7534
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7535
        auto conf = S3Conf::from_obj_store_info(old_obj);
7536
        if (!conf) {
7537
            return -1;
7538
        }
7539
7540
        s3_conf = std::move(*conf);
7541
        s3_conf.prefix = object_store_info.prefix();
7542
    } else {
7543
        LOG(WARNING) << "unknown stage type " << stage_type;
7544
        return -1;
7545
    }
7546
7547
    std::shared_ptr<S3Accessor> s3_accessor;
7548
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
7549
    if (ret != 0) {
7550
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
7551
        return -1;
7552
    }
7553
7554
    *accessor = std::move(s3_accessor);
7555
#endif
7556
3
    return 0;
7557
5
}
7558
7559
11
int InstanceRecycler::recycle_stage() {
7560
11
    int64_t num_scanned = 0;
7561
11
    int64_t num_recycled = 0;
7562
11
    const std::string task_name = "recycle_stage";
7563
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7564
7565
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
7566
7567
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7568
11
    register_recycle_task(task_name, start_time);
7569
7570
11
    DORIS_CLOUD_DEFER {
7571
11
        unregister_recycle_task(task_name);
7572
11
        int64_t cost =
7573
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7574
11
        metrics_context.finish_report();
7575
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7576
11
                .tag("instance_id", instance_id_)
7577
11
                .tag("num_scanned", num_scanned)
7578
11
                .tag("num_recycled", num_recycled);
7579
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
7570
11
    DORIS_CLOUD_DEFER {
7571
11
        unregister_recycle_task(task_name);
7572
11
        int64_t cost =
7573
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7574
11
        metrics_context.finish_report();
7575
        LOG_WARNING("recycle stage, cost={}s", cost)
7576
11
                .tag("instance_id", instance_id_)
7577
11
                .tag("num_scanned", num_scanned)
7578
11
                .tag("num_recycled", num_recycled);
7579
11
    };
7580
7581
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7582
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7583
11
    std::string key0 = recycle_stage_key(key_info0);
7584
11
    std::string key1 = recycle_stage_key(key_info1);
7585
7586
11
    std::vector<std::string_view> stage_keys;
7587
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
7588
11
                         this](std::string_view k, std::string_view v) -> int {
7589
1
        ++num_scanned;
7590
1
        RecycleStagePB recycle_stage;
7591
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7592
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7593
0
            return -1;
7594
0
        }
7595
7596
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7597
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7598
0
            LOG(WARNING) << "invalid idx: " << idx;
7599
0
            return -1;
7600
0
        }
7601
7602
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7603
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7604
1
                [&] {
7605
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7606
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7607
1
                    if (!s3_conf) {
7608
1
                        return -1;
7609
1
                    }
7610
7611
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7612
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7613
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7614
1
                    if (ret != 0) {
7615
1
                        return -1;
7616
1
                    }
7617
7618
1
                    accessor = std::move(s3_accessor);
7619
1
                    return 0;
7620
1
                }(),
7621
1
                "recycle_stage:get_accessor", &accessor);
7622
7623
1
        if (ret != 0) {
7624
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7625
0
            return ret;
7626
0
        }
7627
7628
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7629
1
                .tag("instance_id", instance_id_)
7630
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7631
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7632
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7633
1
                .tag("obj_info_id", idx)
7634
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7635
1
        ret = accessor->delete_all();
7636
1
        if (ret != 0) {
7637
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7638
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7639
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7640
0
                         << ", ret=" << ret;
7641
0
            return -1;
7642
0
        }
7643
1
        metrics_context.total_recycled_num = ++num_recycled;
7644
1
        metrics_context.report();
7645
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7646
1
        stage_keys.push_back(k);
7647
1
        return 0;
7648
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7588
1
                         this](std::string_view k, std::string_view v) -> int {
7589
1
        ++num_scanned;
7590
1
        RecycleStagePB recycle_stage;
7591
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7592
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7593
0
            return -1;
7594
0
        }
7595
7596
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7597
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7598
0
            LOG(WARNING) << "invalid idx: " << idx;
7599
0
            return -1;
7600
0
        }
7601
7602
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7603
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7604
1
                [&] {
7605
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7606
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7607
1
                    if (!s3_conf) {
7608
1
                        return -1;
7609
1
                    }
7610
7611
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7612
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7613
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7614
1
                    if (ret != 0) {
7615
1
                        return -1;
7616
1
                    }
7617
7618
1
                    accessor = std::move(s3_accessor);
7619
1
                    return 0;
7620
1
                }(),
7621
1
                "recycle_stage:get_accessor", &accessor);
7622
7623
1
        if (ret != 0) {
7624
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7625
0
            return ret;
7626
0
        }
7627
7628
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7629
1
                .tag("instance_id", instance_id_)
7630
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7631
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7632
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7633
1
                .tag("obj_info_id", idx)
7634
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7635
1
        ret = accessor->delete_all();
7636
1
        if (ret != 0) {
7637
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7638
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7639
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7640
0
                         << ", ret=" << ret;
7641
0
            return -1;
7642
0
        }
7643
1
        metrics_context.total_recycled_num = ++num_recycled;
7644
1
        metrics_context.report();
7645
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7646
1
        stage_keys.push_back(k);
7647
1
        return 0;
7648
1
    };
7649
7650
11
    auto loop_done = [&stage_keys, this]() -> int {
7651
1
        if (stage_keys.empty()) return 0;
7652
1
        DORIS_CLOUD_DEFER {
7653
1
            stage_keys.clear();
7654
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
7652
1
        DORIS_CLOUD_DEFER {
7653
1
            stage_keys.clear();
7654
1
        };
7655
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7656
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7657
0
            return -1;
7658
0
        }
7659
1
        return 0;
7660
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
7650
1
    auto loop_done = [&stage_keys, this]() -> int {
7651
1
        if (stage_keys.empty()) return 0;
7652
1
        DORIS_CLOUD_DEFER {
7653
1
            stage_keys.clear();
7654
1
        };
7655
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7656
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7657
0
            return -1;
7658
0
        }
7659
1
        return 0;
7660
1
    };
7661
11
    if (config::enable_recycler_stats_metrics) {
7662
0
        scan_and_statistics_stage();
7663
0
    }
7664
    // recycle_func and loop_done for scan and recycle
7665
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
7666
11
}
7667
7668
10
int InstanceRecycler::recycle_expired_stage_objects() {
7669
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
7670
7671
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7672
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7673
7674
10
    DORIS_CLOUD_DEFER {
7675
10
        int64_t cost =
7676
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7677
10
        metrics_context.finish_report();
7678
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7679
10
                .tag("instance_id", instance_id_);
7680
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
7674
10
    DORIS_CLOUD_DEFER {
7675
10
        int64_t cost =
7676
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7677
10
        metrics_context.finish_report();
7678
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7679
10
                .tag("instance_id", instance_id_);
7680
10
    };
7681
7682
10
    int ret = 0;
7683
7684
10
    if (config::enable_recycler_stats_metrics) {
7685
0
        scan_and_statistics_expired_stage_objects();
7686
0
    }
7687
7688
10
    for (const auto& stage : instance_info_.stages()) {
7689
0
        std::stringstream ss;
7690
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
7691
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
7692
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
7693
0
           << ", prefix=" << stage.obj_info().prefix();
7694
7695
0
        if (stopped()) {
7696
0
            break;
7697
0
        }
7698
0
        if (stage.type() == StagePB::EXTERNAL) {
7699
0
            continue;
7700
0
        }
7701
0
        int idx = stoi(stage.obj_info().id());
7702
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7703
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
7704
0
            continue;
7705
0
        }
7706
7707
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7708
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7709
0
        if (!s3_conf) {
7710
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
7711
0
            continue;
7712
0
        }
7713
7714
0
        s3_conf->prefix = stage.obj_info().prefix();
7715
0
        std::shared_ptr<S3Accessor> accessor;
7716
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
7717
0
        if (ret1 != 0) {
7718
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
7719
0
            ret = -1;
7720
0
            continue;
7721
0
        }
7722
7723
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7724
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
7725
0
            ret = -1;
7726
0
            continue;
7727
0
        }
7728
7729
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
7730
0
        int64_t expiration_time =
7731
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
7732
0
                config::internal_stage_objects_expire_time_second;
7733
0
        if (config::force_immediate_recycle) {
7734
0
            expiration_time = INT64_MAX;
7735
0
        }
7736
0
        ret1 = accessor->delete_all(expiration_time);
7737
0
        if (ret1 != 0) {
7738
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
7739
0
                         << ss.str();
7740
0
            ret = -1;
7741
0
            continue;
7742
0
        }
7743
0
        metrics_context.total_recycled_num++;
7744
0
        metrics_context.report();
7745
0
    }
7746
10
    return ret;
7747
10
}
7748
7749
256
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
7750
256
    std::lock_guard lock(recycle_tasks_mutex);
7751
256
    running_recycle_tasks[task_name] = start_time;
7752
256
}
7753
7754
256
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
7755
256
    std::lock_guard lock(recycle_tasks_mutex);
7756
256
    DCHECK(running_recycle_tasks[task_name] > 0);
7757
256
    running_recycle_tasks.erase(task_name);
7758
256
}
7759
7760
3
bool InstanceRecycler::check_recycle_tasks() {
7761
3
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
7762
3
    {
7763
3
        std::lock_guard lock(recycle_tasks_mutex);
7764
3
        tmp_running_recycle_tasks = running_recycle_tasks;
7765
3
    }
7766
7767
3
    bool found = false;
7768
3
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7769
3
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
7770
2
        int64_t cost = now - start_time;
7771
2
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
7772
2
            LOG_INFO("recycle task cost too much time cost={}s", cost)
7773
2
                    .tag("instance_id", instance_id_)
7774
2
                    .tag("task", task_name);
7775
2
            found = true;
7776
2
        }
7777
2
    }
7778
7779
3
    return found;
7780
3
}
7781
7782
// Scan and statistics indexes that need to be recycled
7783
1
int InstanceRecycler::scan_and_statistics_indexes() {
7784
1
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
7785
1
    RecyclerMetricsContext stream_metrics_context(instance_id_, "recycle_stream");
7786
7787
1
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
7788
1
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
7789
1
    std::string index_key0;
7790
1
    std::string index_key1;
7791
1
    recycle_index_key(index_key_info0, &index_key0);
7792
1
    recycle_index_key(index_key_info1, &index_key1);
7793
1
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7794
7795
1
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7796
1
        RecycleIndexPB index_pb;
7797
1
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7798
0
            return 0;
7799
0
        }
7800
1
        int64_t current_time = ::time(nullptr);
7801
1
        if (current_time <
7802
1
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7803
0
            return 0;
7804
0
        }
7805
        // decode index_id
7806
1
        auto k1 = k;
7807
1
        k1.remove_prefix(1);
7808
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7809
1
        decode_key(&k1, &out);
7810
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7811
1
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7812
1
        std::unique_ptr<Transaction> txn;
7813
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7814
1
        if (err != TxnErrorCode::TXN_OK) {
7815
0
            return 0;
7816
0
        }
7817
1
        std::string val;
7818
1
        err = txn->get(k, &val);
7819
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7820
0
            return 0;
7821
0
        }
7822
1
        if (err != TxnErrorCode::TXN_OK) {
7823
0
            return 0;
7824
0
        }
7825
1
        index_pb.Clear();
7826
1
        if (!index_pb.ParseFromString(val)) {
7827
0
            return 0;
7828
0
        }
7829
1
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
7830
1
            if (!index_pb.has_db_id() || !index_pb.has_stream_db_id()) {
7831
0
                LOG_WARNING("table stream recycle index is missing binding")
7832
0
                        .tag("instance_id", instance_id_)
7833
0
                        .tag("stream_id", index_id);
7834
0
                return 0;
7835
0
            }
7836
2
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7837
2
                std::string end = prefix;
7838
2
                end.push_back('\xff');
7839
2
                auto count_offset = [&stream_metrics_context](std::string_view key,
7840
6
                                                              std::string_view value) {
7841
6
                    stream_metrics_context.total_need_recycle_num++;
7842
6
                    stream_metrics_context.total_need_recycle_data_size +=
7843
6
                            key.size() + value.size();
7844
6
                    return 0;
7845
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
7840
6
                                                              std::string_view value) {
7841
6
                    stream_metrics_context.total_need_recycle_num++;
7842
6
                    stream_metrics_context.total_need_recycle_data_size +=
7843
6
                            key.size() + value.size();
7844
6
                    return 0;
7845
6
                };
7846
2
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7847
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
7836
2
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7837
2
                std::string end = prefix;
7838
2
                end.push_back('\xff');
7839
2
                auto count_offset = [&stream_metrics_context](std::string_view key,
7840
2
                                                              std::string_view value) {
7841
2
                    stream_metrics_context.total_need_recycle_num++;
7842
2
                    stream_metrics_context.total_need_recycle_data_size +=
7843
2
                            key.size() + value.size();
7844
2
                    return 0;
7845
2
                };
7846
2
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7847
2
            };
7848
1
            const std::string latest_prefix = table_stream_offset_key_prefix(
7849
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7850
1
                    index_id);
7851
1
            const std::string versioned_prefix = versioned::table_stream_offset_key_prefix(
7852
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7853
1
                    index_id);
7854
1
            if (scan_offset_prefix(latest_prefix) != 0 ||
7855
1
                scan_offset_prefix(versioned_prefix) != 0) {
7856
0
                LOG_WARNING("failed to scan table stream offsets for recycle statistics")
7857
0
                        .tag("instance_id", instance_id_)
7858
0
                        .tag("stream_id", index_id);
7859
0
            }
7860
1
            return 0;
7861
1
        }
7862
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7863
0
            return 0;
7864
0
        }
7865
0
        metrics_context.total_need_recycle_num++;
7866
0
        return 0;
7867
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
7795
1
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7796
1
        RecycleIndexPB index_pb;
7797
1
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7798
0
            return 0;
7799
0
        }
7800
1
        int64_t current_time = ::time(nullptr);
7801
1
        if (current_time <
7802
1
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7803
0
            return 0;
7804
0
        }
7805
        // decode index_id
7806
1
        auto k1 = k;
7807
1
        k1.remove_prefix(1);
7808
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7809
1
        decode_key(&k1, &out);
7810
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7811
1
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7812
1
        std::unique_ptr<Transaction> txn;
7813
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7814
1
        if (err != TxnErrorCode::TXN_OK) {
7815
0
            return 0;
7816
0
        }
7817
1
        std::string val;
7818
1
        err = txn->get(k, &val);
7819
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7820
0
            return 0;
7821
0
        }
7822
1
        if (err != TxnErrorCode::TXN_OK) {
7823
0
            return 0;
7824
0
        }
7825
1
        index_pb.Clear();
7826
1
        if (!index_pb.ParseFromString(val)) {
7827
0
            return 0;
7828
0
        }
7829
1
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
7830
1
            if (!index_pb.has_db_id() || !index_pb.has_stream_db_id()) {
7831
0
                LOG_WARNING("table stream recycle index is missing binding")
7832
0
                        .tag("instance_id", instance_id_)
7833
0
                        .tag("stream_id", index_id);
7834
0
                return 0;
7835
0
            }
7836
1
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7837
1
                std::string end = prefix;
7838
1
                end.push_back('\xff');
7839
1
                auto count_offset = [&stream_metrics_context](std::string_view key,
7840
1
                                                              std::string_view value) {
7841
1
                    stream_metrics_context.total_need_recycle_num++;
7842
1
                    stream_metrics_context.total_need_recycle_data_size +=
7843
1
                            key.size() + value.size();
7844
1
                    return 0;
7845
1
                };
7846
1
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7847
1
            };
7848
1
            const std::string latest_prefix = table_stream_offset_key_prefix(
7849
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7850
1
                    index_id);
7851
1
            const std::string versioned_prefix = versioned::table_stream_offset_key_prefix(
7852
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7853
1
                    index_id);
7854
1
            if (scan_offset_prefix(latest_prefix) != 0 ||
7855
1
                scan_offset_prefix(versioned_prefix) != 0) {
7856
0
                LOG_WARNING("failed to scan table stream offsets for recycle statistics")
7857
0
                        .tag("instance_id", instance_id_)
7858
0
                        .tag("stream_id", index_id);
7859
0
            }
7860
1
            return 0;
7861
1
        }
7862
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7863
0
            return 0;
7864
0
        }
7865
0
        metrics_context.total_need_recycle_num++;
7866
0
        return 0;
7867
0
    };
7868
7869
1
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
7870
1
    metrics_context.report(true);
7871
1
    stream_metrics_context.report(true);
7872
1
    segment_metrics_context_.report(true);
7873
1
    tablet_metrics_context_.report(true);
7874
1
    return ret;
7875
1
}
7876
7877
// Scan and statistics partitions that need to be recycled
7878
0
int InstanceRecycler::scan_and_statistics_partitions() {
7879
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
7880
7881
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
7882
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
7883
0
    std::string part_key0;
7884
0
    std::string part_key1;
7885
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7886
7887
0
    recycle_partition_key(part_key_info0, &part_key0);
7888
0
    recycle_partition_key(part_key_info1, &part_key1);
7889
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
7890
0
        RecyclePartitionPB part_pb;
7891
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
7892
0
            return 0;
7893
0
        }
7894
0
        int64_t current_time = ::time(nullptr);
7895
0
        if (current_time <
7896
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
7897
0
            return 0;
7898
0
        }
7899
        // decode partition_id
7900
0
        auto k1 = k;
7901
0
        k1.remove_prefix(1);
7902
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7903
0
        decode_key(&k1, &out);
7904
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
7905
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
7906
        // Change state to RECYCLING
7907
0
        std::unique_ptr<Transaction> txn;
7908
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7909
0
        if (err != TxnErrorCode::TXN_OK) {
7910
0
            return 0;
7911
0
        }
7912
0
        std::string val;
7913
0
        err = txn->get(k, &val);
7914
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7915
0
            return 0;
7916
0
        }
7917
0
        if (err != TxnErrorCode::TXN_OK) {
7918
0
            return 0;
7919
0
        }
7920
0
        part_pb.Clear();
7921
0
        if (!part_pb.ParseFromString(val)) {
7922
0
            return 0;
7923
0
        }
7924
        // Partitions with PREPARED state MUST have no data
7925
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
7926
0
        int ret = 0;
7927
0
        for (int64_t index_id : part_pb.index_id()) {
7928
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
7929
0
                                            partition_id, is_empty_tablet) != 0) {
7930
0
                ret = 0;
7931
0
            }
7932
0
        }
7933
0
        metrics_context.total_need_recycle_num++;
7934
0
        return ret;
7935
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_
7936
7937
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
7938
0
    metrics_context.report(true);
7939
0
    segment_metrics_context_.report(true);
7940
0
    tablet_metrics_context_.report(true);
7941
0
    return ret;
7942
0
}
7943
7944
// Scan and statistics rowsets that need to be recycled
7945
0
int InstanceRecycler::scan_and_statistics_rowsets() {
7946
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
7947
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
7948
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
7949
0
    std::string recyc_rs_key0;
7950
0
    std::string recyc_rs_key1;
7951
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
7952
0
                recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
7953
0
       int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7954
7955
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
7956
0
        RecycleRowsetPB rowset;
7957
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7958
0
            return 0;
7959
0
        }
7960
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
7961
0
        int64_t current_time = ::time(nullptr);
7962
0
        if (current_time <
7963
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
7964
0
            return 0;
7965
0
        }
7966
7967
0
        if (!rowset.has_type()) {
7968
0
            if (!rowset.has_resource_id()) [[unlikely]] {
7969
0
                return 0;
7970
0
            }
7971
0
            if (rowset.resource_id().empty()) [[unlikely]] {
7972
0
                return 0;
7973
0
            }
7974
0
            metrics_context.total_need_recycle_num++;
7975
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7976
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
7977
0
            segment_metrics_context_.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7978
0
            return 0;
7979
0
        }
7980
7981
0
        if (config::enable_mark_delete_rowset_before_recycle &&
7982
0
            rowset.type() == RecycleRowsetPB::PREPARE &&
7983
0
            (!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled())) {
7984
0
            return 0;
7985
0
        }
7986
7987
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
7988
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
7989
0
                return 0;
7990
0
            }
7991
0
        }
7992
0
        metrics_context.total_need_recycle_num++;
7993
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
7994
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
7995
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
7996
0
        return 0;
7997
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_
7998
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
7999
0
    metrics_context.report(true);
8000
0
    segment_metrics_context_.report(true);
8001
0
    return ret;
8002
0
}
8003
8004
// Scan and statistics tmp_rowsets that need to be recycled
8005
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
8006
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
8007
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
8008
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
8009
0
    std::string tmp_rs_key0;
8010
0
    std::string tmp_rs_key1;
8011
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
8012
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
8013
8014
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8015
8016
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
8017
0
        doris::RowsetMetaCloudPB rowset;
8018
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
8019
0
            return 0;
8020
0
        }
8021
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
8022
0
        int64_t current_time = ::time(nullptr);
8023
0
        if (current_time < expiration) {
8024
0
            return 0;
8025
0
        }
8026
8027
0
        DCHECK_GT(rowset.txn_id(), 0)
8028
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
8029
8030
0
        if(!rowset.has_is_recycled() || !rowset.is_recycled()) {
8031
0
            return 0;
8032
0
        }
8033
8034
0
        if (!rowset.has_resource_id()) {
8035
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
8036
0
                return 0;
8037
0
            }
8038
0
            return 0;
8039
0
        }
8040
8041
0
        metrics_context.total_need_recycle_num++;
8042
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
8043
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
8044
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
8045
0
        return 0;
8046
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_
8047
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
8048
0
    metrics_context.report(true);
8049
0
    segment_metrics_context_.report(true);
8050
0
    return ret;
8051
0
}
8052
8053
// Scan and statistics abort_timeout_txn that need to be recycled
8054
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
8055
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
8056
8057
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
8058
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
8059
0
    std::string begin_txn_running_key;
8060
0
    std::string end_txn_running_key;
8061
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
8062
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
8063
8064
0
    int64_t current_time =
8065
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8066
8067
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
8068
0
                                               std::string_view k, std::string_view v) -> int {
8069
0
        std::unique_ptr<Transaction> txn;
8070
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8071
0
        if (err != TxnErrorCode::TXN_OK) {
8072
0
            return 0;
8073
0
        }
8074
0
        std::string_view k1 = k;
8075
0
        k1.remove_prefix(1);
8076
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8077
0
        if (decode_key(&k1, &out) != 0) {
8078
0
            return 0;
8079
0
        }
8080
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
8081
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
8082
        // Update txn_info
8083
0
        std::string txn_inf_key, txn_inf_val;
8084
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
8085
0
        err = txn->get(txn_inf_key, &txn_inf_val);
8086
0
        if (err != TxnErrorCode::TXN_OK) {
8087
0
            return 0;
8088
0
        }
8089
0
        TxnInfoPB txn_info;
8090
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
8091
0
            return 0;
8092
0
        }
8093
8094
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
8095
0
            TxnRunningPB txn_running_pb;
8096
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
8097
0
                return 0;
8098
0
            }
8099
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
8100
0
                return 0;
8101
0
            }
8102
0
            metrics_context.total_need_recycle_num++;
8103
0
        }
8104
0
        return 0;
8105
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_
8106
8107
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key, std::move(handle_abort_timeout_txn_kv));
8108
0
    metrics_context.report(true);
8109
0
    return ret;
8110
0
}
8111
8112
// Scan and statistics expired_txn_label that need to be recycled
8113
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
8114
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
8115
8116
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
8117
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
8118
0
    std::string begin_recycle_txn_key;
8119
0
    std::string end_recycle_txn_key;
8120
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
8121
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
8122
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8123
0
    int64_t current_time_ms =
8124
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8125
8126
    // for calculate the total num or bytes of recyled objects
8127
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
8128
0
        RecycleTxnPB recycle_txn_pb;
8129
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
8130
0
            return 0;
8131
0
        }
8132
0
        if ((config::force_immediate_recycle) ||
8133
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
8134
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
8135
0
             current_time_ms)) {
8136
0
            metrics_context.total_need_recycle_num++;
8137
0
        }
8138
0
        return 0;
8139
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_
8140
8141
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key, std::move(handle_expired_txn_label_kv));
8142
0
    metrics_context.report(true);
8143
0
    return ret;
8144
0
}
8145
8146
// Scan and statistics copy_jobs that need to be recycled
8147
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
8148
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
8149
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
8150
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
8151
0
    std::string key0;
8152
0
    std::string key1;
8153
0
    copy_job_key(key_info0, &key0);
8154
0
    copy_job_key(key_info1, &key1);
8155
8156
    // for calculate the total num or bytes of recyled objects
8157
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
8158
0
        CopyJobPB copy_job;
8159
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
8160
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
8161
0
            return 0;
8162
0
        }
8163
8164
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
8165
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
8166
0
                int64_t current_time =
8167
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8168
0
                if (copy_job.finish_time_ms() > 0) {
8169
0
                    if (!config::force_immediate_recycle &&
8170
0
                        current_time < copy_job.finish_time_ms() +
8171
0
                                               config::copy_job_max_retention_second * 1000) {
8172
0
                        return 0;
8173
0
                    }
8174
0
                } else {
8175
0
                    if (!config::force_immediate_recycle &&
8176
0
                        current_time < copy_job.start_time_ms() +
8177
0
                                               config::copy_job_max_retention_second * 1000) {
8178
0
                        return 0;
8179
0
                    }
8180
0
                }
8181
0
            }
8182
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
8183
0
            int64_t current_time =
8184
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8185
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
8186
0
                return 0;
8187
0
            }
8188
0
        }
8189
0
        metrics_context.total_need_recycle_num++;
8190
0
        return 0;
8191
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_
8192
8193
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
8194
0
    metrics_context.report(true);
8195
0
    return ret;
8196
0
}
8197
8198
// Scan and statistics stage that need to be recycled
8199
0
int InstanceRecycler::scan_and_statistics_stage() {
8200
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
8201
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
8202
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
8203
0
    std::string key0 = recycle_stage_key(key_info0);
8204
0
    std::string key1 = recycle_stage_key(key_info1);
8205
8206
    // for calculate the total num or bytes of recyled objects
8207
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
8208
0
                                                        std::string_view v) -> int {
8209
0
        RecycleStagePB recycle_stage;
8210
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
8211
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
8212
0
            return 0;
8213
0
        }
8214
8215
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
8216
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
8217
0
            LOG(WARNING) << "invalid idx: " << idx;
8218
0
            return 0;
8219
0
        }
8220
8221
0
        std::shared_ptr<StorageVaultAccessor> accessor;
8222
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
8223
0
                [&] {
8224
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
8225
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8226
0
                    if (!s3_conf) {
8227
0
                        return 0;
8228
0
                    }
8229
8230
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
8231
0
                    std::shared_ptr<S3Accessor> s3_accessor;
8232
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
8233
0
                    if (ret != 0) {
8234
0
                        return 0;
8235
0
                    }
8236
8237
0
                    accessor = std::move(s3_accessor);
8238
0
                    return 0;
8239
0
                }(),
8240
0
                "recycle_stage:get_accessor", &accessor);
8241
8242
0
        if (ret != 0) {
8243
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
8244
0
            return 0;
8245
0
        }
8246
8247
0
        metrics_context.total_need_recycle_num++;
8248
0
        return 0;
8249
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_
8250
8251
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
8252
0
    metrics_context.report(true);
8253
0
    return ret;
8254
0
}
8255
8256
// Scan and statistics expired_stage_objects that need to be recycled
8257
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
8258
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
8259
8260
    // for calculate the total num or bytes of recyled objects
8261
0
    auto scan_and_statistics = [&metrics_context, this]() {
8262
0
        for (const auto& stage : instance_info_.stages()) {
8263
0
            if (stopped()) {
8264
0
                break;
8265
0
            }
8266
0
            if (stage.type() == StagePB::EXTERNAL) {
8267
0
                continue;
8268
0
            }
8269
0
            int idx = stoi(stage.obj_info().id());
8270
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
8271
0
                continue;
8272
0
            }
8273
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
8274
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8275
0
            if (!s3_conf) {
8276
0
                continue;
8277
0
            }
8278
0
            s3_conf->prefix = stage.obj_info().prefix();
8279
0
            std::shared_ptr<S3Accessor> accessor;
8280
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
8281
0
            if (ret1 != 0) {
8282
0
                continue;
8283
0
            }
8284
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
8285
0
                continue;
8286
0
            }
8287
0
            metrics_context.total_need_recycle_num++;
8288
0
        }
8289
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
8290
8291
0
    scan_and_statistics();
8292
0
    metrics_context.report(true);
8293
0
    return 0;
8294
0
}
8295
8296
// Scan and statistics versions that need to be recycled
8297
0
int InstanceRecycler::scan_and_statistics_versions() {
8298
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
8299
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
8300
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
8301
8302
0
    int64_t last_scanned_table_id = 0;
8303
0
    bool is_recycled = false; // Is last scanned kv recycled
8304
    // for calculate the total num or bytes of recyled objects
8305
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
8306
0
                                       std::string_view k, std::string_view) {
8307
0
        auto k1 = k;
8308
0
        k1.remove_prefix(1);
8309
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
8310
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8311
0
        decode_key(&k1, &out);
8312
0
        DCHECK_EQ(out.size(), 6) << k;
8313
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
8314
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
8315
0
            metrics_context.total_need_recycle_num +=
8316
0
                    is_recycled; // Version kv of this table has been recycled
8317
0
            return 0;
8318
0
        }
8319
0
        last_scanned_table_id = table_id;
8320
0
        is_recycled = false;
8321
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
8322
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
8323
0
        std::unique_ptr<Transaction> txn;
8324
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8325
0
        if (err != TxnErrorCode::TXN_OK) {
8326
0
            return 0;
8327
0
        }
8328
0
        std::unique_ptr<RangeGetIterator> iter;
8329
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
8330
0
        if (err != TxnErrorCode::TXN_OK) {
8331
0
            return 0;
8332
0
        }
8333
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
8334
0
            return 0;
8335
0
        }
8336
0
        metrics_context.total_need_recycle_num++;
8337
0
        is_recycled = true;
8338
0
        return 0;
8339
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_
8340
8341
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
8342
0
    metrics_context.report(true);
8343
0
    return ret;
8344
0
}
8345
8346
// Scan and statistics restore jobs that need to be recycled
8347
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
8348
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
8349
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
8350
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
8351
0
    std::string restore_job_key0;
8352
0
    std::string restore_job_key1;
8353
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
8354
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
8355
8356
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8357
8358
    // for calculate the total num or bytes of recyled objects
8359
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
8360
0
        RestoreJobCloudPB restore_job_pb;
8361
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
8362
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
8363
0
            return 0;
8364
0
        }
8365
0
        int64_t expiration =
8366
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
8367
0
        int64_t current_time = ::time(nullptr);
8368
0
        if (current_time < expiration) { // not expired
8369
0
            return 0;
8370
0
        }
8371
0
        metrics_context.total_need_recycle_num++;
8372
0
        if(restore_job_pb.need_recycle_data()) {
8373
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
8374
0
        }
8375
0
        return 0;
8376
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_
8377
8378
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
8379
0
    metrics_context.report(true);
8380
0
    return ret;
8381
0
}
8382
8383
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
8384
3
    if (!should_recycle_versioned_keys()) {
8385
0
        return;
8386
0
    }
8387
8388
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
8389
8390
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
8391
3
    if (recycle_checker.init() != 0) {
8392
0
        return;
8393
0
    }
8394
8395
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
8396
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
8397
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
8398
8399
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
8400
8
    for (; iter->valid(); iter->next()) {
8401
5
        OperationLogPB operation_log;
8402
5
        if (!iter->parse_value(&operation_log)) {
8403
0
            continue;
8404
0
        }
8405
8406
5
        std::string_view key = iter->key();
8407
5
        Versionstamp log_versionstamp;
8408
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
8409
0
            continue;
8410
0
        }
8411
8412
5
        OperationLogReferenceInfo ref_info;
8413
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
8414
5
                                         &ref_info)) {
8415
4
            metrics_context.total_need_recycle_num++;
8416
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
8417
4
        }
8418
5
    }
8419
8420
3
    metrics_context.report(true);
8421
3
}
8422
8423
int InstanceRecycler::classify_rowset_task_by_ref_count(
8424
60
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
8425
60
    constexpr int MAX_RETRY = 10;
8426
60
    const auto& rowset_meta = task.rowset_meta;
8427
60
    int64_t tablet_id = rowset_meta.tablet_id();
8428
60
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
8429
60
    std::string_view reference_instance_id = instance_id_;
8430
60
    if (rowset_meta.has_reference_instance_id()) {
8431
5
        reference_instance_id = rowset_meta.reference_instance_id();
8432
5
    }
8433
8434
61
    for (int i = 0; i < MAX_RETRY; ++i) {
8435
61
        std::unique_ptr<Transaction> txn;
8436
61
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8437
61
        if (err != TxnErrorCode::TXN_OK) {
8438
0
            LOG_WARNING("failed to create txn when classifying rowset task")
8439
0
                    .tag("instance_id", instance_id_)
8440
0
                    .tag("tablet_id", tablet_id)
8441
0
                    .tag("rowset_id", rowset_id)
8442
0
                    .tag("err", err);
8443
0
            return -1;
8444
0
        }
8445
8446
61
        std::string rowset_ref_count_key =
8447
61
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
8448
61
        task.rowset_ref_count_key = rowset_ref_count_key;
8449
8450
61
        int64_t ref_count = 0;
8451
61
        {
8452
61
            std::string value;
8453
61
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
8454
61
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
8455
0
                ref_count = 1;
8456
61
            } else if (err != TxnErrorCode::TXN_OK) {
8457
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
8458
0
                        .tag("instance_id", instance_id_)
8459
0
                        .tag("tablet_id", tablet_id)
8460
0
                        .tag("rowset_id", rowset_id)
8461
0
                        .tag("err", err);
8462
0
                return -1;
8463
61
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
8464
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
8465
0
                        .tag("instance_id", instance_id_)
8466
0
                        .tag("tablet_id", tablet_id)
8467
0
                        .tag("rowset_id", rowset_id)
8468
0
                        .tag("value", hex(value));
8469
0
                return -1;
8470
0
            }
8471
61
        }
8472
8473
61
        if (ref_count > 1) {
8474
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
8475
12
            txn->atomic_add(rowset_ref_count_key, -1);
8476
12
            LOG_INFO("decrease rowset data ref count in classification phase")
8477
12
                    .tag("instance_id", instance_id_)
8478
12
                    .tag("tablet_id", tablet_id)
8479
12
                    .tag("rowset_id", rowset_id)
8480
12
                    .tag("ref_count", ref_count - 1)
8481
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
8482
8483
12
            if (!task.recycle_rowset_key.empty()) {
8484
0
                txn->remove(task.recycle_rowset_key);
8485
0
                LOG_INFO("remove recycle rowset key in classification phase")
8486
0
                        .tag("key", hex(task.recycle_rowset_key));
8487
0
            }
8488
12
            if (!task.non_versioned_rowset_key.empty()) {
8489
12
                txn->remove(task.non_versioned_rowset_key);
8490
12
                LOG_INFO("remove non versioned rowset key in classification phase")
8491
12
                        .tag("key", hex(task.non_versioned_rowset_key));
8492
12
            }
8493
8494
12
            err = txn->commit();
8495
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
8496
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
8497
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
8498
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
8499
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
8500
1
                continue;
8501
11
            } else if (err != TxnErrorCode::TXN_OK) {
8502
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
8503
0
                        .tag("instance_id", instance_id_)
8504
0
                        .tag("tablet_id", tablet_id)
8505
0
                        .tag("rowset_id", rowset_id)
8506
0
                        .tag("err", err);
8507
0
                return -1;
8508
0
            }
8509
11
            return 1; // handled, not added to batch delete
8510
49
        } else {
8511
            // ref_count == 1: Add to batch delete plan without modifying any KV.
8512
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
8513
49
            LOG_INFO("add rowset to batch delete plan")
8514
49
                    .tag("instance_id", instance_id_)
8515
49
                    .tag("tablet_id", tablet_id)
8516
49
                    .tag("rowset_id", rowset_id)
8517
49
                    .tag("resource_id", rowset_meta.resource_id())
8518
49
                    .tag("ref_count", ref_count);
8519
8520
49
            batch_delete_tasks.push_back(std::move(task));
8521
49
            return 0; // added to batch delete
8522
49
        }
8523
61
    }
8524
8525
0
    LOG_WARNING("failed to classify rowset task after retry")
8526
0
            .tag("instance_id", instance_id_)
8527
0
            .tag("tablet_id", tablet_id)
8528
0
            .tag("rowset_id", rowset_id)
8529
0
            .tag("retry", MAX_RETRY);
8530
0
    return -1;
8531
60
}
8532
8533
10
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
8534
10
    int ret = 0;
8535
49
    for (const auto& task : tasks) {
8536
49
        int64_t tablet_id = task.rowset_meta.tablet_id();
8537
49
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
8538
8539
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
8540
        // so we don't need to call it again here.
8541
8542
        // Remove all metadata keys in one transaction
8543
49
        std::unique_ptr<Transaction> txn;
8544
49
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8545
49
        if (err != TxnErrorCode::TXN_OK) {
8546
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
8547
0
                    .tag("instance_id", instance_id_)
8548
0
                    .tag("tablet_id", tablet_id)
8549
0
                    .tag("rowset_id", rowset_id)
8550
0
                    .tag("err", err);
8551
0
            ret = -1;
8552
0
            continue;
8553
0
        }
8554
8555
49
        std::string_view reference_instance_id = instance_id_;
8556
49
        if (task.rowset_meta.has_reference_instance_id()) {
8557
0
            reference_instance_id = task.rowset_meta.reference_instance_id();
8558
0
        }
8559
8560
49
        txn->remove(task.rowset_ref_count_key);
8561
49
        LOG_INFO("delete rowset data ref count key in cleanup phase")
8562
49
                .tag("instance_id", instance_id_)
8563
49
                .tag("tablet_id", tablet_id)
8564
49
                .tag("rowset_id", rowset_id)
8565
49
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
8566
8567
49
        std::string dbm_start_key =
8568
49
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
8569
49
        std::string dbm_end_key = meta_delete_bitmap_key(
8570
49
                {reference_instance_id, tablet_id, rowset_id,
8571
49
                 std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
8572
49
        txn->remove(dbm_start_key, dbm_end_key);
8573
49
        LOG_INFO("remove delete bitmap kv in cleanup phase")
8574
49
                .tag("instance_id", instance_id_)
8575
49
                .tag("tablet_id", tablet_id)
8576
49
                .tag("rowset_id", rowset_id)
8577
49
                .tag("begin", hex(dbm_start_key))
8578
49
                .tag("end", hex(dbm_end_key));
8579
8580
49
        std::string versioned_dbm_start_key =
8581
49
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
8582
49
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
8583
49
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
8584
49
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
8585
49
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
8586
49
                .tag("instance_id", instance_id_)
8587
49
                .tag("tablet_id", tablet_id)
8588
49
                .tag("rowset_id", rowset_id)
8589
49
                .tag("begin", hex(versioned_dbm_start_key))
8590
49
                .tag("end", hex(versioned_dbm_end_key));
8591
8592
        // Remove versioned meta rowset key
8593
49
        if (!task.versioned_rowset_key.empty()) {
8594
49
            versioned::document_remove<RowsetMetaCloudPB>(
8595
49
                txn.get(), task.versioned_rowset_key, task.versionstamp);
8596
49
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
8597
49
                    .tag("instance_id", instance_id_)
8598
49
                    .tag("tablet_id", tablet_id)
8599
49
                    .tag("rowset_id", rowset_id)
8600
49
                    .tag("key_prefix", hex(task.versioned_rowset_key));
8601
49
        }
8602
8603
49
        if (!task.non_versioned_rowset_key.empty()) {
8604
49
            txn->remove(task.non_versioned_rowset_key);
8605
49
            LOG_INFO("remove non versioned rowset key in cleanup phase")
8606
49
                    .tag("instance_id", instance_id_)
8607
49
                    .tag("tablet_id", tablet_id)
8608
49
                    .tag("rowset_id", rowset_id)
8609
49
                    .tag("key", hex(task.non_versioned_rowset_key));
8610
49
        }
8611
8612
        // Remove recycle_rowset_key last to ensure retry safety:
8613
        // if cleanup fails, this key remains and triggers next round retry.
8614
49
        if (!task.recycle_rowset_key.empty()) {
8615
0
            txn->remove(task.recycle_rowset_key);
8616
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
8617
0
                    .tag("instance_id", instance_id_)
8618
0
                    .tag("tablet_id", tablet_id)
8619
0
                    .tag("rowset_id", rowset_id)
8620
0
                    .tag("key", hex(task.recycle_rowset_key));
8621
0
        }
8622
8623
49
        err = txn->commit();
8624
49
        if (err != TxnErrorCode::TXN_OK) {
8625
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
8626
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
8627
0
                    .tag("instance_id", instance_id_)
8628
0
                    .tag("tablet_id", tablet_id)
8629
0
                    .tag("rowset_id", rowset_id)
8630
0
                    .tag("err", err);
8631
0
            ret = -1;
8632
0
            continue;
8633
0
        }
8634
8635
49
        LOG_INFO("cleanup rowset metadata success")
8636
49
                .tag("instance_id", instance_id_)
8637
49
                .tag("tablet_id", tablet_id)
8638
49
                .tag("rowset_id", rowset_id);
8639
49
    }
8640
10
    return ret;
8641
10
}
8642
8643
} // namespace doris::cloud