Coverage Report

Created: 2026-05-19 20:01

/root/doris/cloud/src/recycler/recycler.cpp
Line
Count
Source (jump to first uncovered line)
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "recycler/recycler.h"
19
20
#include <brpc/builtin_service.pb.h>
21
#include <brpc/server.h>
22
#include <butil/endpoint.h>
23
#include <butil/strings/string_split.h>
24
#include <bvar/status.h>
25
#include <gen_cpp/cloud.pb.h>
26
#include <gen_cpp/olap_file.pb.h>
27
28
#include <algorithm>
29
#include <atomic>
30
#include <chrono>
31
#include <cstddef>
32
#include <cstdint>
33
#include <cstdlib>
34
#include <deque>
35
#include <functional>
36
#include <initializer_list>
37
#include <memory>
38
#include <numeric>
39
#include <optional>
40
#include <random>
41
#include <string>
42
#include <string_view>
43
#include <thread>
44
#include <unordered_map>
45
#include <utility>
46
#include <variant>
47
48
#include "common/defer.h"
49
#include "common/stopwatch.h"
50
#include "meta-service/meta_service.h"
51
#include "meta-service/meta_service_helper.h"
52
#include "meta-service/meta_service_schema.h"
53
#include "meta-store/blob_message.h"
54
#include "meta-store/meta_reader.h"
55
#include "meta-store/txn_kv.h"
56
#include "meta-store/txn_kv_error.h"
57
#include "meta-store/versioned_value.h"
58
#include "recycler/checker.h"
59
#ifdef ENABLE_HDFS_STORAGE_VAULT
60
#include "recycler/hdfs_accessor.h"
61
#endif
62
#include "recycler/s3_accessor.h"
63
#include "recycler/storage_vault_accessor.h"
64
#ifdef UNIT_TEST
65
#include "../test/mock_accessor.h"
66
#endif
67
#include "common/bvars.h"
68
#include "common/config.h"
69
#include "common/encryption_util.h"
70
#include "common/logging.h"
71
#include "common/simple_thread_pool.h"
72
#include "common/util.h"
73
#include "cpp/sync_point.h"
74
#include "meta-store/codec.h"
75
#include "meta-store/document_message.h"
76
#include "meta-store/keys.h"
77
#include "recycler/recycler_service.h"
78
#include "recycler/sync_executor.h"
79
#include "recycler/util.h"
80
#include "snapshot/snapshot_manager_factory.h"
81
82
namespace doris::cloud {
83
84
using namespace std::chrono;
85
86
namespace {
87
88
0
int64_t packed_file_retry_sleep_ms() {
89
0
    const int64_t min_ms = std::max<int64_t>(0, config::packed_file_txn_retry_sleep_min_ms);
90
0
    const int64_t max_ms = std::max<int64_t>(min_ms, config::packed_file_txn_retry_sleep_max_ms);
91
0
    thread_local std::mt19937_64 gen(std::random_device {}());
92
0
    std::uniform_int_distribution<int64_t> dist(min_ms, max_ms);
93
0
    return dist(gen);
94
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
95
96
0
void sleep_for_packed_file_retry() {
97
0
    std::this_thread::sleep_for(std::chrono::milliseconds(packed_file_retry_sleep_ms()));
98
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
99
100
} // namespace
101
102
// return 0 for success get a key, 1 for key not found, negative for error
103
0
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
104
0
    std::unique_ptr<Transaction> txn;
105
0
    TxnErrorCode err = txn_kv->create_txn(&txn);
106
0
    if (err != TxnErrorCode::TXN_OK) {
107
0
        return -1;
108
0
    }
109
0
    switch (txn->get(key, &val, true)) {
110
0
    case TxnErrorCode::TXN_OK:
111
0
        return 0;
112
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
113
0
        return 1;
114
0
    default:
115
0
        return -1;
116
0
    };
117
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
118
119
// 0 for success, negative for error
120
static int txn_get(TxnKv* txn_kv, std::string_view begin, std::string_view end,
121
337
                   std::unique_ptr<RangeGetIterator>& it) {
122
337
    std::unique_ptr<Transaction> txn;
123
337
    TxnErrorCode err = txn_kv->create_txn(&txn);
124
337
    if (err != TxnErrorCode::TXN_OK) {
125
0
        return -1;
126
0
    }
127
337
    switch (txn->get(begin, end, &it, true)) {
128
337
    case TxnErrorCode::TXN_OK:
129
337
        return 0;
130
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
131
0
        return 1;
132
0
    default:
133
0
        return -1;
134
337
    };
135
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
121
31
                   std::unique_ptr<RangeGetIterator>& it) {
122
31
    std::unique_ptr<Transaction> txn;
123
31
    TxnErrorCode err = txn_kv->create_txn(&txn);
124
31
    if (err != TxnErrorCode::TXN_OK) {
125
0
        return -1;
126
0
    }
127
31
    switch (txn->get(begin, end, &it, true)) {
128
31
    case TxnErrorCode::TXN_OK:
129
31
        return 0;
130
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
131
0
        return 1;
132
0
    default:
133
0
        return -1;
134
31
    };
135
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
121
306
                   std::unique_ptr<RangeGetIterator>& it) {
122
306
    std::unique_ptr<Transaction> txn;
123
306
    TxnErrorCode err = txn_kv->create_txn(&txn);
124
306
    if (err != TxnErrorCode::TXN_OK) {
125
0
        return -1;
126
0
    }
127
306
    switch (txn->get(begin, end, &it, true)) {
128
306
    case TxnErrorCode::TXN_OK:
129
306
        return 0;
130
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
131
0
        return 1;
132
0
    default:
133
0
        return -1;
134
306
    };
135
0
}
136
137
// return 0 for success otherwise error
138
6
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
139
6
    std::unique_ptr<Transaction> txn;
140
6
    TxnErrorCode err = txn_kv->create_txn(&txn);
141
6
    if (err != TxnErrorCode::TXN_OK) {
142
0
        return -1;
143
0
    }
144
10
    for (auto k : keys) {
145
10
        txn->remove(k);
146
10
    }
147
6
    switch (txn->commit()) {
148
6
    case TxnErrorCode::TXN_OK:
149
6
        return 0;
150
0
    case TxnErrorCode::TXN_CONFLICT:
151
0
        return -1;
152
0
    default:
153
0
        return -1;
154
6
    }
155
6
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
138
1
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
139
1
    std::unique_ptr<Transaction> txn;
140
1
    TxnErrorCode err = txn_kv->create_txn(&txn);
141
1
    if (err != TxnErrorCode::TXN_OK) {
142
0
        return -1;
143
0
    }
144
1
    for (auto k : keys) {
145
1
        txn->remove(k);
146
1
    }
147
1
    switch (txn->commit()) {
148
1
    case TxnErrorCode::TXN_OK:
149
1
        return 0;
150
0
    case TxnErrorCode::TXN_CONFLICT:
151
0
        return -1;
152
0
    default:
153
0
        return -1;
154
1
    }
155
1
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
138
5
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
139
5
    std::unique_ptr<Transaction> txn;
140
5
    TxnErrorCode err = txn_kv->create_txn(&txn);
141
5
    if (err != TxnErrorCode::TXN_OK) {
142
0
        return -1;
143
0
    }
144
9
    for (auto k : keys) {
145
9
        txn->remove(k);
146
9
    }
147
5
    switch (txn->commit()) {
148
5
    case TxnErrorCode::TXN_OK:
149
5
        return 0;
150
0
    case TxnErrorCode::TXN_CONFLICT:
151
0
        return -1;
152
0
    default:
153
0
        return -1;
154
5
    }
155
5
}
156
157
// return 0 for success otherwise error
158
139
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
159
139
    std::unique_ptr<Transaction> txn;
160
139
    TxnErrorCode err = txn_kv->create_txn(&txn);
161
139
    if (err != TxnErrorCode::TXN_OK) {
162
0
        return -1;
163
0
    }
164
105k
    for (auto& k : keys) {
165
105k
        txn->remove(k);
166
105k
    }
167
139
    switch (txn->commit()) {
168
139
    case TxnErrorCode::TXN_OK:
169
139
        return 0;
170
0
    case TxnErrorCode::TXN_CONFLICT:
171
0
        return -1;
172
0
    default:
173
0
        return -1;
174
139
    }
175
139
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
158
33
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
159
33
    std::unique_ptr<Transaction> txn;
160
33
    TxnErrorCode err = txn_kv->create_txn(&txn);
161
33
    if (err != TxnErrorCode::TXN_OK) {
162
0
        return -1;
163
0
    }
164
33
    for (auto& k : keys) {
165
16
        txn->remove(k);
166
16
    }
167
33
    switch (txn->commit()) {
168
33
    case TxnErrorCode::TXN_OK:
169
33
        return 0;
170
0
    case TxnErrorCode::TXN_CONFLICT:
171
0
        return -1;
172
0
    default:
173
0
        return -1;
174
33
    }
175
33
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
158
106
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
159
106
    std::unique_ptr<Transaction> txn;
160
106
    TxnErrorCode err = txn_kv->create_txn(&txn);
161
106
    if (err != TxnErrorCode::TXN_OK) {
162
0
        return -1;
163
0
    }
164
105k
    for (auto& k : keys) {
165
105k
        txn->remove(k);
166
105k
    }
167
106
    switch (txn->commit()) {
168
106
    case TxnErrorCode::TXN_OK:
169
106
        return 0;
170
0
    case TxnErrorCode::TXN_CONFLICT:
171
0
        return -1;
172
0
    default:
173
0
        return -1;
174
106
    }
175
106
}
176
177
// return 0 for success otherwise error
178
[[maybe_unused]] static int txn_remove(TxnKv* txn_kv, std::string_view begin,
179
106k
                                       std::string_view end) {
180
106k
    std::unique_ptr<Transaction> txn;
181
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
182
106k
    if (err != TxnErrorCode::TXN_OK) {
183
0
        return -1;
184
0
    }
185
106k
    txn->remove(begin, end);
186
106k
    switch (txn->commit()) {
187
106k
    case TxnErrorCode::TXN_OK:
188
106k
        return 0;
189
0
    case TxnErrorCode::TXN_CONFLICT:
190
0
        return -1;
191
0
    default:
192
0
        return -1;
193
106k
    }
194
106k
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
179
16
                                       std::string_view end) {
180
16
    std::unique_ptr<Transaction> txn;
181
16
    TxnErrorCode err = txn_kv->create_txn(&txn);
182
16
    if (err != TxnErrorCode::TXN_OK) {
183
0
        return -1;
184
0
    }
185
16
    txn->remove(begin, end);
186
16
    switch (txn->commit()) {
187
16
    case TxnErrorCode::TXN_OK:
188
16
        return 0;
189
0
    case TxnErrorCode::TXN_CONFLICT:
190
0
        return -1;
191
0
    default:
192
0
        return -1;
193
16
    }
194
16
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
179
106k
                                       std::string_view end) {
180
106k
    std::unique_ptr<Transaction> txn;
181
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
182
106k
    if (err != TxnErrorCode::TXN_OK) {
183
0
        return -1;
184
0
    }
185
106k
    txn->remove(begin, end);
186
106k
    switch (txn->commit()) {
187
106k
    case TxnErrorCode::TXN_OK:
188
106k
        return 0;
189
0
    case TxnErrorCode::TXN_CONFLICT:
190
0
        return -1;
191
0
    default:
192
0
        return -1;
193
106k
    }
194
106k
}
195
196
void scan_restore_job_rowset(
197
        Transaction* txn, const std::string& instance_id, int64_t tablet_id, MetaServiceCode& code,
198
        std::string& msg,
199
        std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>* restore_job_rs_metas);
200
201
static inline void check_recycle_task(const std::string& instance_id, const std::string& task_name,
202
                                      int64_t num_scanned, int64_t num_recycled,
203
47
                                      int64_t start_time) {
204
47
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
205
0
        int64_t cost =
206
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
207
0
        if (cost > config::recycle_task_threshold_seconds) {
208
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
209
0
                    .tag("instance_id", instance_id)
210
0
                    .tag("task", task_name)
211
0
                    .tag("num_scanned", num_scanned)
212
0
                    .tag("num_recycled", num_recycled);
213
0
        }
214
0
    }
215
47
    return;
216
47
}
recycler.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
203
2
                                      int64_t start_time) {
204
2
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
205
0
        int64_t cost =
206
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
207
0
        if (cost > config::recycle_task_threshold_seconds) {
208
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
209
0
                    .tag("instance_id", instance_id)
210
0
                    .tag("task", task_name)
211
0
                    .tag("num_scanned", num_scanned)
212
0
                    .tag("num_recycled", num_recycled);
213
0
        }
214
0
    }
215
2
    return;
216
2
}
recycler_test.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
203
45
                                      int64_t start_time) {
204
45
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
205
0
        int64_t cost =
206
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
207
0
        if (cost > config::recycle_task_threshold_seconds) {
208
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
209
0
                    .tag("instance_id", instance_id)
210
0
                    .tag("task", task_name)
211
0
                    .tag("num_scanned", num_scanned)
212
0
                    .tag("num_recycled", num_recycled);
213
0
        }
214
0
    }
215
45
    return;
216
45
}
217
218
6
Recycler::Recycler(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
219
6
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
220
221
6
    auto s3_producer_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
222
6
                                                               "s3_producer_pool");
223
6
    s3_producer_pool->start();
224
6
    auto recycle_tablet_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
225
6
                                                                  "recycle_tablet_pool");
226
6
    recycle_tablet_pool->start();
227
6
    auto group_recycle_function_pool = std::make_shared<SimpleThreadPool>(
228
6
            config::recycle_pool_parallelism, "group_recycle_function_pool");
229
6
    group_recycle_function_pool->start();
230
6
    _thread_pool_group =
231
6
            RecyclerThreadPoolGroup(std::move(s3_producer_pool), std::move(recycle_tablet_pool),
232
6
                                    std::move(group_recycle_function_pool));
233
234
6
    auto resource_mgr = std::make_shared<ResourceManager>(txn_kv_);
235
6
    txn_lazy_committer_ = std::make_shared<TxnLazyCommitter>(txn_kv_, std::move(resource_mgr));
236
6
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
237
6
}
238
239
6
Recycler::~Recycler() {
240
6
    if (!stopped()) {
241
0
        stop();
242
0
    }
243
6
}
244
245
5
void Recycler::instance_scanner_callback() {
246
    // sleep 60 seconds before scheduling for the launch procedure to complete:
247
    // some bad hdfs connection may cause some log to stdout stderr
248
    // which may pollute .out file and affect the script to check success
249
5
    std::this_thread::sleep_for(
250
5
            std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
251
1.34k
    while (!stopped()) {
252
1.34k
        if (config::enable_recycler) {
253
4
            std::vector<InstanceInfoPB> instances;
254
4
            get_all_instances(txn_kv_.get(), instances);
255
            // TODO(plat1ko): delete job recycle kv of non-existent instances
256
4
            LOG(INFO) << "Recycler get instances: " << [&instances] {
257
4
                std::stringstream ss;
258
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
259
4
                return ss.str();
260
4
            }();
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
Line
Count
Source
256
4
            LOG(INFO) << "Recycler get instances: " << [&instances] {
257
4
                std::stringstream ss;
258
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
259
4
                return ss.str();
260
4
            }();
261
4
            if (!instances.empty()) {
262
                // enqueue instances
263
3
                std::lock_guard lock(mtx_);
264
30
                for (auto& instance : instances) {
265
30
                    if (instance_filter_.filter_out(instance.instance_id())) continue;
266
30
                    auto [_, success] = pending_instance_set_.insert(instance.instance_id());
267
                    // skip instance already in pending queue
268
30
                    if (success) {
269
30
                        pending_instance_queue_.push_back(std::move(instance));
270
30
                    }
271
30
                }
272
3
                pending_instance_cond_.notify_all();
273
3
            }
274
1.33k
        } else {
275
1.33k
            LOG(WARNING) << "Skip recycler since enable_recycler is false";
276
1.33k
        }
277
1.34k
        {
278
1.34k
            std::unique_lock lock(mtx_);
279
1.34k
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
280
2.68k
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
280
2.68k
                               [&]() { return stopped(); });
281
1.34k
        }
282
1.34k
    }
283
5
}
284
285
8
void Recycler::recycle_callback() {
286
38
    while (!stopped()) {
287
38
        InstanceInfoPB instance;
288
38
        {
289
38
            std::unique_lock lock(mtx_);
290
38
            pending_instance_cond_.wait(
291
52
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
291
52
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
292
38
            if (stopped()) {
293
8
                return;
294
8
            }
295
30
            instance = std::move(pending_instance_queue_.front());
296
30
            pending_instance_queue_.pop_front();
297
30
            pending_instance_set_.erase(instance.instance_id());
298
30
        }
299
0
        auto& instance_id = instance.instance_id();
300
30
        {
301
30
            std::lock_guard lock(mtx_);
302
            // skip instance in recycling
303
30
            if (recycling_instance_map_.count(instance_id)) continue;
304
30
        }
305
30
        if (!config::enable_recycler) {
306
1
            LOG(WARNING) << "Skip recycle instance_id=" << instance_id
307
1
                         << " since enable_recycler is false";
308
1
            continue;
309
1
        }
310
29
        auto instance_recycler = std::make_shared<InstanceRecycler>(
311
29
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
312
313
29
        if (int r = instance_recycler->init(); r != 0) {
314
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
315
0
                         << " ret=" << r;
316
0
            continue;
317
0
        }
318
29
        std::string recycle_job_key;
319
29
        job_recycle_key({instance_id}, &recycle_job_key);
320
29
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
321
29
                                               ip_port_, config::recycle_interval_seconds * 1000);
322
29
        if (ret != 0) { // Prepare failed
323
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
324
20
                         << " ret=" << ret;
325
20
            continue;
326
20
        } else {
327
9
            std::lock_guard lock(mtx_);
328
9
            recycling_instance_map_.emplace(instance_id, instance_recycler);
329
9
        }
330
9
        if (stopped()) return;
331
9
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
332
9
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
333
9
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
334
9
        g_bvar_recycler_instance_recycle_task_status.put({"submitted"}, 1);
335
9
        ret = instance_recycler->do_recycle();
336
        // If instance recycler has been aborted, don't finish this job
337
338
10
        if (!instance_recycler->stopped()) {
339
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
340
10
                                        ret == 0, ctime_ms);
341
10
        }
342
10
        if (instance_recycler->stopped() || ret != 0) {
343
0
            g_bvar_recycler_instance_recycle_task_status.put({"error"}, 1);
344
0
        }
345
9
        {
346
9
            std::lock_guard lock(mtx_);
347
9
            recycling_instance_map_.erase(instance_id);
348
9
        }
349
350
9
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
351
9
        auto elpased_ms = now - ctime_ms;
352
9
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
353
9
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
354
9
        g_bvar_recycler_instance_next_ts.put({instance_id},
355
9
                                             now + config::recycle_interval_seconds * 1000);
356
9
        g_bvar_recycler_instance_recycle_task_status.put({"completed"}, 1);
357
9
        LOG(INFO) << "recycle instance done, "
358
9
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
359
9
                  << " now: " << now;
360
361
9
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
362
363
9
        LOG_WARNING("finish recycle instance")
364
9
                .tag("instance_id", instance_id)
365
9
                .tag("cost_ms", elpased_ms);
366
9
    }
367
8
}
368
369
4
void Recycler::lease_recycle_jobs() {
370
54
    while (!stopped()) {
371
50
        std::vector<std::string> instances;
372
50
        instances.reserve(recycling_instance_map_.size());
373
50
        {
374
50
            std::lock_guard lock(mtx_);
375
50
            for (auto& [id, _] : recycling_instance_map_) {
376
30
                instances.push_back(id);
377
30
            }
378
50
        }
379
50
        for (auto& i : instances) {
380
30
            std::string recycle_job_key;
381
30
            job_recycle_key({i}, &recycle_job_key);
382
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
383
30
            if (ret == 1) {
384
0
                std::lock_guard lock(mtx_);
385
0
                if (auto it = recycling_instance_map_.find(i);
386
0
                    it != recycling_instance_map_.end()) {
387
0
                    it->second->stop();
388
0
                }
389
0
            }
390
30
        }
391
50
        {
392
50
            std::unique_lock lock(mtx_);
393
50
            notifier_.wait_for(lock,
394
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
395
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
395
100
                               [&]() { return stopped(); });
396
50
        }
397
50
    }
398
4
}
399
400
4
void Recycler::check_recycle_tasks() {
401
7
    while (!stopped()) {
402
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
403
3
        {
404
3
            std::lock_guard lock(mtx_);
405
3
            recycling_instance_map = recycling_instance_map_;
406
3
        }
407
3
        for (auto& entry : recycling_instance_map) {
408
0
            entry.second->check_recycle_tasks();
409
0
        }
410
411
3
        std::unique_lock lock(mtx_);
412
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
413
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
413
6
                           [&]() { return stopped(); });
414
3
    }
415
4
}
416
417
4
int Recycler::start(brpc::Server* server) {
418
4
    instance_filter_.reset(config::recycle_whitelist, config::recycle_blacklist);
419
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
420
4
    S3Environment::getInstance();
421
422
4
    if (config::enable_checker) {
423
0
        checker_ = std::make_unique<Checker>(txn_kv_);
424
0
        int ret = checker_->start();
425
0
        std::string msg;
426
0
        if (ret != 0) {
427
0
            msg = "failed to start checker";
428
0
            LOG(ERROR) << msg;
429
0
            std::cerr << msg << std::endl;
430
0
            return ret;
431
0
        }
432
0
        msg = "checker started";
433
0
        LOG(INFO) << msg;
434
0
        std::cout << msg << std::endl;
435
0
    }
436
437
4
    if (server) {
438
        // Add service
439
1
        auto recycler_service =
440
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
441
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
442
1
    }
443
444
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
444
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
445
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
446
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
446
8
        workers_.emplace_back([this] { recycle_callback(); });
447
8
    }
448
449
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
450
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
451
452
4
    if (config::enable_snapshot_data_migrator) {
453
0
        snapshot_data_migrator_ = std::make_shared<SnapshotDataMigrator>(txn_kv_);
454
0
        int ret = snapshot_data_migrator_->start();
455
0
        if (ret != 0) {
456
0
            LOG(ERROR) << "failed to start snapshot data migrator";
457
0
            return ret;
458
0
        }
459
0
        LOG(INFO) << "snapshot data migrator started";
460
0
    }
461
462
4
    if (config::enable_snapshot_chain_compactor) {
463
0
        snapshot_chain_compactor_ = std::make_shared<SnapshotChainCompactor>(txn_kv_);
464
0
        int ret = snapshot_chain_compactor_->start();
465
0
        if (ret != 0) {
466
0
            LOG(ERROR) << "failed to start snapshot chain compactor";
467
0
            return ret;
468
0
        }
469
0
        LOG(INFO) << "snapshot chain compactor started";
470
0
    }
471
472
4
    return 0;
473
4
}
474
475
4
void Recycler::stop() {
476
4
    stopped_ = true;
477
4
    notifier_.notify_all();
478
4
    pending_instance_cond_.notify_all();
479
4
    {
480
4
        std::lock_guard lock(mtx_);
481
4
        for (auto& [_, recycler] : recycling_instance_map_) {
482
0
            recycler->stop();
483
0
        }
484
4
    }
485
20
    for (auto& w : workers_) {
486
20
        if (w.joinable()) w.join();
487
20
    }
488
4
    if (checker_) {
489
0
        checker_->stop();
490
0
    }
491
4
    if (snapshot_data_migrator_) {
492
0
        snapshot_data_migrator_->stop();
493
0
    }
494
4
    if (snapshot_chain_compactor_) {
495
0
        snapshot_chain_compactor_->stop();
496
0
    }
497
4
}
498
499
class InstanceRecycler::InvertedIndexIdCache {
500
public:
501
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
502
132
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
503
504
    // Return 0 if success, 1 if schema kv not found, negative for error
505
    // For the same index_id, schema_version, res, since `get` is not completely atomic
506
    // one thread has not finished inserting, and another thread has not get the index_id and schema_version,
507
    // resulting in repeated addition and inaccuracy.
508
    // however, this approach can reduce the lock range and sacrifice a bit of meta repeated get to improve concurrency performance.
509
    // repeated addition does not affect correctness.
510
28.4k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
511
28.4k
        {
512
28.4k
            std::lock_guard lock(mtx_);
513
28.4k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
514
4.11k
                return 0;
515
4.11k
            }
516
24.2k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
517
24.2k
                it != inverted_index_id_map_.end()) {
518
17.4k
                res = it->second;
519
17.4k
                return 0;
520
17.4k
            }
521
24.2k
        }
522
        // Get schema from kv
523
        // TODO(plat1ko): Single flight
524
6.87k
        std::unique_ptr<Transaction> txn;
525
6.87k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
526
6.87k
        if (err != TxnErrorCode::TXN_OK) {
527
0
            LOG(WARNING) << "failed to create txn, err=" << err;
528
0
            return -1;
529
0
        }
530
6.87k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
531
6.87k
        ValueBuf val_buf;
532
6.87k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
533
6.87k
        if (err != TxnErrorCode::TXN_OK) {
534
500
            LOG(WARNING) << "failed to get schema, err=" << err;
535
500
            return static_cast<int>(err);
536
500
        }
537
6.37k
        doris::TabletSchemaCloudPB schema;
538
6.37k
        if (!parse_schema_value(val_buf, &schema)) {
539
0
            LOG(WARNING) << "malformed schema value, key=" << hex(schema_key);
540
0
            return -1;
541
0
        }
542
6.37k
        if (schema.index_size() > 0) {
543
4.78k
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
544
4.78k
            if (schema.has_inverted_index_storage_format()) {
545
4.77k
                index_format = schema.inverted_index_storage_format();
546
4.77k
            }
547
4.78k
            res.first = index_format;
548
4.78k
            res.second.reserve(schema.index_size());
549
12.3k
            for (auto& i : schema.index()) {
550
12.3k
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
551
12.3k
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
552
12.3k
                }
553
12.3k
            }
554
4.78k
        }
555
6.37k
        insert(index_id, schema_version, res);
556
6.37k
        return 0;
557
6.37k
    }
558
559
    // Empty `ids` means this schema has no inverted index
560
6.37k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
561
6.37k
        if (index_info.second.empty()) {
562
1.59k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
563
1.59k
            std::lock_guard lock(mtx_);
564
1.59k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
565
4.78k
        } else {
566
4.78k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
567
4.78k
            std::lock_guard lock(mtx_);
568
4.78k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
569
4.78k
        }
570
6.37k
    }
571
572
private:
573
    std::string instance_id_;
574
    std::shared_ptr<TxnKv> txn_kv_;
575
576
    std::mutex mtx_;
577
    using Key = std::pair<int64_t, int32_t>; // <index_id, schema_version>
578
    struct HashOfKey {
579
59.0k
        size_t operator()(const Key& key) const {
580
59.0k
            size_t seed = 0;
581
59.0k
            seed = std::hash<int64_t> {}(key.first);
582
59.0k
            seed = std::hash<int32_t> {}(key.second);
583
59.0k
            return seed;
584
59.0k
        }
585
    };
586
    // <index_id, schema_version> -> inverted_index_ids
587
    std::unordered_map<Key, InvertedIndexInfo, HashOfKey> inverted_index_id_map_;
588
    // Store <index_id, schema_version> of schema which doesn't have inverted index
589
    std::unordered_set<Key, HashOfKey> schemas_without_inverted_index_;
590
};
591
592
InstanceRecycler::InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
593
                                   RecyclerThreadPoolGroup thread_pool_group,
594
                                   std::shared_ptr<TxnLazyCommitter> txn_lazy_committer)
595
        : txn_kv_(std::move(txn_kv)),
596
          instance_id_(instance.instance_id()),
597
          instance_info_(instance),
598
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
599
          _thread_pool_group(std::move(thread_pool_group)),
600
          txn_lazy_committer_(std::move(txn_lazy_committer)),
601
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
602
132
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
603
132
    delete_bitmap_lock_white_list_->init();
604
132
    resource_mgr_->init();
605
606
132
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
607
608
    // Since the recycler's resource manager could not be notified when instance info changes,
609
    // we need to refresh the instance info here to ensure the resource manager has the latest info.
610
132
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
611
132
};
612
613
132
InstanceRecycler::~InstanceRecycler() = default;
614
615
116
int InstanceRecycler::init_obj_store_accessors() {
616
116
    for (const auto& obj_info : instance_info_.obj_info()) {
617
76
#ifdef UNIT_TEST
618
76
        auto accessor = std::make_shared<MockAccessor>();
619
#else
620
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
621
        if (!s3_conf) {
622
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
623
            return -1;
624
        }
625
626
        std::shared_ptr<S3Accessor> accessor;
627
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
628
        if (ret != 0) {
629
            LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
630
                         << " resource_id=" << obj_info.id();
631
            return ret;
632
        }
633
#endif
634
76
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
635
76
    }
636
637
116
    return 0;
638
116
}
639
640
116
int InstanceRecycler::init_storage_vault_accessors() {
641
116
    if (instance_info_.resource_ids().empty()) {
642
109
        return 0;
643
109
    }
644
645
7
    FullRangeGetOptions opts(txn_kv_);
646
7
    opts.prefetch = true;
647
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
648
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
649
650
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
651
18
        auto [k, v] = *kv;
652
18
        StorageVaultPB vault;
653
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
654
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
655
0
            return -1;
656
0
        }
657
18
        std::string recycler_storage_vault_white_list = accumulate(
658
18
                config::recycler_storage_vault_white_list.begin(),
659
18
                config::recycler_storage_vault_white_list.end(), std::string(),
660
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
660
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
661
18
        LOG_INFO("config::recycler_storage_vault_white_list")
662
18
                .tag("", recycler_storage_vault_white_list);
663
18
        if (!config::recycler_storage_vault_white_list.empty()) {
664
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
665
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
666
8
                it == config::recycler_storage_vault_white_list.end()) {
667
2
                LOG_WARNING(
668
2
                        "failed to init accessor for vault because this vault is not in "
669
2
                        "config::recycler_storage_vault_white_list. ")
670
2
                        .tag(" vault name:", vault.name())
671
2
                        .tag(" config::recycler_storage_vault_white_list:",
672
2
                             recycler_storage_vault_white_list);
673
2
                continue;
674
2
            }
675
8
        }
676
16
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
677
16
                                 &accessor_map_, &vault);
678
16
        if (vault.has_hdfs_info()) {
679
9
#ifdef ENABLE_HDFS_STORAGE_VAULT
680
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
681
9
            int ret = accessor->init();
682
9
            if (ret != 0) {
683
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
684
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
685
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
686
4
                continue;
687
4
            }
688
5
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
689
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
690
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
691
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
692
#else
693
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
694
                       << "but HDFS storage vaults were detected";
695
#endif
696
7
        } else if (vault.has_obj_info()) {
697
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
698
7
            if (!s3_conf) {
699
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
700
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
701
1
                continue;
702
1
            }
703
704
6
            std::shared_ptr<S3Accessor> accessor;
705
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
706
6
            if (ret != 0) {
707
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
708
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
709
0
                             << " ret=" << ret
710
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
711
0
                continue;
712
0
            }
713
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
714
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
715
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
716
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
717
6
        }
718
16
    }
719
720
7
    if (!it->is_valid()) {
721
0
        LOG_WARNING("failed to get storage vault kv");
722
0
        return -1;
723
0
    }
724
725
7
    if (accessor_map_.empty()) {
726
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
727
1
        return -2;
728
1
    }
729
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
730
6
             instance_id_);
731
732
6
    return 0;
733
7
}
734
735
116
int InstanceRecycler::init() {
736
116
    int ret = init_obj_store_accessors();
737
116
    if (ret != 0) {
738
0
        return ret;
739
0
    }
740
741
116
    return init_storage_vault_accessors();
742
116
}
743
744
template <typename... Func>
745
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
746
120
    return [funcs...]() {
747
120
        return [](std::initializer_list<int> ret_vals) {
748
120
            int i = 0;
749
140
            for (int ret : ret_vals) {
750
140
                if (ret != 0) {
751
0
                    i = ret;
752
0
                }
753
140
            }
754
120
            return i;
755
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
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
0
                    i = ret;
752
0
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
0
                    i = ret;
752
0
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
20
            for (int ret : ret_vals) {
750
20
                if (ret != 0) {
751
0
                    i = ret;
752
0
                }
753
20
            }
754
10
            return i;
755
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
0
                    i = ret;
752
0
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
0
                    i = ret;
752
0
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
0
                    i = ret;
752
0
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
20
            for (int ret : ret_vals) {
750
20
                if (ret != 0) {
751
0
                    i = ret;
752
0
                }
753
20
            }
754
10
            return i;
755
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
0
                    i = ret;
752
0
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
0
                    i = ret;
752
0
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
0
                    i = ret;
752
0
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
0
                    i = ret;
752
0
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
0
                    i = ret;
752
0
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
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
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
757
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
745
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
757
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
745
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
757
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
745
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
757
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
745
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
757
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
745
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
757
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
745
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
757
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
745
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
757
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
745
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
757
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
745
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
757
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
745
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
757
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
745
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
757
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
745
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
746
10
    return [funcs...]() {
747
10
        return [](std::initializer_list<int> ret_vals) {
748
10
            int i = 0;
749
10
            for (int ret : ret_vals) {
750
10
                if (ret != 0) {
751
10
                    i = ret;
752
10
                }
753
10
            }
754
10
            return i;
755
10
        }({funcs()...});
756
10
    };
757
10
}
758
759
10
int InstanceRecycler::do_recycle() {
760
10
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
761
10
    tablet_metrics_context_.reset();
762
10
    segment_metrics_context_.reset();
763
10
    DORIS_CLOUD_DEFER {
764
10
        tablet_metrics_context_.finish_report();
765
10
        segment_metrics_context_.finish_report();
766
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
763
10
    DORIS_CLOUD_DEFER {
764
10
        tablet_metrics_context_.finish_report();
765
10
        segment_metrics_context_.finish_report();
766
10
    };
767
10
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
768
0
        int res = recycle_cluster_snapshots();
769
0
        if (res != 0) {
770
0
            return -1;
771
0
        }
772
0
        return recycle_deleted_instance();
773
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
774
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
775
10
                                        fmt::format("instance id {}", instance_id_),
776
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
776
120
                                        [](int r) { return r != 0; });
777
10
        sync_executor
778
10
                .add(task_wrapper(
779
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
779
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
780
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
780
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
781
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
782
                                   // becase they may both recycle the same set of tablets
783
                        // recycle dropped table or idexes(mv, rollup)
784
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
784
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
785
                        // recycle dropped partitions
786
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
786
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
787
10
                .add(task_wrapper(
788
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
788
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
789
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
789
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
790
10
                .add(task_wrapper(
791
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
791
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
792
10
                .add(task_wrapper(
793
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
793
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
794
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
794
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
795
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
795
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
796
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
796
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
797
10
                .add(task_wrapper(
798
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
798
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
799
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
799
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
800
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
800
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
801
10
        bool finished = true;
802
10
        std::vector<int> rets = sync_executor.when_all(&finished);
803
120
        for (int ret : rets) {
804
120
            if (ret != 0) {
805
0
                return ret;
806
0
            }
807
120
        }
808
10
        return finished ? 0 : -1;
809
10
    } else {
810
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
811
0
                     << " instance_id=" << instance_id_;
812
0
        return -1;
813
0
    }
814
10
}
815
816
/**
817
* 1. delete all remote data
818
* 2. delete all kv
819
* 3. remove instance kv
820
*/
821
5
int InstanceRecycler::recycle_deleted_instance() {
822
5
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
823
824
5
    int ret = 0;
825
5
    auto start_time = steady_clock::now();
826
827
5
    DORIS_CLOUD_DEFER {
828
5
        auto cost = duration<float>(steady_clock::now() - start_time).count();
829
5
        LOG(WARNING) << (ret == 0 ? "successfully" : "failed to")
830
5
                     << " recycle deleted instance, cost=" << cost
831
5
                     << "s, instance_id=" << instance_id_;
832
5
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
827
5
    DORIS_CLOUD_DEFER {
828
5
        auto cost = duration<float>(steady_clock::now() - start_time).count();
829
5
        LOG(WARNING) << (ret == 0 ? "successfully" : "failed to")
830
5
                     << " recycle deleted instance, cost=" << cost
831
5
                     << "s, instance_id=" << instance_id_;
832
5
    };
833
834
    // Step 1: Recycle tmp rowsets (contains ref count but txn is not committed)
835
5
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
836
5
        int res = recycle_tmp_rowsets();
837
5
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
838
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
839
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
840
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
841
            // and cannot be recycled.
842
5
            res = recycle_tmp_rowsets();
843
5
        }
844
5
        return res;
845
5
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_1clEv
Line
Count
Source
835
5
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
836
5
        int res = recycle_tmp_rowsets();
837
5
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
838
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
839
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
840
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
841
            // and cannot be recycled.
842
5
            res = recycle_tmp_rowsets();
843
5
        }
844
5
        return res;
845
5
    };
846
5
    if (recycle_tmp_rowsets_with_mark_delete_enabled() != 0) {
847
0
        LOG_WARNING("failed to recycle tmp rowsets").tag("instance_id", instance_id_);
848
0
        ret = -1;
849
0
        return -1;
850
0
    }
851
852
    // Step 2: Recycle versioned rowsets in recycle space (already marked for deletion)
853
5
    if (recycle_versioned_rowsets() != 0) {
854
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
855
0
        ret = -1;
856
0
        return -1;
857
0
    }
858
859
    // Step 3: Recycle operation logs (can recycle logs not referenced by snapshots)
860
5
    if (recycle_operation_logs() != 0) {
861
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
862
0
        ret = -1;
863
0
        return -1;
864
0
    }
865
866
    // Step 4: Check if there are still cluster snapshots
867
5
    bool has_snapshots = false;
868
5
    if (has_cluster_snapshots(&has_snapshots) != 0) {
869
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
870
0
        ret = -1;
871
0
        return -1;
872
5
    } else if (has_snapshots) {
873
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
874
1
        return 0;
875
1
    }
876
877
4
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
878
4
                            instance_info().snapshot_switch_status() !=
879
1
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
880
4
    if (snapshot_enabled) {
881
1
        bool has_unrecycled_rowsets = false;
882
1
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
883
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
884
0
            ret = -1;
885
0
            return -1;
886
1
        } else if (has_unrecycled_rowsets) {
887
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
888
0
                    .tag("instance_id", instance_id_);
889
0
            return ret;
890
0
        }
891
3
    } else { // delete all remote data if snapshot is disabled
892
3
        for (auto& [_, accessor] : accessor_map_) {
893
3
            if (stopped()) {
894
0
                return ret;
895
0
            }
896
897
3
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
898
3
            int del_ret = accessor->delete_all();
899
3
            if (del_ret == 0) {
900
3
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
901
3
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
902
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
903
                // so the recycling has been successful.
904
0
                ret = -1;
905
0
            }
906
3
        }
907
908
3
        if (ret != 0) {
909
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
910
0
            return ret;
911
0
        }
912
3
    }
913
914
    // Check successor instance, if exists, skip deleting kv because successor instance may still need the data in kv
915
4
    if (instance_info_.has_successor_instance_id() &&
916
4
        !instance_info_.successor_instance_id().empty()) {
917
0
        std::string key = instance_key(instance_info_.successor_instance_id());
918
0
        std::unique_ptr<Transaction> txn;
919
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
920
0
        if (err != TxnErrorCode::TXN_OK) {
921
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_
922
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
923
0
                         << " err=" << err;
924
0
            ret = -1;
925
0
            return -1;
926
0
        }
927
928
0
        std::string value;
929
0
        err = txn->get(key, &value);
930
0
        if (err == TxnErrorCode::TXN_OK) {
931
0
            LOG(INFO) << "instance successor instance is still exist, skip deleting kv,"
932
0
                      << " instance_id=" << instance_id_
933
0
                      << " successor_instance_id=" << instance_info_.successor_instance_id();
934
0
            return 0;
935
0
        } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
936
0
            LOG(WARNING) << "failed to get successor instance, instance_id=" << instance_id_
937
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
938
0
                         << " err=" << err;
939
0
            ret = -1;
940
0
            return -1;
941
0
        }
942
0
    }
943
944
    // delete all kv
945
4
    std::unique_ptr<Transaction> txn;
946
4
    TxnErrorCode err = txn_kv_->create_txn(&txn);
947
4
    if (err != TxnErrorCode::TXN_OK) {
948
0
        LOG(WARNING) << "failed to create txn";
949
0
        ret = -1;
950
0
        return -1;
951
0
    }
952
4
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
953
    // delete kv before deleting objects to prevent the checker from misjudging data loss
954
4
    std::string start_txn_key = txn_key_prefix(instance_id_);
955
4
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
956
4
    txn->remove(start_txn_key, end_txn_key);
957
4
    std::string start_version_key = version_key_prefix(instance_id_);
958
4
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
959
4
    txn->remove(start_version_key, end_version_key);
960
4
    std::string start_meta_key = meta_key_prefix(instance_id_);
961
4
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
962
4
    txn->remove(start_meta_key, end_meta_key);
963
4
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
964
4
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
965
4
    txn->remove(start_recycle_key, end_recycle_key);
966
4
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
967
4
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
968
4
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
969
4
    std::string start_copy_key = copy_key_prefix(instance_id_);
970
4
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
971
4
    txn->remove(start_copy_key, end_copy_key);
972
    // should not remove job key range, because we need to reserve job recycle kv
973
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
974
4
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
975
4
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
976
4
    txn->remove(start_job_tablet_key, end_job_tablet_key);
977
4
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
978
4
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
979
4
    std::string start_vault_key = storage_vault_key(key_info0);
980
4
    std::string end_vault_key = storage_vault_key(key_info1);
981
4
    txn->remove(start_vault_key, end_vault_key);
982
4
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
983
4
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
984
4
    txn->remove(versioned_version_key_start, versioned_version_key_end);
985
4
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
986
4
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
987
4
    txn->remove(versioned_index_key_start, versioned_index_key_end);
988
4
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
989
4
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
990
4
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
991
4
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
992
4
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
993
4
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
994
4
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
995
4
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
996
4
    txn->remove(versioned_data_key_start, versioned_data_key_end);
997
4
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
998
4
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
999
4
    txn->remove(versioned_log_key_start, versioned_log_key_end);
1000
4
    err = txn->commit();
1001
4
    if (err != TxnErrorCode::TXN_OK) {
1002
0
        LOG(WARNING) << "failed to delete all kv, instance_id=" << instance_id_ << ", err=" << err;
1003
0
        ret = -1;
1004
0
    }
1005
1006
4
    if (ret == 0) {
1007
        // remove instance kv
1008
        // ATTN: MUST ensure that cloud platform won't regenerate the same instance id
1009
4
        err = txn_kv_->create_txn(&txn);
1010
4
        if (err != TxnErrorCode::TXN_OK) {
1011
0
            LOG(WARNING) << "failed to create txn";
1012
0
            ret = -1;
1013
0
            return ret;
1014
0
        }
1015
4
        std::string key;
1016
4
        instance_key({instance_id_}, &key);
1017
4
        txn->atomic_add(system_meta_service_instance_update_key(), 1);
1018
4
        txn->remove(key);
1019
4
        err = txn->commit();
1020
4
        if (err != TxnErrorCode::TXN_OK) {
1021
0
            LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
1022
0
                         << " err=" << err;
1023
0
            ret = -1;
1024
0
        }
1025
4
    }
1026
4
    return ret;
1027
4
}
1028
1029
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
1030
9
                                          bool* exists, PackedFileRecycleStats* stats) {
1031
9
    if (exists == nullptr) {
1032
0
        return -1;
1033
0
    }
1034
9
    *exists = false;
1035
1036
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
1037
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1038
9
    std::string scan_begin = begin;
1039
1040
9
    while (true) {
1041
9
        std::unique_ptr<RangeGetIterator> it_range;
1042
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
1043
9
        if (get_ret < 0) {
1044
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1045
0
                    .tag("instance_id", instance_id_)
1046
0
                    .tag("tablet_id", tablet_id)
1047
0
                    .tag("ret", get_ret);
1048
0
            return -1;
1049
0
        }
1050
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1051
6
            return 0;
1052
6
        }
1053
1054
3
        std::string last_key;
1055
3
        while (it_range->has_next()) {
1056
3
            auto [k, v] = it_range->next();
1057
3
            last_key.assign(k.data(), k.size());
1058
3
            doris::RowsetMetaCloudPB rowset_meta;
1059
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1060
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1061
0
                        .tag("instance_id", instance_id_)
1062
0
                        .tag("tablet_id", tablet_id)
1063
0
                        .tag("key", hex(k));
1064
0
                continue;
1065
0
            }
1066
3
            if (stats) {
1067
3
                ++stats->rowset_scan_count;
1068
3
            }
1069
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1070
3
                *exists = true;
1071
3
                return 0;
1072
3
            }
1073
3
        }
1074
1075
0
        if (!it_range->more()) {
1076
0
            return 0;
1077
0
        }
1078
1079
        // Continue scanning from the next key to keep each transaction short.
1080
0
        scan_begin = std::move(last_key);
1081
0
        scan_begin.push_back('\x00');
1082
0
    }
1083
9
}
1084
1085
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1086
                                                          const std::string& rowset_id,
1087
                                                          int64_t txn_id, bool* recycle_exists,
1088
11
                                                          bool* tmp_exists) {
1089
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1090
0
        return -1;
1091
0
    }
1092
11
    *recycle_exists = false;
1093
11
    *tmp_exists = false;
1094
1095
11
    if (txn_id <= 0) {
1096
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1097
0
                .tag("instance_id", instance_id_)
1098
0
                .tag("tablet_id", tablet_id)
1099
0
                .tag("rowset_id", rowset_id)
1100
0
                .tag("txn_id", txn_id);
1101
0
        return -1;
1102
0
    }
1103
1104
11
    std::unique_ptr<Transaction> txn;
1105
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1106
11
    if (err != TxnErrorCode::TXN_OK) {
1107
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1108
0
                .tag("instance_id", instance_id_)
1109
0
                .tag("tablet_id", tablet_id)
1110
0
                .tag("rowset_id", rowset_id)
1111
0
                .tag("txn_id", txn_id)
1112
0
                .tag("err", err);
1113
0
        return -1;
1114
0
    }
1115
1116
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1117
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1118
11
    if (ret == TxnErrorCode::TXN_OK) {
1119
1
        *recycle_exists = true;
1120
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1121
0
        LOG_WARNING("failed to check recycle rowset existence")
1122
0
                .tag("instance_id", instance_id_)
1123
0
                .tag("tablet_id", tablet_id)
1124
0
                .tag("rowset_id", rowset_id)
1125
0
                .tag("key", hex(recycle_key))
1126
0
                .tag("err", ret);
1127
0
        return -1;
1128
0
    }
1129
1130
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1131
11
    ret = key_exists(txn.get(), tmp_key, true);
1132
11
    if (ret == TxnErrorCode::TXN_OK) {
1133
1
        *tmp_exists = true;
1134
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1135
0
        LOG_WARNING("failed to check tmp rowset existence")
1136
0
                .tag("instance_id", instance_id_)
1137
0
                .tag("tablet_id", tablet_id)
1138
0
                .tag("txn_id", txn_id)
1139
0
                .tag("key", hex(tmp_key))
1140
0
                .tag("err", ret);
1141
0
        return -1;
1142
0
    }
1143
1144
11
    return 0;
1145
11
}
1146
1147
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1148
8
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1149
8
    if (!hint.empty()) {
1150
8
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1151
8
            return {hint, it->second};
1152
8
        }
1153
8
    }
1154
1155
0
    return {"", nullptr};
1156
8
}
1157
1158
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1159
                                               const std::string& packed_file_path,
1160
3
                                               PackedFileRecycleStats* stats) {
1161
3
    bool local_changed = false;
1162
3
    int64_t left_num = 0;
1163
3
    int64_t left_bytes = 0;
1164
3
    bool all_small_files_confirmed = true;
1165
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1166
1167
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1168
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1169
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1170
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1171
14
        LOG_INFO("packed slice correction status")
1172
14
                .tag("instance_id", instance_id_)
1173
14
                .tag("packed_file_path", packed_file_path)
1174
14
                .tag("small_file_path", file.path())
1175
14
                .tag("tablet_id", tablet_id)
1176
14
                .tag("rowset_id", rowset_id)
1177
14
                .tag("txn_id", txn_id)
1178
14
                .tag("size", file.size())
1179
14
                .tag("deleted", file.deleted())
1180
14
                .tag("corrected", file.corrected())
1181
14
                .tag("confirmed_this_round", confirmed_this_round);
1182
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
1167
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1168
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1169
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1170
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1171
14
        LOG_INFO("packed slice correction status")
1172
14
                .tag("instance_id", instance_id_)
1173
14
                .tag("packed_file_path", packed_file_path)
1174
14
                .tag("small_file_path", file.path())
1175
14
                .tag("tablet_id", tablet_id)
1176
14
                .tag("rowset_id", rowset_id)
1177
14
                .tag("txn_id", txn_id)
1178
14
                .tag("size", file.size())
1179
14
                .tag("deleted", file.deleted())
1180
14
                .tag("corrected", file.corrected())
1181
14
                .tag("confirmed_this_round", confirmed_this_round);
1182
14
    };
1183
1184
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1185
14
        auto* small_file = packed_info->mutable_slices(i);
1186
14
        if (small_file->deleted()) {
1187
3
            log_small_file_status(*small_file, small_file->corrected());
1188
3
            continue;
1189
3
        }
1190
1191
11
        if (small_file->corrected()) {
1192
0
            left_num++;
1193
0
            left_bytes += small_file->size();
1194
0
            log_small_file_status(*small_file, true);
1195
0
            continue;
1196
0
        }
1197
1198
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1199
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1200
0
                    .tag("instance_id", instance_id_)
1201
0
                    .tag("small_file_path", small_file->path())
1202
0
                    .tag("index", i);
1203
0
            return -1;
1204
0
        }
1205
1206
11
        int64_t tablet_id = small_file->tablet_id();
1207
11
        const std::string& rowset_id = small_file->rowset_id();
1208
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1209
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1210
0
                    .tag("instance_id", instance_id_)
1211
0
                    .tag("small_file_path", small_file->path())
1212
0
                    .tag("index", i)
1213
0
                    .tag("tablet_id", tablet_id)
1214
0
                    .tag("rowset_id", rowset_id)
1215
0
                    .tag("has_txn_id", small_file->has_txn_id())
1216
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1217
0
            return -1;
1218
0
        }
1219
11
        int64_t txn_id = small_file->txn_id();
1220
11
        bool recycle_exists = false;
1221
11
        bool tmp_exists = false;
1222
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1223
11
                                                &tmp_exists) != 0) {
1224
0
            return -1;
1225
0
        }
1226
1227
11
        bool small_file_confirmed = false;
1228
11
        if (tmp_exists) {
1229
1
            left_num++;
1230
1
            left_bytes += small_file->size();
1231
1
            small_file_confirmed = true;
1232
10
        } else if (recycle_exists) {
1233
1
            left_num++;
1234
1
            left_bytes += small_file->size();
1235
            // keep small_file_confirmed=false so the packed file remains uncorrected
1236
9
        } else {
1237
9
            bool rowset_exists = false;
1238
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1239
0
                return -1;
1240
0
            }
1241
1242
9
            if (!rowset_exists) {
1243
6
                if (!small_file->deleted()) {
1244
6
                    small_file->set_deleted(true);
1245
6
                    local_changed = true;
1246
6
                }
1247
6
                if (!small_file->corrected()) {
1248
6
                    small_file->set_corrected(true);
1249
6
                    local_changed = true;
1250
6
                }
1251
6
                small_file_confirmed = true;
1252
6
            } else {
1253
3
                left_num++;
1254
3
                left_bytes += small_file->size();
1255
3
                small_file_confirmed = true;
1256
3
            }
1257
9
        }
1258
1259
11
        if (!small_file_confirmed) {
1260
1
            all_small_files_confirmed = false;
1261
1
        }
1262
1263
11
        if (small_file->corrected() != small_file_confirmed) {
1264
4
            small_file->set_corrected(small_file_confirmed);
1265
4
            local_changed = true;
1266
4
        }
1267
1268
11
        log_small_file_status(*small_file, small_file_confirmed);
1269
11
    }
1270
1271
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1272
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1273
3
        local_changed = true;
1274
3
    }
1275
3
    if (packed_info->ref_cnt() != left_num) {
1276
3
        auto old_ref_cnt = packed_info->ref_cnt();
1277
3
        packed_info->set_ref_cnt(left_num);
1278
3
        LOG_INFO("corrected packed file ref count")
1279
3
                .tag("instance_id", instance_id_)
1280
3
                .tag("resource_id", packed_info->resource_id())
1281
3
                .tag("packed_file_path", packed_file_path)
1282
3
                .tag("old_ref_cnt", old_ref_cnt)
1283
3
                .tag("new_ref_cnt", left_num);
1284
3
        local_changed = true;
1285
3
    }
1286
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1287
2
        packed_info->set_corrected(all_small_files_confirmed);
1288
2
        local_changed = true;
1289
2
    }
1290
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1291
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1292
1
        local_changed = true;
1293
1
    }
1294
1295
3
    if (changed != nullptr) {
1296
3
        *changed = local_changed;
1297
3
    }
1298
3
    return 0;
1299
3
}
1300
1301
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1302
                                                 const std::string& packed_file_path,
1303
4
                                                 PackedFileRecycleStats* stats) {
1304
4
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1305
4
    bool correction_ok = false;
1306
4
    cloud::PackedFileInfoPB packed_info;
1307
1308
4
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1309
4
        if (stopped()) {
1310
0
            LOG_WARNING("recycler stopped before processing packed file")
1311
0
                    .tag("instance_id", instance_id_)
1312
0
                    .tag("packed_file_path", packed_file_path)
1313
0
                    .tag("attempt", attempt);
1314
0
            return -1;
1315
0
        }
1316
1317
4
        std::unique_ptr<Transaction> txn;
1318
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1319
4
        if (err != TxnErrorCode::TXN_OK) {
1320
0
            LOG_WARNING("failed to create txn when processing packed file")
1321
0
                    .tag("instance_id", instance_id_)
1322
0
                    .tag("packed_file_path", packed_file_path)
1323
0
                    .tag("attempt", attempt)
1324
0
                    .tag("err", err);
1325
0
            return -1;
1326
0
        }
1327
1328
4
        std::string packed_val;
1329
4
        err = txn->get(packed_key, &packed_val);
1330
4
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1331
0
            return 0;
1332
0
        }
1333
4
        if (err != TxnErrorCode::TXN_OK) {
1334
0
            LOG_WARNING("failed to get packed file kv")
1335
0
                    .tag("instance_id", instance_id_)
1336
0
                    .tag("packed_file_path", packed_file_path)
1337
0
                    .tag("attempt", attempt)
1338
0
                    .tag("err", err);
1339
0
            return -1;
1340
0
        }
1341
1342
4
        if (!packed_info.ParseFromString(packed_val)) {
1343
0
            LOG_WARNING("failed to parse packed file info")
1344
0
                    .tag("instance_id", instance_id_)
1345
0
                    .tag("packed_file_path", packed_file_path)
1346
0
                    .tag("attempt", attempt);
1347
0
            return -1;
1348
0
        }
1349
1350
4
        int64_t now_sec = ::time(nullptr);
1351
4
        bool corrected = packed_info.corrected();
1352
4
        bool due = config::force_immediate_recycle ||
1353
4
                   now_sec - packed_info.created_at_sec() >=
1354
4
                           config::packed_file_correction_delay_seconds;
1355
1356
4
        if (!corrected && due) {
1357
3
            bool changed = false;
1358
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1359
0
                LOG_WARNING("correct_packed_file_info failed")
1360
0
                        .tag("instance_id", instance_id_)
1361
0
                        .tag("packed_file_path", packed_file_path)
1362
0
                        .tag("attempt", attempt);
1363
0
                return -1;
1364
0
            }
1365
3
            if (changed) {
1366
3
                std::string updated;
1367
3
                if (!packed_info.SerializeToString(&updated)) {
1368
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1369
0
                            .tag("instance_id", instance_id_)
1370
0
                            .tag("packed_file_path", packed_file_path)
1371
0
                            .tag("attempt", attempt);
1372
0
                    return -1;
1373
0
                }
1374
3
                txn->put(packed_key, updated);
1375
3
                err = txn->commit();
1376
3
                if (err == TxnErrorCode::TXN_OK) {
1377
3
                    if (stats) {
1378
3
                        ++stats->num_corrected;
1379
3
                    }
1380
3
                } else {
1381
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1382
0
                        LOG_WARNING(
1383
0
                                "failed to commit correction for packed file due to conflict, "
1384
0
                                "retrying")
1385
0
                                .tag("instance_id", instance_id_)
1386
0
                                .tag("packed_file_path", packed_file_path)
1387
0
                                .tag("attempt", attempt);
1388
0
                        sleep_for_packed_file_retry();
1389
0
                        packed_info.Clear();
1390
0
                        continue;
1391
0
                    }
1392
0
                    LOG_WARNING("failed to commit correction for packed file")
1393
0
                            .tag("instance_id", instance_id_)
1394
0
                            .tag("packed_file_path", packed_file_path)
1395
0
                            .tag("attempt", attempt)
1396
0
                            .tag("err", err);
1397
0
                    return -1;
1398
0
                }
1399
3
            }
1400
3
        }
1401
1402
4
        correction_ok = true;
1403
4
        break;
1404
4
    }
1405
1406
4
    if (!correction_ok) {
1407
0
        return -1;
1408
0
    }
1409
1410
4
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1411
4
          packed_info.ref_cnt() == 0)) {
1412
3
        return 0;
1413
3
    }
1414
1415
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1416
0
        LOG_WARNING("packed file missing resource id when recycling")
1417
0
                .tag("instance_id", instance_id_)
1418
0
                .tag("packed_file_path", packed_file_path);
1419
0
        return -1;
1420
0
    }
1421
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1422
1
    if (!accessor) {
1423
0
        LOG_WARNING("no accessor available to delete packed file")
1424
0
                .tag("instance_id", instance_id_)
1425
0
                .tag("packed_file_path", packed_file_path)
1426
0
                .tag("resource_id", packed_info.resource_id());
1427
0
        return -1;
1428
0
    }
1429
1
    int del_ret = accessor->delete_file(packed_file_path);
1430
1
    if (del_ret != 0 && del_ret != 1) {
1431
0
        LOG_WARNING("failed to delete packed file")
1432
0
                .tag("instance_id", instance_id_)
1433
0
                .tag("packed_file_path", packed_file_path)
1434
0
                .tag("resource_id", resource_id)
1435
0
                .tag("ret", del_ret);
1436
0
        return -1;
1437
0
    }
1438
1
    if (del_ret == 1) {
1439
0
        LOG_INFO("packed file already removed")
1440
0
                .tag("instance_id", instance_id_)
1441
0
                .tag("packed_file_path", packed_file_path)
1442
0
                .tag("resource_id", resource_id);
1443
1
    } else {
1444
1
        LOG_INFO("deleted packed file")
1445
1
                .tag("instance_id", instance_id_)
1446
1
                .tag("packed_file_path", packed_file_path)
1447
1
                .tag("resource_id", resource_id);
1448
1
    }
1449
1450
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1451
1
        std::unique_ptr<Transaction> del_txn;
1452
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1453
1
        if (err != TxnErrorCode::TXN_OK) {
1454
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1455
0
                    .tag("instance_id", instance_id_)
1456
0
                    .tag("packed_file_path", packed_file_path)
1457
0
                    .tag("del_attempt", del_attempt)
1458
0
                    .tag("err", err);
1459
0
            return -1;
1460
0
        }
1461
1462
1
        std::string latest_val;
1463
1
        err = del_txn->get(packed_key, &latest_val);
1464
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1465
0
            return 0;
1466
0
        }
1467
1
        if (err != TxnErrorCode::TXN_OK) {
1468
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1469
0
                    .tag("instance_id", instance_id_)
1470
0
                    .tag("packed_file_path", packed_file_path)
1471
0
                    .tag("del_attempt", del_attempt)
1472
0
                    .tag("err", err);
1473
0
            return -1;
1474
0
        }
1475
1476
1
        cloud::PackedFileInfoPB latest_info;
1477
1
        if (!latest_info.ParseFromString(latest_val)) {
1478
0
            LOG_WARNING("failed to parse packed file info before removal")
1479
0
                    .tag("instance_id", instance_id_)
1480
0
                    .tag("packed_file_path", packed_file_path)
1481
0
                    .tag("del_attempt", del_attempt);
1482
0
            return -1;
1483
0
        }
1484
1485
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1486
1
              latest_info.ref_cnt() == 0)) {
1487
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1488
0
                    .tag("instance_id", instance_id_)
1489
0
                    .tag("packed_file_path", packed_file_path)
1490
0
                    .tag("del_attempt", del_attempt);
1491
0
            return 0;
1492
0
        }
1493
1494
1
        del_txn->remove(packed_key);
1495
1
        err = del_txn->commit();
1496
1
        if (err == TxnErrorCode::TXN_OK) {
1497
1
            if (stats) {
1498
1
                ++stats->num_deleted;
1499
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1500
1
                                        static_cast<int64_t>(latest_val.size());
1501
1
                if (del_ret == 0 || del_ret == 1) {
1502
1
                    ++stats->num_object_deleted;
1503
1
                    int64_t object_size = latest_info.total_slice_bytes();
1504
1
                    if (object_size <= 0) {
1505
0
                        object_size = packed_info.total_slice_bytes();
1506
0
                    }
1507
1
                    stats->bytes_object_deleted += object_size;
1508
1
                }
1509
1
            }
1510
1
            LOG_INFO("removed packed file metadata")
1511
1
                    .tag("instance_id", instance_id_)
1512
1
                    .tag("packed_file_path", packed_file_path);
1513
1
            return 0;
1514
1
        }
1515
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1516
0
            if (del_attempt >= max_retry_times) {
1517
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1518
0
                        .tag("instance_id", instance_id_)
1519
0
                        .tag("packed_file_path", packed_file_path)
1520
0
                        .tag("del_attempt", del_attempt);
1521
0
                return -1;
1522
0
            }
1523
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1524
0
                    .tag("instance_id", instance_id_)
1525
0
                    .tag("packed_file_path", packed_file_path)
1526
0
                    .tag("del_attempt", del_attempt);
1527
0
            sleep_for_packed_file_retry();
1528
0
            continue;
1529
0
        }
1530
0
        LOG_WARNING("failed to remove packed file kv")
1531
0
                .tag("instance_id", instance_id_)
1532
0
                .tag("packed_file_path", packed_file_path)
1533
0
                .tag("del_attempt", del_attempt)
1534
0
                .tag("err", err);
1535
0
        return -1;
1536
0
    }
1537
1538
0
    return -1;
1539
1
}
1540
1541
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view /*value*/,
1542
4
                                            PackedFileRecycleStats* stats, int* ret) {
1543
4
    if (stats) {
1544
4
        ++stats->num_scanned;
1545
4
    }
1546
4
    std::string packed_file_path;
1547
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1548
0
        LOG_WARNING("failed to decode packed file key")
1549
0
                .tag("instance_id", instance_id_)
1550
0
                .tag("key", hex(key));
1551
0
        if (stats) {
1552
0
            ++stats->num_failed;
1553
0
        }
1554
0
        if (ret) {
1555
0
            *ret = -1;
1556
0
        }
1557
0
        return 0;
1558
0
    }
1559
1560
4
    std::string packed_key(key);
1561
4
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1562
4
    if (process_ret != 0) {
1563
0
        if (stats) {
1564
0
            ++stats->num_failed;
1565
0
        }
1566
0
        if (ret) {
1567
0
            *ret = -1;
1568
0
        }
1569
0
    }
1570
4
    return 0;
1571
4
}
1572
1573
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1574
9.77k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1575
9.77k
    if (config::force_immediate_recycle) {
1576
15
        return 0L;
1577
15
    }
1578
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1579
9.75k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1580
9.75k
    int64_t retention_seconds = config::retention_seconds;
1581
9.75k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1582
7.80k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1583
7.80k
    }
1584
9.75k
    int64_t final_expiration = expiration + retention_seconds;
1585
9.75k
    if (*earlest_ts > final_expiration) {
1586
7
        *earlest_ts = final_expiration;
1587
7
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1588
7
    }
1589
9.75k
    return final_expiration;
1590
9.77k
}
1591
1592
int64_t calculate_partition_expired_time(
1593
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1594
9
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1595
9
    if (config::force_immediate_recycle) {
1596
3
        return 0L;
1597
3
    }
1598
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1599
6
                                                            : partition_meta_pb.creation_time();
1600
6
    int64_t retention_seconds = config::retention_seconds;
1601
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1602
6
        retention_seconds =
1603
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1604
6
    }
1605
6
    int64_t final_expiration = expiration + retention_seconds;
1606
6
    if (*earlest_ts > final_expiration) {
1607
2
        *earlest_ts = final_expiration;
1608
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1609
2
    }
1610
6
    return final_expiration;
1611
9
}
1612
1613
int64_t calculate_index_expired_time(const std::string& instance_id_,
1614
                                     const RecycleIndexPB& index_meta_pb,
1615
10
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1616
10
    if (config::force_immediate_recycle) {
1617
4
        return 0L;
1618
4
    }
1619
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1620
6
                                                        : index_meta_pb.creation_time();
1621
6
    int64_t retention_seconds = config::retention_seconds;
1622
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1623
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1624
6
    }
1625
6
    int64_t final_expiration = expiration + retention_seconds;
1626
6
    if (*earlest_ts > final_expiration) {
1627
2
        *earlest_ts = final_expiration;
1628
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1629
2
    }
1630
6
    return final_expiration;
1631
10
}
1632
1633
int64_t calculate_tmp_rowset_expired_time(
1634
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1635
106k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1636
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1637
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1638
    //  duration or timeout always < `retention_time` in practice.
1639
106k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1640
106k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1641
106k
                                 : tmp_rowset_meta_pb.creation_time();
1642
106k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1643
106k
    int64_t final_expiration = expiration + config::retention_seconds;
1644
106k
    if (*earlest_ts > final_expiration) {
1645
24
        *earlest_ts = final_expiration;
1646
24
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1647
24
    }
1648
106k
    return final_expiration;
1649
106k
}
1650
1651
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1652
30.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1653
30.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1654
30.0k
    if (*earlest_ts > final_expiration / 1000) {
1655
8
        *earlest_ts = final_expiration / 1000;
1656
8
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1657
8
    }
1658
30.0k
    return final_expiration;
1659
30.0k
}
1660
1661
int64_t calculate_restore_job_expired_time(
1662
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1663
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1664
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1665
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1666
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1667
        // final state, recycle immediately
1668
41
        return 0L;
1669
41
    }
1670
    // not final state, wait much longer than the FE's timeout(1 day)
1671
0
    int64_t last_modified_s =
1672
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1673
0
    int64_t expiration = restore_job.expired_at_s() > 0
1674
0
                                 ? last_modified_s + restore_job.expired_at_s()
1675
0
                                 : last_modified_s;
1676
0
    int64_t final_expiration = expiration + config::retention_seconds;
1677
0
    if (*earlest_ts > final_expiration) {
1678
0
        *earlest_ts = final_expiration;
1679
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1680
0
    }
1681
0
    return final_expiration;
1682
41
}
1683
1684
2
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1685
2
    AbortTxnRequest req;
1686
2
    TxnInfoPB txn_info;
1687
2
    MetaServiceCode code = MetaServiceCode::OK;
1688
2
    std::string msg;
1689
2
    std::stringstream ss;
1690
2
    std::unique_ptr<Transaction> txn;
1691
2
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1692
2
    if (err != TxnErrorCode::TXN_OK) {
1693
0
        LOG_WARNING("failed to create txn").tag("err", err);
1694
0
        return -1;
1695
0
    }
1696
1697
    // get txn index
1698
2
    TxnIndexPB txn_idx_pb;
1699
2
    auto index_key = txn_index_key({instance_id_, txn_id});
1700
2
    std::string index_val;
1701
2
    err = txn->get(index_key, &index_val);
1702
2
    if (err != TxnErrorCode::TXN_OK) {
1703
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1704
            // maybe recycled
1705
0
            LOG_INFO("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1706
0
                    .tag("key", hex(index_key))
1707
0
                    .tag("txn_id", txn_id);
1708
0
            return 0;
1709
0
        }
1710
0
        LOG_WARNING("failed to get txn index")
1711
0
                .tag("err", err)
1712
0
                .tag("key", hex(index_key))
1713
0
                .tag("txn_id", txn_id);
1714
0
        return -1;
1715
0
    }
1716
2
    if (!txn_idx_pb.ParseFromString(index_val)) {
1717
0
        LOG_WARNING("failed to parse txn index")
1718
0
                .tag("err", err)
1719
0
                .tag("key", hex(index_key))
1720
0
                .tag("txn_id", txn_id);
1721
0
        return -1;
1722
0
    }
1723
1724
2
    auto info_key = txn_info_key({instance_id_, txn_idx_pb.tablet_index().db_id(), txn_id});
1725
2
    std::string info_val;
1726
2
    err = txn->get(info_key, &info_val);
1727
2
    if (err != TxnErrorCode::TXN_OK) {
1728
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1729
            // maybe recycled
1730
0
            LOG_INFO("txn info not found, txn_id={} instance_id={}", txn_id, instance_id_)
1731
0
                    .tag("key", hex(info_key))
1732
0
                    .tag("txn_id", txn_id);
1733
0
            return 0;
1734
0
        }
1735
0
        LOG_WARNING("failed to get txn info")
1736
0
                .tag("err", err)
1737
0
                .tag("key", hex(info_key))
1738
0
                .tag("txn_id", txn_id);
1739
0
        return -1;
1740
0
    }
1741
2
    if (!txn_info.ParseFromString(info_val)) {
1742
0
        LOG_WARNING("failed to parse txn info")
1743
0
                .tag("err", err)
1744
0
                .tag("key", hex(info_key))
1745
0
                .tag("txn_id", txn_id);
1746
0
        return -1;
1747
0
    }
1748
1749
2
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
1750
0
        LOG_INFO("txn is not prepared status, txn_id={} status={}", txn_id, txn_info.status())
1751
0
                .tag("key", hex(info_key))
1752
0
                .tag("txn_id", txn_id);
1753
0
        return 0;
1754
0
    }
1755
1756
2
    req.set_txn_id(txn_id);
1757
1758
2
    LOG(INFO) << "begin abort txn for related rowset, txn_id=" << txn_id
1759
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString();
1760
1761
2
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
1762
2
    err = txn->commit();
1763
2
    if (err != TxnErrorCode::TXN_OK) {
1764
0
        code = cast_as<ErrCategory::COMMIT>(err);
1765
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
1766
0
        msg = ss.str();
1767
0
        return -1;
1768
0
    }
1769
1770
2
    LOG(INFO) << "finish abort txn for related rowset, txn_id=" << txn_id
1771
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString()
1772
2
              << " code=" << code << " msg=" << msg;
1773
1774
2
    return 0;
1775
2
}
1776
1777
4
int InstanceRecycler::abort_job_for_related_rowset(const RowsetMetaCloudPB& rowset_meta) {
1778
4
    FinishTabletJobRequest req;
1779
4
    FinishTabletJobResponse res;
1780
4
    req.set_action(FinishTabletJobRequest::ABORT);
1781
4
    MetaServiceCode code = MetaServiceCode::OK;
1782
4
    std::string msg;
1783
4
    std::stringstream ss;
1784
1785
4
    TabletIndexPB tablet_idx;
1786
4
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, rowset_meta.tablet_id(), tablet_idx);
1787
4
    if (ret == 1) {
1788
        // tablet maybe recycled, directly return 0
1789
1
        return 0;
1790
3
    } else if (ret != 0) {
1791
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << rowset_meta.tablet_id()
1792
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
1793
0
        return ret;
1794
0
    }
1795
1796
3
    std::unique_ptr<Transaction> txn;
1797
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1798
3
    if (err != TxnErrorCode::TXN_OK) {
1799
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
1800
0
        return -1;
1801
0
    }
1802
1803
3
    std::string job_key =
1804
3
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
1805
3
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
1806
3
    std::string job_val;
1807
3
    err = txn->get(job_key, &job_val);
1808
3
    if (err != TxnErrorCode::TXN_OK) {
1809
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1810
0
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
1811
0
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
1812
0
            return 0;
1813
0
        }
1814
0
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
1815
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
1816
0
                     << " key=" << hex(job_key);
1817
0
        return -1;
1818
0
    }
1819
1820
3
    TabletJobInfoPB job_pb;
1821
3
    if (!job_pb.ParseFromString(job_val)) {
1822
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
1823
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
1824
0
        return -1;
1825
0
    }
1826
1827
3
    std::string job_id {};
1828
3
    if (!job_pb.compaction().empty()) {
1829
2
        for (const auto& c : job_pb.compaction()) {
1830
2
            if (c.id() == rowset_meta.job_id()) {
1831
2
                job_id = c.id();
1832
2
                break;
1833
2
            }
1834
2
        }
1835
2
    } else if (job_pb.has_schema_change()) {
1836
1
        job_id = job_pb.schema_change().id();
1837
1
    }
1838
1839
3
    if (!job_id.empty() && rowset_meta.job_id() == job_id) {
1840
3
        LOG(INFO) << "begin to abort job for related rowset, job_id=" << rowset_meta.job_id()
1841
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
1842
3
        req.mutable_job()->CopyFrom(job_pb);
1843
3
        req.set_action(FinishTabletJobRequest::ABORT);
1844
3
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
1845
3
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
1846
3
                           ss);
1847
3
        if (code != MetaServiceCode::OK) {
1848
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
1849
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
1850
0
                         << " msg=" << msg;
1851
0
            return -1;
1852
0
        }
1853
3
        LOG(INFO) << "finish abort job for related rowset, job_id=" << rowset_meta.job_id()
1854
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
1855
3
                  << " code=" << code << " msg=" << msg;
1856
3
    } else {
1857
        // clang-format off
1858
0
        LOG(INFO) << "there is no job for related rowset, directly recycle rowset data"
1859
0
                  << ", instance_id=" << instance_id_ 
1860
0
                  << ", tablet_id=" << tablet_idx.tablet_id() 
1861
0
                  << ", job_id=" << job_id
1862
0
                  << ", rowset_id=" << rowset_meta.rowset_id_v2();
1863
        // clang-format on
1864
0
    }
1865
1866
3
    return 0;
1867
3
}
1868
1869
template <typename T>
1870
55.7k
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
1871
55.7k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1872
51.9k
        return rowset_meta_pb.mutable_rowset_meta();
1873
51.9k
    } else {
1874
51.9k
        return &rowset_meta_pb;
1875
51.9k
    }
1876
55.7k
}
_ZN5doris5cloud19mutable_rowset_metaINS0_15RecycleRowsetPBEEEPNS_17RowsetMetaCloudPBERT_
Line
Count
Source
1870
3.75k
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
1871
3.75k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1872
3.75k
        return rowset_meta_pb.mutable_rowset_meta();
1873
3.75k
    } else {
1874
3.75k
        return &rowset_meta_pb;
1875
3.75k
    }
1876
3.75k
}
_ZN5doris5cloud19mutable_rowset_metaINS_17RowsetMetaCloudPBEEEPS2_RT_
Line
Count
Source
1870
51.9k
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
1871
51.9k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1872
51.9k
        return rowset_meta_pb.mutable_rowset_meta();
1873
51.9k
    } else {
1874
51.9k
        return &rowset_meta_pb;
1875
51.9k
    }
1876
51.9k
}
1877
1878
template <typename T>
1879
223k
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
1880
223k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1881
212k
        return rowset_meta_pb.rowset_meta();
1882
212k
    } else {
1883
212k
        return rowset_meta_pb;
1884
212k
    }
1885
223k
}
_ZN5doris5cloud11rowset_metaINS0_15RecycleRowsetPBEEERKNS_17RowsetMetaCloudPBERKT_
Line
Count
Source
1879
11.9k
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
1880
11.9k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1881
11.9k
        return rowset_meta_pb.rowset_meta();
1882
11.9k
    } else {
1883
11.9k
        return rowset_meta_pb;
1884
11.9k
    }
1885
11.9k
}
_ZN5doris5cloud11rowset_metaINS_17RowsetMetaCloudPBEEERKS2_RKT_
Line
Count
Source
1879
212k
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
1880
212k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1881
212k
        return rowset_meta_pb.rowset_meta();
1882
212k
    } else {
1883
212k
        return rowset_meta_pb;
1884
212k
    }
1885
212k
}
1886
1887
struct DeferredRecycleAbortTask {
1888
    enum class Type : uint8_t {
1889
        TXN,
1890
        JOB,
1891
    };
1892
1893
    Type type = Type::TXN;
1894
    int64_t txn_id = 0;
1895
    int64_t tablet_id = 0;
1896
    int64_t start_version = 0;
1897
    int64_t end_version = 0;
1898
    std::string rowset_id;
1899
    std::string job_id;
1900
};
1901
1902
struct DeferredRecyclePrepareDeleteTask {
1903
    std::string key;
1904
    std::string resource_id;
1905
    std::string rowset_id;
1906
    int64_t tablet_id = 0;
1907
};
1908
1909
template <typename T>
1910
57.7k
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
1911
57.7k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1912
3.75k
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
1913
3.10k
            return std::nullopt;
1914
3.10k
        }
1915
3.75k
    }
1916
1917
654
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1918
654
    DeferredRecycleAbortTask task;
1919
654
    task.tablet_id = rs_meta.tablet_id();
1920
654
    task.start_version = rs_meta.start_version();
1921
654
    task.end_version = rs_meta.end_version();
1922
54.6k
    if (rs_meta.has_load_id()) {
1923
4
        task.type = DeferredRecycleAbortTask::Type::TXN;
1924
4
        task.txn_id = rs_meta.txn_id();
1925
4
        return task;
1926
4
    }
1927
54.6k
    if (rs_meta.has_job_id()) {
1928
6
        task.type = DeferredRecycleAbortTask::Type::JOB;
1929
6
        task.rowset_id = rs_meta.rowset_id_v2();
1930
6
        task.job_id = rs_meta.job_id();
1931
6
        return task;
1932
6
    }
1933
54.6k
    return std::nullopt;
1934
54.6k
}
_ZN5doris5cloud24make_deferred_abort_taskINS0_15RecycleRowsetPBEEESt8optionalINS0_24DeferredRecycleAbortTaskEERKT_
Line
Count
Source
1910
3.75k
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
1911
3.75k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1912
3.75k
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
1913
3.10k
            return std::nullopt;
1914
3.10k
        }
1915
3.75k
    }
1916
1917
654
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1918
654
    DeferredRecycleAbortTask task;
1919
654
    task.tablet_id = rs_meta.tablet_id();
1920
654
    task.start_version = rs_meta.start_version();
1921
654
    task.end_version = rs_meta.end_version();
1922
654
    if (rs_meta.has_load_id()) {
1923
2
        task.type = DeferredRecycleAbortTask::Type::TXN;
1924
2
        task.txn_id = rs_meta.txn_id();
1925
2
        return task;
1926
2
    }
1927
652
    if (rs_meta.has_job_id()) {
1928
2
        task.type = DeferredRecycleAbortTask::Type::JOB;
1929
2
        task.rowset_id = rs_meta.rowset_id_v2();
1930
2
        task.job_id = rs_meta.job_id();
1931
2
        return task;
1932
2
    }
1933
650
    return std::nullopt;
1934
652
}
_ZN5doris5cloud24make_deferred_abort_taskINS_17RowsetMetaCloudPBEEESt8optionalINS0_24DeferredRecycleAbortTaskEERKT_
Line
Count
Source
1910
54.0k
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
1911
54.0k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1912
54.0k
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
1913
54.0k
            return std::nullopt;
1914
54.0k
        }
1915
54.0k
    }
1916
1917
54.0k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1918
54.0k
    DeferredRecycleAbortTask task;
1919
54.0k
    task.tablet_id = rs_meta.tablet_id();
1920
54.0k
    task.start_version = rs_meta.start_version();
1921
54.0k
    task.end_version = rs_meta.end_version();
1922
54.0k
    if (rs_meta.has_load_id()) {
1923
2
        task.type = DeferredRecycleAbortTask::Type::TXN;
1924
2
        task.txn_id = rs_meta.txn_id();
1925
2
        return task;
1926
2
    }
1927
54.0k
    if (rs_meta.has_job_id()) {
1928
4
        task.type = DeferredRecycleAbortTask::Type::JOB;
1929
4
        task.rowset_id = rs_meta.rowset_id_v2();
1930
4
        task.job_id = rs_meta.job_id();
1931
4
        return task;
1932
4
    }
1933
54.0k
    return std::nullopt;
1934
54.0k
}
1935
1936
template <typename T>
1937
169k
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
1938
169k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1939
169k
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
1940
169k
}
_ZN5doris5cloud28need_mark_rowset_as_recycledINS0_15RecycleRowsetPBEEEbRKT_
Line
Count
Source
1937
11.2k
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
1938
11.2k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1939
11.2k
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
1940
11.2k
}
_ZN5doris5cloud28need_mark_rowset_as_recycledINS_17RowsetMetaCloudPBEEEbRKT_
Line
Count
Source
1937
158k
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
1938
158k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1939
158k
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
1940
158k
}
1941
1942
template <typename T>
1943
int batch_mark_rowsets_as_recycled(TxnKv* txn_kv, const std::string& instance_id,
1944
42
                                   const std::vector<std::string>& keys) {
1945
42
    std::unique_ptr<Transaction> txn;
1946
42
    TxnErrorCode err = txn_kv->create_txn(&txn);
1947
42
    if (err != TxnErrorCode::TXN_OK) {
1948
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1949
0
        return -1;
1950
0
    }
1951
42
    std::vector<std::optional<std::string>> values;
1952
42
    err = txn->batch_get(&values, keys);
1953
42
    if (err != TxnErrorCode::TXN_OK) {
1954
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
1955
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
1956
0
        return -1;
1957
0
    }
1958
42
    size_t total_keys = keys.size();
1959
55.8k
    for (size_t i = 0; i < total_keys; i++) {
1960
55.7k
        if (!values[i].has_value()) {
1961
            // has already been removed by commit_rowset
1962
0
            continue;
1963
0
        }
1964
55.7k
        auto key = keys[i];
1965
55.7k
        auto val = values[i].value();
1966
55.7k
        T rowset_meta_pb;
1967
55.7k
        if (!rowset_meta_pb.ParseFromString(val)) {
1968
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
1969
0
                         << " key=" << hex(key);
1970
0
            return -1;
1971
0
        }
1972
55.7k
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
1973
0
            continue;
1974
0
        }
1975
55.7k
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
1976
55.7k
        val.clear();
1977
55.7k
        rowset_meta_pb.SerializeToString(&val);
1978
55.7k
        txn->put(key, val);
1979
55.7k
    }
1980
42
    err = txn->commit();
1981
42
    if (err != TxnErrorCode::TXN_OK) {
1982
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
1983
0
        return -1;
1984
0
    }
1985
1986
42
    return 0;
1987
42
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
1944
26
                                   const std::vector<std::string>& keys) {
1945
26
    std::unique_ptr<Transaction> txn;
1946
26
    TxnErrorCode err = txn_kv->create_txn(&txn);
1947
26
    if (err != TxnErrorCode::TXN_OK) {
1948
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1949
0
        return -1;
1950
0
    }
1951
26
    std::vector<std::optional<std::string>> values;
1952
26
    err = txn->batch_get(&values, keys);
1953
26
    if (err != TxnErrorCode::TXN_OK) {
1954
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
1955
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
1956
0
        return -1;
1957
0
    }
1958
26
    size_t total_keys = keys.size();
1959
3.78k
    for (size_t i = 0; i < total_keys; i++) {
1960
3.75k
        if (!values[i].has_value()) {
1961
            // has already been removed by commit_rowset
1962
0
            continue;
1963
0
        }
1964
3.75k
        auto key = keys[i];
1965
3.75k
        auto val = values[i].value();
1966
3.75k
        T rowset_meta_pb;
1967
3.75k
        if (!rowset_meta_pb.ParseFromString(val)) {
1968
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
1969
0
                         << " key=" << hex(key);
1970
0
            return -1;
1971
0
        }
1972
3.75k
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
1973
0
            continue;
1974
0
        }
1975
3.75k
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
1976
3.75k
        val.clear();
1977
3.75k
        rowset_meta_pb.SerializeToString(&val);
1978
3.75k
        txn->put(key, val);
1979
3.75k
    }
1980
26
    err = txn->commit();
1981
26
    if (err != TxnErrorCode::TXN_OK) {
1982
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
1983
0
        return -1;
1984
0
    }
1985
1986
26
    return 0;
1987
26
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
1944
16
                                   const std::vector<std::string>& keys) {
1945
16
    std::unique_ptr<Transaction> txn;
1946
16
    TxnErrorCode err = txn_kv->create_txn(&txn);
1947
16
    if (err != TxnErrorCode::TXN_OK) {
1948
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1949
0
        return -1;
1950
0
    }
1951
16
    std::vector<std::optional<std::string>> values;
1952
16
    err = txn->batch_get(&values, keys);
1953
16
    if (err != TxnErrorCode::TXN_OK) {
1954
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
1955
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
1956
0
        return -1;
1957
0
    }
1958
16
    size_t total_keys = keys.size();
1959
52.0k
    for (size_t i = 0; i < total_keys; i++) {
1960
52.0k
        if (!values[i].has_value()) {
1961
            // has already been removed by commit_rowset
1962
0
            continue;
1963
0
        }
1964
52.0k
        auto key = keys[i];
1965
52.0k
        auto val = values[i].value();
1966
52.0k
        T rowset_meta_pb;
1967
52.0k
        if (!rowset_meta_pb.ParseFromString(val)) {
1968
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
1969
0
                         << " key=" << hex(key);
1970
0
            return -1;
1971
0
        }
1972
52.0k
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
1973
0
            continue;
1974
0
        }
1975
52.0k
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
1976
52.0k
        val.clear();
1977
52.0k
        rowset_meta_pb.SerializeToString(&val);
1978
52.0k
        txn->put(key, val);
1979
52.0k
    }
1980
16
    err = txn->commit();
1981
16
    if (err != TxnErrorCode::TXN_OK) {
1982
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
1983
0
        return -1;
1984
0
    }
1985
1986
16
    return 0;
1987
16
}
1988
1989
template <typename T>
1990
int collect_deferred_abort_tasks(TxnKv* txn_kv, const std::string& instance_id,
1991
                                 const std::vector<std::string>& keys,
1992
                                 std::vector<DeferredRecycleAbortTask>* abort_tasks,
1993
5
                                 bool skip_base_version) {
1994
5
    constexpr size_t kAbortCheckBatchSize = 256;
1995
10
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
1996
5
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
1997
5
        std::unique_ptr<Transaction> txn;
1998
5
        TxnErrorCode err = txn_kv->create_txn(&txn);
1999
5
        if (err != TxnErrorCode::TXN_OK) {
2000
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2001
0
            return -1;
2002
0
        }
2003
10
        for (size_t idx = offset; idx < limit; ++idx) {
2004
5
            const std::string& key = keys[idx];
2005
5
            std::string val;
2006
5
            err = txn->get(key, &val);
2007
5
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2008
                // has already been removed
2009
0
                continue;
2010
0
            }
2011
5
            if (err != TxnErrorCode::TXN_OK) {
2012
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2013
0
                             << " key=" << hex(key);
2014
0
                return -1;
2015
0
            }
2016
5
            T rowset_meta_pb;
2017
5
            if (!rowset_meta_pb.ParseFromString(val)) {
2018
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2019
0
                             << " key=" << hex(key);
2020
0
                return -1;
2021
0
            }
2022
5
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2023
0
                continue;
2024
0
            }
2025
5
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2026
5
                abort_task.has_value()) {
2027
5
                abort_tasks->emplace_back(std::move(*abort_task));
2028
5
            }
2029
5
        }
2030
5
    }
2031
5
    return 0;
2032
5
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24DeferredRecycleAbortTaskESaISI_EEb
Line
Count
Source
1993
2
                                 bool skip_base_version) {
1994
2
    constexpr size_t kAbortCheckBatchSize = 256;
1995
4
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
1996
2
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
1997
2
        std::unique_ptr<Transaction> txn;
1998
2
        TxnErrorCode err = txn_kv->create_txn(&txn);
1999
2
        if (err != TxnErrorCode::TXN_OK) {
2000
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2001
0
            return -1;
2002
0
        }
2003
4
        for (size_t idx = offset; idx < limit; ++idx) {
2004
2
            const std::string& key = keys[idx];
2005
2
            std::string val;
2006
2
            err = txn->get(key, &val);
2007
2
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2008
                // has already been removed
2009
0
                continue;
2010
0
            }
2011
2
            if (err != TxnErrorCode::TXN_OK) {
2012
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2013
0
                             << " key=" << hex(key);
2014
0
                return -1;
2015
0
            }
2016
2
            T rowset_meta_pb;
2017
2
            if (!rowset_meta_pb.ParseFromString(val)) {
2018
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2019
0
                             << " key=" << hex(key);
2020
0
                return -1;
2021
0
            }
2022
2
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2023
0
                continue;
2024
0
            }
2025
2
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2026
2
                abort_task.has_value()) {
2027
2
                abort_tasks->emplace_back(std::move(*abort_task));
2028
2
            }
2029
2
        }
2030
2
    }
2031
2
    return 0;
2032
2
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24DeferredRecycleAbortTaskESaISI_EEb
Line
Count
Source
1993
3
                                 bool skip_base_version) {
1994
3
    constexpr size_t kAbortCheckBatchSize = 256;
1995
6
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
1996
3
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
1997
3
        std::unique_ptr<Transaction> txn;
1998
3
        TxnErrorCode err = txn_kv->create_txn(&txn);
1999
3
        if (err != TxnErrorCode::TXN_OK) {
2000
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2001
0
            return -1;
2002
0
        }
2003
6
        for (size_t idx = offset; idx < limit; ++idx) {
2004
3
            const std::string& key = keys[idx];
2005
3
            std::string val;
2006
3
            err = txn->get(key, &val);
2007
3
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2008
                // has already been removed
2009
0
                continue;
2010
0
            }
2011
3
            if (err != TxnErrorCode::TXN_OK) {
2012
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2013
0
                             << " key=" << hex(key);
2014
0
                return -1;
2015
0
            }
2016
3
            T rowset_meta_pb;
2017
3
            if (!rowset_meta_pb.ParseFromString(val)) {
2018
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2019
0
                             << " key=" << hex(key);
2020
0
                return -1;
2021
0
            }
2022
3
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2023
0
                continue;
2024
0
            }
2025
3
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2026
3
                abort_task.has_value()) {
2027
3
                abort_tasks->emplace_back(std::move(*abort_task));
2028
3
            }
2029
3
        }
2030
3
    }
2031
3
    return 0;
2032
3
}
2033
2034
template <typename T>
2035
int InstanceRecycler::batch_abort_txn_or_job_for_recycle(const std::vector<std::string>& keys,
2036
5
                                                         bool skip_base_version) {
2037
5
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2038
5
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2039
5
                                        skip_base_version) != 0) {
2040
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2041
0
        return -1;
2042
0
    }
2043
5
    for (const auto& abort_task : abort_tasks) {
2044
5
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2045
5
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2046
5
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2047
5
        int abort_ret = 0;
2048
5
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2049
2
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2050
3
        } else {
2051
3
            RowsetMetaCloudPB rowset_meta;
2052
3
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2053
3
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2054
3
            rowset_meta.set_job_id(abort_task.job_id);
2055
3
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2056
3
        }
2057
5
        if (abort_ret != 0) {
2058
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2059
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2060
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2061
0
            return abort_ret;
2062
0
        }
2063
5
    }
2064
5
    return 0;
2065
5
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEb
Line
Count
Source
2036
2
                                                         bool skip_base_version) {
2037
2
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2038
2
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2039
2
                                        skip_base_version) != 0) {
2040
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2041
0
        return -1;
2042
0
    }
2043
2
    for (const auto& abort_task : abort_tasks) {
2044
2
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2045
2
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2046
2
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2047
2
        int abort_ret = 0;
2048
2
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2049
1
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2050
1
        } else {
2051
1
            RowsetMetaCloudPB rowset_meta;
2052
1
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2053
1
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2054
1
            rowset_meta.set_job_id(abort_task.job_id);
2055
1
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2056
1
        }
2057
2
        if (abort_ret != 0) {
2058
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2059
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2060
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2061
0
            return abort_ret;
2062
0
        }
2063
2
    }
2064
2
    return 0;
2065
2
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEb
Line
Count
Source
2036
3
                                                         bool skip_base_version) {
2037
3
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2038
3
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2039
3
                                        skip_base_version) != 0) {
2040
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2041
0
        return -1;
2042
0
    }
2043
3
    for (const auto& abort_task : abort_tasks) {
2044
3
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2045
3
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2046
3
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2047
3
        int abort_ret = 0;
2048
3
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2049
1
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2050
2
        } else {
2051
2
            RowsetMetaCloudPB rowset_meta;
2052
2
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2053
2
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2054
2
            rowset_meta.set_job_id(abort_task.job_id);
2055
2
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2056
2
        }
2057
3
        if (abort_ret != 0) {
2058
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2059
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2060
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2061
0
            return abort_ret;
2062
0
        }
2063
3
    }
2064
3
    return 0;
2065
3
}
2066
2067
int collect_prepare_delete_tasks(TxnKv* txn_kv, const std::string& instance_id,
2068
                                 const std::vector<std::string>& keys,
2069
23
                                 std::vector<DeferredRecyclePrepareDeleteTask>* delete_tasks) {
2070
23
    constexpr size_t kPrepareCheckBatchSize = 256;
2071
46
    for (size_t offset = 0; offset < keys.size(); offset += kPrepareCheckBatchSize) {
2072
23
        size_t limit = std::min(keys.size(), offset + kPrepareCheckBatchSize);
2073
23
        std::unique_ptr<Transaction> txn;
2074
23
        TxnErrorCode err = txn_kv->create_txn(&txn);
2075
23
        if (err != TxnErrorCode::TXN_OK) {
2076
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2077
0
            return -1;
2078
0
        }
2079
675
        for (size_t idx = offset; idx < limit; ++idx) {
2080
652
            const std::string& key = keys[idx];
2081
652
            std::string val;
2082
652
            err = txn->get(key, &val);
2083
652
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2084
                // has already been removed
2085
0
                continue;
2086
0
            }
2087
652
            if (err != TxnErrorCode::TXN_OK) {
2088
0
                LOG(WARNING) << "failed to get recycle rowset, instance_id=" << instance_id
2089
0
                             << " key=" << hex(key);
2090
0
                return -1;
2091
0
            }
2092
652
            RecycleRowsetPB rowset;
2093
652
            if (!rowset.ParseFromString(val)) {
2094
0
                LOG(WARNING) << "failed to parse recycle rowset, instance_id=" << instance_id
2095
0
                             << " key=" << hex(key);
2096
0
                return -1;
2097
0
            }
2098
652
            if (rowset.type() != RecycleRowsetPB::PREPARE) {
2099
0
                continue;
2100
0
            }
2101
652
            const auto& rs_meta = rowset.rowset_meta();
2102
652
            delete_tasks->push_back(
2103
652
                    {key, rs_meta.resource_id(), rs_meta.rowset_id_v2(), rs_meta.tablet_id()});
2104
652
        }
2105
23
    }
2106
23
    return 0;
2107
23
}
2108
2109
1
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
2110
1
    const std::string task_name = "recycle_ref_rowsets";
2111
1
    *has_unrecycled_rowsets = false;
2112
2113
1
    std::string data_rowset_ref_count_key_start =
2114
1
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
2115
1
    std::string data_rowset_ref_count_key_end =
2116
1
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
2117
2118
1
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
2119
2120
1
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2121
1
    register_recycle_task(task_name, start_time);
2122
2123
1
    DORIS_CLOUD_DEFER {
2124
1
        unregister_recycle_task(task_name);
2125
1
        int64_t cost =
2126
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2127
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2128
1
                .tag("instance_id", instance_id_);
2129
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Line
Count
Source
2123
1
    DORIS_CLOUD_DEFER {
2124
1
        unregister_recycle_task(task_name);
2125
1
        int64_t cost =
2126
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2127
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2128
1
                .tag("instance_id", instance_id_);
2129
1
    };
2130
2131
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
2132
1
    std::set<int64_t> tablets_with_refs;
2133
1
    int64_t num_scanned = 0;
2134
2135
1
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
2136
0
        ++num_scanned;
2137
0
        int64_t tablet_id;
2138
0
        std::string rowset_id;
2139
0
        std::string_view key(k);
2140
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
2141
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
2142
0
            return 0; // Continue scanning
2143
0
        }
2144
2145
0
        tablets_with_refs.insert(tablet_id);
2146
0
        return 0;
2147
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
2148
2149
1
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
2150
1
                         std::move(scan_func)) != 0) {
2151
0
        LOG_WARNING("failed to scan data rowset ref count keys");
2152
0
        return -1;
2153
0
    }
2154
2155
1
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
2156
1
             tablets_with_refs.size(), num_scanned)
2157
1
            .tag("instance_id", instance_id_);
2158
2159
    // Phase 2: Recycle each tablet
2160
1
    int64_t num_recycled_tablets = 0;
2161
1
    for (int64_t tablet_id : tablets_with_refs) {
2162
0
        if (stopped()) {
2163
0
            LOG_INFO("recycler stopped, skip remaining tablets")
2164
0
                    .tag("instance_id", instance_id_)
2165
0
                    .tag("tablets_processed", num_recycled_tablets)
2166
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
2167
0
            break;
2168
0
        }
2169
2170
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
2171
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
2172
0
            LOG_WARNING("failed to recycle tablet")
2173
0
                    .tag("instance_id", instance_id_)
2174
0
                    .tag("tablet_id", tablet_id);
2175
0
            return -1;
2176
0
        }
2177
0
        ++num_recycled_tablets;
2178
0
    }
2179
2180
1
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
2181
1
            .tag("instance_id", instance_id_)
2182
1
            .tag("total_tablets", tablets_with_refs.size());
2183
2184
    // Phase 3: Scan again to check if any ref count keys still exist
2185
1
    std::unique_ptr<Transaction> txn;
2186
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2187
1
    if (err != TxnErrorCode::TXN_OK) {
2188
0
        LOG_WARNING("failed to create txn for final check")
2189
0
                .tag("instance_id", instance_id_)
2190
0
                .tag("err", err);
2191
0
        return -1;
2192
0
    }
2193
2194
1
    std::unique_ptr<RangeGetIterator> iter;
2195
1
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2196
1
    if (err != TxnErrorCode::TXN_OK) {
2197
0
        LOG_WARNING("failed to create range iterator for final check")
2198
0
                .tag("instance_id", instance_id_)
2199
0
                .tag("err", err);
2200
0
        return -1;
2201
0
    }
2202
2203
1
    *has_unrecycled_rowsets = iter->has_next();
2204
1
    if (*has_unrecycled_rowsets) {
2205
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2206
0
                .tag("instance_id", instance_id_);
2207
0
    }
2208
2209
1
    return 0;
2210
1
}
2211
2212
17
int InstanceRecycler::recycle_indexes() {
2213
17
    const std::string task_name = "recycle_indexes";
2214
17
    int64_t num_scanned = 0;
2215
17
    int64_t num_expired = 0;
2216
17
    int64_t num_recycled = 0;
2217
17
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2218
2219
17
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2220
17
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2221
17
    std::string index_key0;
2222
17
    std::string index_key1;
2223
17
    recycle_index_key(index_key_info0, &index_key0);
2224
17
    recycle_index_key(index_key_info1, &index_key1);
2225
2226
17
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2227
2228
17
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2229
17
    register_recycle_task(task_name, start_time);
2230
2231
17
    DORIS_CLOUD_DEFER {
2232
17
        unregister_recycle_task(task_name);
2233
17
        int64_t cost =
2234
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2235
17
        metrics_context.finish_report();
2236
17
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2237
17
                .tag("instance_id", instance_id_)
2238
17
                .tag("num_scanned", num_scanned)
2239
17
                .tag("num_expired", num_expired)
2240
17
                .tag("num_recycled", num_recycled);
2241
17
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2231
2
    DORIS_CLOUD_DEFER {
2232
2
        unregister_recycle_task(task_name);
2233
2
        int64_t cost =
2234
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2235
2
        metrics_context.finish_report();
2236
2
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2237
2
                .tag("instance_id", instance_id_)
2238
2
                .tag("num_scanned", num_scanned)
2239
2
                .tag("num_expired", num_expired)
2240
2
                .tag("num_recycled", num_recycled);
2241
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2231
15
    DORIS_CLOUD_DEFER {
2232
15
        unregister_recycle_task(task_name);
2233
15
        int64_t cost =
2234
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2235
15
        metrics_context.finish_report();
2236
15
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2237
15
                .tag("instance_id", instance_id_)
2238
15
                .tag("num_scanned", num_scanned)
2239
15
                .tag("num_expired", num_expired)
2240
15
                .tag("num_recycled", num_recycled);
2241
15
    };
2242
2243
17
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2244
2245
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2246
17
    std::vector<std::string_view> index_keys;
2247
17
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2248
10
        ++num_scanned;
2249
10
        RecycleIndexPB index_pb;
2250
10
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2251
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2252
0
            return -1;
2253
0
        }
2254
10
        int64_t current_time = ::time(nullptr);
2255
10
        if (current_time <
2256
10
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2257
0
            return 0;
2258
0
        }
2259
10
        ++num_expired;
2260
        // decode index_id
2261
10
        auto k1 = k;
2262
10
        k1.remove_prefix(1);
2263
10
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2264
10
        decode_key(&k1, &out);
2265
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2266
10
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2267
10
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2268
10
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2269
10
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2270
        // Change state to RECYCLING
2271
10
        std::unique_ptr<Transaction> txn;
2272
10
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2273
10
        if (err != TxnErrorCode::TXN_OK) {
2274
0
            LOG_WARNING("failed to create txn").tag("err", err);
2275
0
            return -1;
2276
0
        }
2277
10
        std::string val;
2278
10
        err = txn->get(k, &val);
2279
10
        if (err ==
2280
10
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2281
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2282
0
            return 0;
2283
0
        }
2284
10
        if (err != TxnErrorCode::TXN_OK) {
2285
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2286
0
            return -1;
2287
0
        }
2288
10
        index_pb.Clear();
2289
10
        if (!index_pb.ParseFromString(val)) {
2290
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2291
0
            return -1;
2292
0
        }
2293
10
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2294
9
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2295
9
            txn->put(k, index_pb.SerializeAsString());
2296
9
            err = txn->commit();
2297
9
            if (err != TxnErrorCode::TXN_OK) {
2298
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2299
0
                return -1;
2300
0
            }
2301
9
        }
2302
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2303
1
            LOG_WARNING("failed to recycle tablets under index")
2304
1
                    .tag("table_id", index_pb.table_id())
2305
1
                    .tag("instance_id", instance_id_)
2306
1
                    .tag("index_id", index_id);
2307
1
            return -1;
2308
1
        }
2309
2310
9
        if (index_pb.has_db_id()) {
2311
            // Recycle the versioned keys
2312
3
            std::unique_ptr<Transaction> txn;
2313
3
            err = txn_kv_->create_txn(&txn);
2314
3
            if (err != TxnErrorCode::TXN_OK) {
2315
0
                LOG_WARNING("failed to create txn").tag("err", err);
2316
0
                return -1;
2317
0
            }
2318
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2319
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2320
3
            std::string index_inverted_key = versioned::index_inverted_key(
2321
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2322
3
            versioned_remove_all(txn.get(), meta_key);
2323
3
            txn->remove(index_key);
2324
3
            txn->remove(index_inverted_key);
2325
3
            err = txn->commit();
2326
3
            if (err != TxnErrorCode::TXN_OK) {
2327
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2328
0
                return -1;
2329
0
            }
2330
3
        }
2331
2332
9
        metrics_context.total_recycled_num = ++num_recycled;
2333
9
        metrics_context.report();
2334
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2335
9
        index_keys.push_back(k);
2336
9
        return 0;
2337
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2247
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2248
2
        ++num_scanned;
2249
2
        RecycleIndexPB index_pb;
2250
2
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2251
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2252
0
            return -1;
2253
0
        }
2254
2
        int64_t current_time = ::time(nullptr);
2255
2
        if (current_time <
2256
2
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2257
0
            return 0;
2258
0
        }
2259
2
        ++num_expired;
2260
        // decode index_id
2261
2
        auto k1 = k;
2262
2
        k1.remove_prefix(1);
2263
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2264
2
        decode_key(&k1, &out);
2265
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2266
2
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2267
2
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2268
2
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2269
2
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2270
        // Change state to RECYCLING
2271
2
        std::unique_ptr<Transaction> txn;
2272
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2273
2
        if (err != TxnErrorCode::TXN_OK) {
2274
0
            LOG_WARNING("failed to create txn").tag("err", err);
2275
0
            return -1;
2276
0
        }
2277
2
        std::string val;
2278
2
        err = txn->get(k, &val);
2279
2
        if (err ==
2280
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2281
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2282
0
            return 0;
2283
0
        }
2284
2
        if (err != TxnErrorCode::TXN_OK) {
2285
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2286
0
            return -1;
2287
0
        }
2288
2
        index_pb.Clear();
2289
2
        if (!index_pb.ParseFromString(val)) {
2290
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2291
0
            return -1;
2292
0
        }
2293
2
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2294
1
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2295
1
            txn->put(k, index_pb.SerializeAsString());
2296
1
            err = txn->commit();
2297
1
            if (err != TxnErrorCode::TXN_OK) {
2298
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2299
0
                return -1;
2300
0
            }
2301
1
        }
2302
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2303
1
            LOG_WARNING("failed to recycle tablets under index")
2304
1
                    .tag("table_id", index_pb.table_id())
2305
1
                    .tag("instance_id", instance_id_)
2306
1
                    .tag("index_id", index_id);
2307
1
            return -1;
2308
1
        }
2309
2310
1
        if (index_pb.has_db_id()) {
2311
            // Recycle the versioned keys
2312
1
            std::unique_ptr<Transaction> txn;
2313
1
            err = txn_kv_->create_txn(&txn);
2314
1
            if (err != TxnErrorCode::TXN_OK) {
2315
0
                LOG_WARNING("failed to create txn").tag("err", err);
2316
0
                return -1;
2317
0
            }
2318
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2319
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2320
1
            std::string index_inverted_key = versioned::index_inverted_key(
2321
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2322
1
            versioned_remove_all(txn.get(), meta_key);
2323
1
            txn->remove(index_key);
2324
1
            txn->remove(index_inverted_key);
2325
1
            err = txn->commit();
2326
1
            if (err != TxnErrorCode::TXN_OK) {
2327
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2328
0
                return -1;
2329
0
            }
2330
1
        }
2331
2332
1
        metrics_context.total_recycled_num = ++num_recycled;
2333
1
        metrics_context.report();
2334
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2335
1
        index_keys.push_back(k);
2336
1
        return 0;
2337
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2247
8
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2248
8
        ++num_scanned;
2249
8
        RecycleIndexPB index_pb;
2250
8
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2251
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2252
0
            return -1;
2253
0
        }
2254
8
        int64_t current_time = ::time(nullptr);
2255
8
        if (current_time <
2256
8
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2257
0
            return 0;
2258
0
        }
2259
8
        ++num_expired;
2260
        // decode index_id
2261
8
        auto k1 = k;
2262
8
        k1.remove_prefix(1);
2263
8
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2264
8
        decode_key(&k1, &out);
2265
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2266
8
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2267
8
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2268
8
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2269
8
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2270
        // Change state to RECYCLING
2271
8
        std::unique_ptr<Transaction> txn;
2272
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2273
8
        if (err != TxnErrorCode::TXN_OK) {
2274
0
            LOG_WARNING("failed to create txn").tag("err", err);
2275
0
            return -1;
2276
0
        }
2277
8
        std::string val;
2278
8
        err = txn->get(k, &val);
2279
8
        if (err ==
2280
8
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2281
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2282
0
            return 0;
2283
0
        }
2284
8
        if (err != TxnErrorCode::TXN_OK) {
2285
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2286
0
            return -1;
2287
0
        }
2288
8
        index_pb.Clear();
2289
8
        if (!index_pb.ParseFromString(val)) {
2290
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2291
0
            return -1;
2292
0
        }
2293
8
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2294
8
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2295
8
            txn->put(k, index_pb.SerializeAsString());
2296
8
            err = txn->commit();
2297
8
            if (err != TxnErrorCode::TXN_OK) {
2298
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2299
0
                return -1;
2300
0
            }
2301
8
        }
2302
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2303
0
            LOG_WARNING("failed to recycle tablets under index")
2304
0
                    .tag("table_id", index_pb.table_id())
2305
0
                    .tag("instance_id", instance_id_)
2306
0
                    .tag("index_id", index_id);
2307
0
            return -1;
2308
0
        }
2309
2310
8
        if (index_pb.has_db_id()) {
2311
            // Recycle the versioned keys
2312
2
            std::unique_ptr<Transaction> txn;
2313
2
            err = txn_kv_->create_txn(&txn);
2314
2
            if (err != TxnErrorCode::TXN_OK) {
2315
0
                LOG_WARNING("failed to create txn").tag("err", err);
2316
0
                return -1;
2317
0
            }
2318
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2319
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2320
2
            std::string index_inverted_key = versioned::index_inverted_key(
2321
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2322
2
            versioned_remove_all(txn.get(), meta_key);
2323
2
            txn->remove(index_key);
2324
2
            txn->remove(index_inverted_key);
2325
2
            err = txn->commit();
2326
2
            if (err != TxnErrorCode::TXN_OK) {
2327
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2328
0
                return -1;
2329
0
            }
2330
2
        }
2331
2332
8
        metrics_context.total_recycled_num = ++num_recycled;
2333
8
        metrics_context.report();
2334
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2335
8
        index_keys.push_back(k);
2336
8
        return 0;
2337
8
    };
2338
2339
17
    auto loop_done = [&index_keys, this]() -> int {
2340
6
        if (index_keys.empty()) return 0;
2341
5
        DORIS_CLOUD_DEFER {
2342
5
            index_keys.clear();
2343
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2341
1
        DORIS_CLOUD_DEFER {
2342
1
            index_keys.clear();
2343
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2341
4
        DORIS_CLOUD_DEFER {
2342
4
            index_keys.clear();
2343
4
        };
2344
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2345
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2346
0
            return -1;
2347
0
        }
2348
5
        return 0;
2349
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2339
2
    auto loop_done = [&index_keys, this]() -> int {
2340
2
        if (index_keys.empty()) return 0;
2341
1
        DORIS_CLOUD_DEFER {
2342
1
            index_keys.clear();
2343
1
        };
2344
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2345
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2346
0
            return -1;
2347
0
        }
2348
1
        return 0;
2349
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2339
4
    auto loop_done = [&index_keys, this]() -> int {
2340
4
        if (index_keys.empty()) return 0;
2341
4
        DORIS_CLOUD_DEFER {
2342
4
            index_keys.clear();
2343
4
        };
2344
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2345
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2346
0
            return -1;
2347
0
        }
2348
4
        return 0;
2349
4
    };
2350
2351
17
    if (config::enable_recycler_stats_metrics) {
2352
0
        scan_and_statistics_indexes();
2353
0
    }
2354
    // recycle_func and loop_done for scan and recycle
2355
17
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
2356
17
}
2357
2358
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
2359
8.24k
                             int64_t tablet_id) {
2360
8.24k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
2361
2362
8.24k
    std::unique_ptr<Transaction> txn;
2363
8.24k
    TxnErrorCode err = txn_kv->create_txn(&txn);
2364
8.24k
    if (err != TxnErrorCode::TXN_OK) {
2365
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
2366
0
                     << " tablet_id=" << tablet_id << " err=" << err;
2367
0
        return false;
2368
0
    }
2369
2370
8.24k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
2371
8.24k
    std::string tablet_idx_val;
2372
8.24k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
2373
8.24k
    if (TxnErrorCode::TXN_OK != err) {
2374
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
2375
0
                     << " tablet_id=" << tablet_id << " err=" << err
2376
0
                     << " key=" << hex(tablet_idx_key);
2377
0
        return false;
2378
0
    }
2379
2380
8.24k
    TabletIndexPB tablet_idx_pb;
2381
8.24k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
2382
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
2383
0
                     << " tablet_id=" << tablet_id;
2384
0
        return false;
2385
0
    }
2386
2387
8.24k
    if (!tablet_idx_pb.has_db_id()) {
2388
        // In the previous version, the db_id was not set in the index_pb.
2389
        // If updating to the version which enable txn lazy commit, the db_id will be set.
2390
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
2391
0
                  << " instance_id=" << instance_id
2392
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
2393
0
        return true;
2394
0
    }
2395
2396
8.24k
    std::string ver_val;
2397
8.24k
    std::string ver_key =
2398
8.24k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
2399
8.24k
                                   tablet_idx_pb.partition_id()});
2400
8.24k
    err = txn->get(ver_key, &ver_val);
2401
2402
8.24k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
2403
204
        LOG(INFO) << ""
2404
204
                     "partition version not found, instance_id="
2405
204
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
2406
204
                  << " table_id=" << tablet_idx_pb.table_id()
2407
204
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
2408
204
                  << " key=" << hex(ver_key);
2409
204
        return true;
2410
204
    }
2411
2412
8.03k
    if (TxnErrorCode::TXN_OK != err) {
2413
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
2414
0
                     << " db_id=" << tablet_idx_pb.db_id()
2415
0
                     << " table_id=" << tablet_idx_pb.table_id()
2416
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2417
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
2418
0
        return false;
2419
0
    }
2420
2421
8.03k
    VersionPB version_pb;
2422
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
2423
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
2424
0
                     << " db_id=" << tablet_idx_pb.db_id()
2425
0
                     << " table_id=" << tablet_idx_pb.table_id()
2426
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2427
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
2428
0
        return false;
2429
0
    }
2430
2431
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
2432
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
2433
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
2434
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
2435
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
2436
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
2437
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
2438
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
2439
4.00k
                     << " key=" << hex(ver_key);
2440
4.00k
        return false;
2441
4.00k
    }
2442
4.03k
    return true;
2443
8.03k
}
2444
2445
15
int InstanceRecycler::recycle_partitions() {
2446
15
    const std::string task_name = "recycle_partitions";
2447
15
    int64_t num_scanned = 0;
2448
15
    int64_t num_expired = 0;
2449
15
    int64_t num_recycled = 0;
2450
15
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2451
2452
15
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
2453
15
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
2454
15
    std::string part_key0;
2455
15
    std::string part_key1;
2456
15
    recycle_partition_key(part_key_info0, &part_key0);
2457
15
    recycle_partition_key(part_key_info1, &part_key1);
2458
2459
15
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
2460
2461
15
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2462
15
    register_recycle_task(task_name, start_time);
2463
2464
15
    DORIS_CLOUD_DEFER {
2465
15
        unregister_recycle_task(task_name);
2466
15
        int64_t cost =
2467
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2468
15
        metrics_context.finish_report();
2469
15
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2470
15
                .tag("instance_id", instance_id_)
2471
15
                .tag("num_scanned", num_scanned)
2472
15
                .tag("num_expired", num_expired)
2473
15
                .tag("num_recycled", num_recycled);
2474
15
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2464
2
    DORIS_CLOUD_DEFER {
2465
2
        unregister_recycle_task(task_name);
2466
2
        int64_t cost =
2467
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2468
2
        metrics_context.finish_report();
2469
2
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2470
2
                .tag("instance_id", instance_id_)
2471
2
                .tag("num_scanned", num_scanned)
2472
2
                .tag("num_expired", num_expired)
2473
2
                .tag("num_recycled", num_recycled);
2474
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2464
13
    DORIS_CLOUD_DEFER {
2465
13
        unregister_recycle_task(task_name);
2466
13
        int64_t cost =
2467
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2468
13
        metrics_context.finish_report();
2469
13
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2470
13
                .tag("instance_id", instance_id_)
2471
13
                .tag("num_scanned", num_scanned)
2472
13
                .tag("num_expired", num_expired)
2473
13
                .tag("num_recycled", num_recycled);
2474
13
    };
2475
2476
15
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2477
2478
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
2479
15
    std::vector<std::string_view> partition_keys;
2480
15
    std::vector<std::string> partition_version_keys;
2481
15
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2482
9
        ++num_scanned;
2483
9
        RecyclePartitionPB part_pb;
2484
9
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2485
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2486
0
            return -1;
2487
0
        }
2488
9
        int64_t current_time = ::time(nullptr);
2489
9
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2490
9
                                                            &earlest_ts)) { // not expired
2491
0
            return 0;
2492
0
        }
2493
9
        ++num_expired;
2494
        // decode partition_id
2495
9
        auto k1 = k;
2496
9
        k1.remove_prefix(1);
2497
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2498
9
        decode_key(&k1, &out);
2499
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2500
9
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2501
9
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2502
9
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2503
9
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2504
        // Change state to RECYCLING
2505
9
        std::unique_ptr<Transaction> txn;
2506
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2507
9
        if (err != TxnErrorCode::TXN_OK) {
2508
0
            LOG_WARNING("failed to create txn").tag("err", err);
2509
0
            return -1;
2510
0
        }
2511
9
        std::string val;
2512
9
        err = txn->get(k, &val);
2513
9
        if (err ==
2514
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2515
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2516
0
            return 0;
2517
0
        }
2518
9
        if (err != TxnErrorCode::TXN_OK) {
2519
0
            LOG_WARNING("failed to get kv");
2520
0
            return -1;
2521
0
        }
2522
9
        part_pb.Clear();
2523
9
        if (!part_pb.ParseFromString(val)) {
2524
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2525
0
            return -1;
2526
0
        }
2527
        // Partitions with PREPARED state MUST have no data
2528
9
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2529
8
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2530
8
            txn->put(k, part_pb.SerializeAsString());
2531
8
            err = txn->commit();
2532
8
            if (err != TxnErrorCode::TXN_OK) {
2533
0
                LOG_WARNING("failed to commit txn: {}", err);
2534
0
                return -1;
2535
0
            }
2536
8
        }
2537
2538
9
        int ret = 0;
2539
33
        for (int64_t index_id : part_pb.index_id()) {
2540
33
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2541
1
                LOG_WARNING("failed to recycle tablets under partition")
2542
1
                        .tag("table_id", part_pb.table_id())
2543
1
                        .tag("instance_id", instance_id_)
2544
1
                        .tag("index_id", index_id)
2545
1
                        .tag("partition_id", partition_id);
2546
1
                ret = -1;
2547
1
            }
2548
33
        }
2549
9
        if (ret == 0 && part_pb.has_db_id()) {
2550
            // Recycle the versioned keys
2551
8
            std::unique_ptr<Transaction> txn;
2552
8
            err = txn_kv_->create_txn(&txn);
2553
8
            if (err != TxnErrorCode::TXN_OK) {
2554
0
                LOG_WARNING("failed to create txn").tag("err", err);
2555
0
                return -1;
2556
0
            }
2557
8
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2558
8
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2559
8
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2560
8
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2561
8
            std::string partition_version_key =
2562
8
                    versioned::partition_version_key({instance_id_, partition_id});
2563
8
            versioned_remove_all(txn.get(), meta_key);
2564
8
            txn->remove(index_key);
2565
8
            txn->remove(inverted_index_key);
2566
8
            versioned_remove_all(txn.get(), partition_version_key);
2567
8
            err = txn->commit();
2568
8
            if (err != TxnErrorCode::TXN_OK) {
2569
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2570
0
                return -1;
2571
0
            }
2572
8
        }
2573
2574
9
        if (ret == 0) {
2575
8
            ++num_recycled;
2576
8
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2577
8
            partition_keys.push_back(k);
2578
8
            if (part_pb.db_id() > 0) {
2579
8
                partition_version_keys.push_back(partition_version_key(
2580
8
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2581
8
            }
2582
8
            metrics_context.total_recycled_num = num_recycled;
2583
8
            metrics_context.report();
2584
8
        }
2585
9
        return ret;
2586
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2481
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2482
2
        ++num_scanned;
2483
2
        RecyclePartitionPB part_pb;
2484
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2485
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2486
0
            return -1;
2487
0
        }
2488
2
        int64_t current_time = ::time(nullptr);
2489
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2490
2
                                                            &earlest_ts)) { // not expired
2491
0
            return 0;
2492
0
        }
2493
2
        ++num_expired;
2494
        // decode partition_id
2495
2
        auto k1 = k;
2496
2
        k1.remove_prefix(1);
2497
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2498
2
        decode_key(&k1, &out);
2499
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2500
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2501
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2502
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2503
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2504
        // Change state to RECYCLING
2505
2
        std::unique_ptr<Transaction> txn;
2506
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2507
2
        if (err != TxnErrorCode::TXN_OK) {
2508
0
            LOG_WARNING("failed to create txn").tag("err", err);
2509
0
            return -1;
2510
0
        }
2511
2
        std::string val;
2512
2
        err = txn->get(k, &val);
2513
2
        if (err ==
2514
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2515
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2516
0
            return 0;
2517
0
        }
2518
2
        if (err != TxnErrorCode::TXN_OK) {
2519
0
            LOG_WARNING("failed to get kv");
2520
0
            return -1;
2521
0
        }
2522
2
        part_pb.Clear();
2523
2
        if (!part_pb.ParseFromString(val)) {
2524
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2525
0
            return -1;
2526
0
        }
2527
        // Partitions with PREPARED state MUST have no data
2528
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2529
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2530
1
            txn->put(k, part_pb.SerializeAsString());
2531
1
            err = txn->commit();
2532
1
            if (err != TxnErrorCode::TXN_OK) {
2533
0
                LOG_WARNING("failed to commit txn: {}", err);
2534
0
                return -1;
2535
0
            }
2536
1
        }
2537
2538
2
        int ret = 0;
2539
2
        for (int64_t index_id : part_pb.index_id()) {
2540
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2541
1
                LOG_WARNING("failed to recycle tablets under partition")
2542
1
                        .tag("table_id", part_pb.table_id())
2543
1
                        .tag("instance_id", instance_id_)
2544
1
                        .tag("index_id", index_id)
2545
1
                        .tag("partition_id", partition_id);
2546
1
                ret = -1;
2547
1
            }
2548
2
        }
2549
2
        if (ret == 0 && part_pb.has_db_id()) {
2550
            // Recycle the versioned keys
2551
1
            std::unique_ptr<Transaction> txn;
2552
1
            err = txn_kv_->create_txn(&txn);
2553
1
            if (err != TxnErrorCode::TXN_OK) {
2554
0
                LOG_WARNING("failed to create txn").tag("err", err);
2555
0
                return -1;
2556
0
            }
2557
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2558
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2559
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2560
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2561
1
            std::string partition_version_key =
2562
1
                    versioned::partition_version_key({instance_id_, partition_id});
2563
1
            versioned_remove_all(txn.get(), meta_key);
2564
1
            txn->remove(index_key);
2565
1
            txn->remove(inverted_index_key);
2566
1
            versioned_remove_all(txn.get(), partition_version_key);
2567
1
            err = txn->commit();
2568
1
            if (err != TxnErrorCode::TXN_OK) {
2569
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2570
0
                return -1;
2571
0
            }
2572
1
        }
2573
2574
2
        if (ret == 0) {
2575
1
            ++num_recycled;
2576
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2577
1
            partition_keys.push_back(k);
2578
1
            if (part_pb.db_id() > 0) {
2579
1
                partition_version_keys.push_back(partition_version_key(
2580
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2581
1
            }
2582
1
            metrics_context.total_recycled_num = num_recycled;
2583
1
            metrics_context.report();
2584
1
        }
2585
2
        return ret;
2586
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2481
7
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2482
7
        ++num_scanned;
2483
7
        RecyclePartitionPB part_pb;
2484
7
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2485
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2486
0
            return -1;
2487
0
        }
2488
7
        int64_t current_time = ::time(nullptr);
2489
7
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2490
7
                                                            &earlest_ts)) { // not expired
2491
0
            return 0;
2492
0
        }
2493
7
        ++num_expired;
2494
        // decode partition_id
2495
7
        auto k1 = k;
2496
7
        k1.remove_prefix(1);
2497
7
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2498
7
        decode_key(&k1, &out);
2499
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2500
7
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2501
7
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2502
7
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2503
7
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2504
        // Change state to RECYCLING
2505
7
        std::unique_ptr<Transaction> txn;
2506
7
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2507
7
        if (err != TxnErrorCode::TXN_OK) {
2508
0
            LOG_WARNING("failed to create txn").tag("err", err);
2509
0
            return -1;
2510
0
        }
2511
7
        std::string val;
2512
7
        err = txn->get(k, &val);
2513
7
        if (err ==
2514
7
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2515
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2516
0
            return 0;
2517
0
        }
2518
7
        if (err != TxnErrorCode::TXN_OK) {
2519
0
            LOG_WARNING("failed to get kv");
2520
0
            return -1;
2521
0
        }
2522
7
        part_pb.Clear();
2523
7
        if (!part_pb.ParseFromString(val)) {
2524
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2525
0
            return -1;
2526
0
        }
2527
        // Partitions with PREPARED state MUST have no data
2528
7
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2529
7
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2530
7
            txn->put(k, part_pb.SerializeAsString());
2531
7
            err = txn->commit();
2532
7
            if (err != TxnErrorCode::TXN_OK) {
2533
0
                LOG_WARNING("failed to commit txn: {}", err);
2534
0
                return -1;
2535
0
            }
2536
7
        }
2537
2538
7
        int ret = 0;
2539
31
        for (int64_t index_id : part_pb.index_id()) {
2540
31
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2541
0
                LOG_WARNING("failed to recycle tablets under partition")
2542
0
                        .tag("table_id", part_pb.table_id())
2543
0
                        .tag("instance_id", instance_id_)
2544
0
                        .tag("index_id", index_id)
2545
0
                        .tag("partition_id", partition_id);
2546
0
                ret = -1;
2547
0
            }
2548
31
        }
2549
7
        if (ret == 0 && part_pb.has_db_id()) {
2550
            // Recycle the versioned keys
2551
7
            std::unique_ptr<Transaction> txn;
2552
7
            err = txn_kv_->create_txn(&txn);
2553
7
            if (err != TxnErrorCode::TXN_OK) {
2554
0
                LOG_WARNING("failed to create txn").tag("err", err);
2555
0
                return -1;
2556
0
            }
2557
7
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2558
7
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2559
7
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2560
7
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2561
7
            std::string partition_version_key =
2562
7
                    versioned::partition_version_key({instance_id_, partition_id});
2563
7
            versioned_remove_all(txn.get(), meta_key);
2564
7
            txn->remove(index_key);
2565
7
            txn->remove(inverted_index_key);
2566
7
            versioned_remove_all(txn.get(), partition_version_key);
2567
7
            err = txn->commit();
2568
7
            if (err != TxnErrorCode::TXN_OK) {
2569
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2570
0
                return -1;
2571
0
            }
2572
7
        }
2573
2574
7
        if (ret == 0) {
2575
7
            ++num_recycled;
2576
7
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2577
7
            partition_keys.push_back(k);
2578
7
            if (part_pb.db_id() > 0) {
2579
7
                partition_version_keys.push_back(partition_version_key(
2580
7
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2581
7
            }
2582
7
            metrics_context.total_recycled_num = num_recycled;
2583
7
            metrics_context.report();
2584
7
        }
2585
7
        return ret;
2586
7
    };
2587
2588
15
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2589
5
        if (partition_keys.empty()) return 0;
2590
4
        DORIS_CLOUD_DEFER {
2591
4
            partition_keys.clear();
2592
4
            partition_version_keys.clear();
2593
4
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2590
1
        DORIS_CLOUD_DEFER {
2591
1
            partition_keys.clear();
2592
1
            partition_version_keys.clear();
2593
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2590
3
        DORIS_CLOUD_DEFER {
2591
3
            partition_keys.clear();
2592
3
            partition_version_keys.clear();
2593
3
        };
2594
4
        std::unique_ptr<Transaction> txn;
2595
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2596
4
        if (err != TxnErrorCode::TXN_OK) {
2597
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2598
0
            return -1;
2599
0
        }
2600
8
        for (auto& k : partition_keys) {
2601
8
            txn->remove(k);
2602
8
        }
2603
8
        for (auto& k : partition_version_keys) {
2604
8
            txn->remove(k);
2605
8
        }
2606
4
        err = txn->commit();
2607
4
        if (err != TxnErrorCode::TXN_OK) {
2608
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2609
0
                         << " err=" << err;
2610
0
            return -1;
2611
0
        }
2612
4
        return 0;
2613
4
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2588
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2589
2
        if (partition_keys.empty()) return 0;
2590
1
        DORIS_CLOUD_DEFER {
2591
1
            partition_keys.clear();
2592
1
            partition_version_keys.clear();
2593
1
        };
2594
1
        std::unique_ptr<Transaction> txn;
2595
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2596
1
        if (err != TxnErrorCode::TXN_OK) {
2597
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2598
0
            return -1;
2599
0
        }
2600
1
        for (auto& k : partition_keys) {
2601
1
            txn->remove(k);
2602
1
        }
2603
1
        for (auto& k : partition_version_keys) {
2604
1
            txn->remove(k);
2605
1
        }
2606
1
        err = txn->commit();
2607
1
        if (err != TxnErrorCode::TXN_OK) {
2608
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2609
0
                         << " err=" << err;
2610
0
            return -1;
2611
0
        }
2612
1
        return 0;
2613
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2588
3
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2589
3
        if (partition_keys.empty()) return 0;
2590
3
        DORIS_CLOUD_DEFER {
2591
3
            partition_keys.clear();
2592
3
            partition_version_keys.clear();
2593
3
        };
2594
3
        std::unique_ptr<Transaction> txn;
2595
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2596
3
        if (err != TxnErrorCode::TXN_OK) {
2597
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2598
0
            return -1;
2599
0
        }
2600
7
        for (auto& k : partition_keys) {
2601
7
            txn->remove(k);
2602
7
        }
2603
7
        for (auto& k : partition_version_keys) {
2604
7
            txn->remove(k);
2605
7
        }
2606
3
        err = txn->commit();
2607
3
        if (err != TxnErrorCode::TXN_OK) {
2608
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2609
0
                         << " err=" << err;
2610
0
            return -1;
2611
0
        }
2612
3
        return 0;
2613
3
    };
2614
2615
15
    if (config::enable_recycler_stats_metrics) {
2616
0
        scan_and_statistics_partitions();
2617
0
    }
2618
    // recycle_func and loop_done for scan and recycle
2619
15
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
2620
15
}
2621
2622
14
int InstanceRecycler::recycle_versions() {
2623
14
    if (should_recycle_versioned_keys()) {
2624
2
        return recycle_orphan_partitions();
2625
2
    }
2626
2627
12
    int64_t num_scanned = 0;
2628
12
    int64_t num_recycled = 0;
2629
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
2630
2631
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
2632
2633
12
    auto start_time = steady_clock::now();
2634
2635
12
    DORIS_CLOUD_DEFER {
2636
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2637
12
        metrics_context.finish_report();
2638
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
2639
12
                .tag("instance_id", instance_id_)
2640
12
                .tag("num_scanned", num_scanned)
2641
12
                .tag("num_recycled", num_recycled);
2642
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
2635
12
    DORIS_CLOUD_DEFER {
2636
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2637
12
        metrics_context.finish_report();
2638
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
2639
12
                .tag("instance_id", instance_id_)
2640
12
                .tag("num_scanned", num_scanned)
2641
12
                .tag("num_recycled", num_recycled);
2642
12
    };
2643
2644
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
2645
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
2646
12
    int64_t last_scanned_table_id = 0;
2647
12
    bool is_recycled = false; // Is last scanned kv recycled
2648
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
2649
12
                         &metrics_context, this](std::string_view k, std::string_view) {
2650
2
        ++num_scanned;
2651
2
        auto k1 = k;
2652
2
        k1.remove_prefix(1);
2653
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
2654
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2655
2
        decode_key(&k1, &out);
2656
2
        DCHECK_EQ(out.size(), 6) << k;
2657
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
2658
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
2659
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
2660
0
            return 0;
2661
0
        }
2662
2
        last_scanned_table_id = table_id;
2663
2
        is_recycled = false;
2664
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
2665
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
2666
2
        std::unique_ptr<Transaction> txn;
2667
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2668
2
        if (err != TxnErrorCode::TXN_OK) {
2669
0
            return -1;
2670
0
        }
2671
2
        std::unique_ptr<RangeGetIterator> iter;
2672
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
2673
2
        if (err != TxnErrorCode::TXN_OK) {
2674
0
            return -1;
2675
0
        }
2676
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
2677
1
            return 0;
2678
1
        }
2679
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2680
        // 1. Remove all partition version kvs of this table
2681
1
        auto partition_version_key_begin =
2682
1
                partition_version_key({instance_id_, db_id, table_id, 0});
2683
1
        auto partition_version_key_end =
2684
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
2685
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
2686
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
2687
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
2688
1
                     << " table_id=" << table_id;
2689
        // 2. Remove the table version kv of this table
2690
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
2691
1
        txn->remove(tbl_version_key);
2692
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
2693
        // 3. Remove mow delete bitmap update lock and tablet job lock
2694
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2695
1
        txn->remove(lock_key);
2696
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2697
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2698
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2699
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
2700
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2701
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2702
1
                     << " table_id=" << table_id;
2703
1
        err = txn->commit();
2704
1
        if (err != TxnErrorCode::TXN_OK) {
2705
0
            return -1;
2706
0
        }
2707
1
        metrics_context.total_recycled_num = ++num_recycled;
2708
1
        metrics_context.report();
2709
1
        is_recycled = true;
2710
1
        return 0;
2711
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2649
2
                         &metrics_context, this](std::string_view k, std::string_view) {
2650
2
        ++num_scanned;
2651
2
        auto k1 = k;
2652
2
        k1.remove_prefix(1);
2653
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
2654
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2655
2
        decode_key(&k1, &out);
2656
2
        DCHECK_EQ(out.size(), 6) << k;
2657
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
2658
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
2659
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
2660
0
            return 0;
2661
0
        }
2662
2
        last_scanned_table_id = table_id;
2663
2
        is_recycled = false;
2664
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
2665
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
2666
2
        std::unique_ptr<Transaction> txn;
2667
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2668
2
        if (err != TxnErrorCode::TXN_OK) {
2669
0
            return -1;
2670
0
        }
2671
2
        std::unique_ptr<RangeGetIterator> iter;
2672
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
2673
2
        if (err != TxnErrorCode::TXN_OK) {
2674
0
            return -1;
2675
0
        }
2676
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
2677
1
            return 0;
2678
1
        }
2679
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2680
        // 1. Remove all partition version kvs of this table
2681
1
        auto partition_version_key_begin =
2682
1
                partition_version_key({instance_id_, db_id, table_id, 0});
2683
1
        auto partition_version_key_end =
2684
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
2685
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
2686
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
2687
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
2688
1
                     << " table_id=" << table_id;
2689
        // 2. Remove the table version kv of this table
2690
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
2691
1
        txn->remove(tbl_version_key);
2692
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
2693
        // 3. Remove mow delete bitmap update lock and tablet job lock
2694
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2695
1
        txn->remove(lock_key);
2696
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2697
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2698
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2699
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
2700
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2701
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2702
1
                     << " table_id=" << table_id;
2703
1
        err = txn->commit();
2704
1
        if (err != TxnErrorCode::TXN_OK) {
2705
0
            return -1;
2706
0
        }
2707
1
        metrics_context.total_recycled_num = ++num_recycled;
2708
1
        metrics_context.report();
2709
1
        is_recycled = true;
2710
1
        return 0;
2711
1
    };
2712
2713
12
    if (config::enable_recycler_stats_metrics) {
2714
0
        scan_and_statistics_versions();
2715
0
    }
2716
    // recycle_func and loop_done for scan and recycle
2717
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
2718
14
}
2719
2720
3
int InstanceRecycler::recycle_orphan_partitions() {
2721
3
    int64_t num_scanned = 0;
2722
3
    int64_t num_recycled = 0;
2723
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
2724
2725
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
2726
3
            .tag("instance_id", instance_id_);
2727
2728
3
    auto start_time = steady_clock::now();
2729
2730
3
    DORIS_CLOUD_DEFER {
2731
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2732
3
        metrics_context.finish_report();
2733
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
2734
3
                .tag("instance_id", instance_id_)
2735
3
                .tag("num_scanned", num_scanned)
2736
3
                .tag("num_recycled", num_recycled);
2737
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
2730
3
    DORIS_CLOUD_DEFER {
2731
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2732
3
        metrics_context.finish_report();
2733
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
2734
3
                .tag("instance_id", instance_id_)
2735
3
                .tag("num_scanned", num_scanned)
2736
3
                .tag("num_recycled", num_recycled);
2737
3
    };
2738
2739
3
    bool is_empty_table = false;        // whether the table has no indexes
2740
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
2741
3
    int64_t current_table_id = 0;       // current scanning table id
2742
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
2743
3
                         &current_table_id, &is_table_kvs_recycled,
2744
3
                         this](std::string_view k, std::string_view) {
2745
2
        ++num_scanned;
2746
2747
2
        std::string_view k1(k);
2748
2
        int64_t db_id, table_id, partition_id;
2749
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
2750
2
                                                            &partition_id)) {
2751
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
2752
0
            return -1;
2753
2
        } else if (table_id != current_table_id) {
2754
2
            current_table_id = table_id;
2755
2
            is_table_kvs_recycled = false;
2756
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
2757
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
2758
2
            if (err != TxnErrorCode::TXN_OK) {
2759
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
2760
0
                             << " table_id=" << table_id << " err=" << err;
2761
0
                return -1;
2762
0
            }
2763
2
        }
2764
2765
2
        if (!is_empty_table) {
2766
            // table is not empty, skip recycle
2767
1
            return 0;
2768
1
        }
2769
2770
1
        std::unique_ptr<Transaction> txn;
2771
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2772
1
        if (err != TxnErrorCode::TXN_OK) {
2773
0
            return -1;
2774
0
        }
2775
2776
        // 1. Remove all partition related kvs
2777
1
        std::string partition_meta_key =
2778
1
                versioned::meta_partition_key({instance_id_, partition_id});
2779
1
        std::string partition_index_key =
2780
1
                versioned::partition_index_key({instance_id_, partition_id});
2781
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
2782
1
                {instance_id_, db_id, table_id, partition_id});
2783
1
        std::string partition_version_key =
2784
1
                versioned::partition_version_key({instance_id_, partition_id});
2785
1
        txn->remove(partition_index_key);
2786
1
        txn->remove(partition_inverted_key);
2787
1
        versioned_remove_all(txn.get(), partition_meta_key);
2788
1
        versioned_remove_all(txn.get(), partition_version_key);
2789
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
2790
1
                     << " table_id=" << table_id << " db_id=" << db_id
2791
1
                     << " partition_meta_key=" << hex(partition_meta_key)
2792
1
                     << " partition_version_key=" << hex(partition_version_key);
2793
2794
1
        if (!is_table_kvs_recycled) {
2795
1
            is_table_kvs_recycled = true;
2796
2797
            // 2. Remove the table version kv of this table
2798
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
2799
1
            versioned_remove_all(txn.get(), table_version_key);
2800
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
2801
            // 3. Remove mow delete bitmap update lock and tablet job lock
2802
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2803
1
            txn->remove(lock_key);
2804
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2805
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2806
1
            std::string tablet_job_key_end =
2807
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2808
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
2809
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2810
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2811
1
                         << " table_id=" << table_id;
2812
1
        }
2813
2814
1
        err = txn->commit();
2815
1
        if (err != TxnErrorCode::TXN_OK) {
2816
0
            return -1;
2817
0
        }
2818
1
        metrics_context.total_recycled_num = ++num_recycled;
2819
1
        metrics_context.report();
2820
1
        return 0;
2821
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
2744
2
                         this](std::string_view k, std::string_view) {
2745
2
        ++num_scanned;
2746
2747
2
        std::string_view k1(k);
2748
2
        int64_t db_id, table_id, partition_id;
2749
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
2750
2
                                                            &partition_id)) {
2751
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
2752
0
            return -1;
2753
2
        } else if (table_id != current_table_id) {
2754
2
            current_table_id = table_id;
2755
2
            is_table_kvs_recycled = false;
2756
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
2757
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
2758
2
            if (err != TxnErrorCode::TXN_OK) {
2759
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
2760
0
                             << " table_id=" << table_id << " err=" << err;
2761
0
                return -1;
2762
0
            }
2763
2
        }
2764
2765
2
        if (!is_empty_table) {
2766
            // table is not empty, skip recycle
2767
1
            return 0;
2768
1
        }
2769
2770
1
        std::unique_ptr<Transaction> txn;
2771
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2772
1
        if (err != TxnErrorCode::TXN_OK) {
2773
0
            return -1;
2774
0
        }
2775
2776
        // 1. Remove all partition related kvs
2777
1
        std::string partition_meta_key =
2778
1
                versioned::meta_partition_key({instance_id_, partition_id});
2779
1
        std::string partition_index_key =
2780
1
                versioned::partition_index_key({instance_id_, partition_id});
2781
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
2782
1
                {instance_id_, db_id, table_id, partition_id});
2783
1
        std::string partition_version_key =
2784
1
                versioned::partition_version_key({instance_id_, partition_id});
2785
1
        txn->remove(partition_index_key);
2786
1
        txn->remove(partition_inverted_key);
2787
1
        versioned_remove_all(txn.get(), partition_meta_key);
2788
1
        versioned_remove_all(txn.get(), partition_version_key);
2789
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
2790
1
                     << " table_id=" << table_id << " db_id=" << db_id
2791
1
                     << " partition_meta_key=" << hex(partition_meta_key)
2792
1
                     << " partition_version_key=" << hex(partition_version_key);
2793
2794
1
        if (!is_table_kvs_recycled) {
2795
1
            is_table_kvs_recycled = true;
2796
2797
            // 2. Remove the table version kv of this table
2798
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
2799
1
            versioned_remove_all(txn.get(), table_version_key);
2800
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
2801
            // 3. Remove mow delete bitmap update lock and tablet job lock
2802
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2803
1
            txn->remove(lock_key);
2804
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2805
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2806
1
            std::string tablet_job_key_end =
2807
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2808
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
2809
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2810
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2811
1
                         << " table_id=" << table_id;
2812
1
        }
2813
2814
1
        err = txn->commit();
2815
1
        if (err != TxnErrorCode::TXN_OK) {
2816
0
            return -1;
2817
0
        }
2818
1
        metrics_context.total_recycled_num = ++num_recycled;
2819
1
        metrics_context.report();
2820
1
        return 0;
2821
1
    };
2822
2823
    // recycle_func and loop_done for scan and recycle
2824
3
    return scan_and_recycle(
2825
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
2826
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
2827
3
            std::move(recycle_func));
2828
3
}
2829
2830
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
2831
                                      RecyclerMetricsContext& metrics_context,
2832
49
                                      int64_t partition_id) {
2833
49
    bool is_multi_version =
2834
49
            instance_info_.has_multi_version_status() &&
2835
49
            instance_info_.multi_version_status() != MultiVersionStatus::MULTI_VERSION_DISABLED;
2836
49
    int64_t num_scanned = 0;
2837
49
    std::atomic_long num_recycled = 0;
2838
2839
49
    std::string tablet_key_begin, tablet_key_end;
2840
49
    std::string stats_key_begin, stats_key_end;
2841
49
    std::string job_key_begin, job_key_end;
2842
2843
49
    std::string tablet_belongs;
2844
49
    if (partition_id > 0) {
2845
        // recycle tablets in a partition belonging to the index
2846
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
2847
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
2848
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
2849
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
2850
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
2851
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
2852
33
        tablet_belongs = "partition";
2853
33
    } else {
2854
        // recycle tablets in the index
2855
16
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
2856
16
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
2857
16
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
2858
16
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
2859
16
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
2860
16
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
2861
16
        tablet_belongs = "index";
2862
16
    }
2863
2864
49
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
2865
49
            .tag("table_id", table_id)
2866
49
            .tag("index_id", index_id)
2867
49
            .tag("partition_id", partition_id);
2868
2869
49
    auto start_time = steady_clock::now();
2870
2871
49
    DORIS_CLOUD_DEFER {
2872
49
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2873
49
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
2874
49
                .tag("instance_id", instance_id_)
2875
49
                .tag("table_id", table_id)
2876
49
                .tag("index_id", index_id)
2877
49
                .tag("partition_id", partition_id)
2878
49
                .tag("num_scanned", num_scanned)
2879
49
                .tag("num_recycled", num_recycled);
2880
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
2871
4
    DORIS_CLOUD_DEFER {
2872
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2873
4
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
2874
4
                .tag("instance_id", instance_id_)
2875
4
                .tag("table_id", table_id)
2876
4
                .tag("index_id", index_id)
2877
4
                .tag("partition_id", partition_id)
2878
4
                .tag("num_scanned", num_scanned)
2879
4
                .tag("num_recycled", num_recycled);
2880
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
2871
45
    DORIS_CLOUD_DEFER {
2872
45
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2873
45
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
2874
45
                .tag("instance_id", instance_id_)
2875
45
                .tag("table_id", table_id)
2876
45
                .tag("index_id", index_id)
2877
45
                .tag("partition_id", partition_id)
2878
45
                .tag("num_scanned", num_scanned)
2879
45
                .tag("num_recycled", num_recycled);
2880
45
    };
2881
2882
    // The first string_view represents the tablet key which has been recycled
2883
    // The second bool represents whether the following fdb's tablet key deletion could be done using range move or not
2884
49
    using TabletKeyPair = std::pair<std::string_view, bool>;
2885
49
    SyncExecutor<TabletKeyPair> sync_executor(
2886
49
            _thread_pool_group.recycle_tablet_pool,
2887
49
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
2888
49
                        index_id, partition_id),
2889
4.23k
            [](const TabletKeyPair& k) { return k.first.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKSt4pairISt17basic_string_viewIcSt11char_traitsIcEEbE
Line
Count
Source
2889
4.00k
            [](const TabletKeyPair& k) { return k.first.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKSt4pairISt17basic_string_viewIcSt11char_traitsIcEEbE
Line
Count
Source
2889
237
            [](const TabletKeyPair& k) { return k.first.empty(); });
2890
2891
    // Elements in `tablet_keys` has the same lifetime as `it` in `scan_and_recycle`
2892
49
    std::vector<std::string> tablet_idx_keys;
2893
49
    std::vector<std::string> restore_job_keys;
2894
49
    std::vector<std::string> init_rs_keys;
2895
49
    std::vector<std::string> tablet_compact_stats_keys;
2896
49
    std::vector<std::string> tablet_load_stats_keys;
2897
49
    std::vector<std::string> versioned_meta_tablet_keys;
2898
8.24k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2899
8.24k
        bool use_range_remove = true;
2900
8.24k
        ++num_scanned;
2901
8.24k
        doris::TabletMetaCloudPB tablet_meta_pb;
2902
8.24k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
2903
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
2904
0
            use_range_remove = false;
2905
0
            return -1;
2906
0
        }
2907
8.24k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
2908
2909
8.24k
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
2910
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
2911
4.00k
            return -1;
2912
4.00k
        }
2913
2914
4.24k
        tablet_idx_keys.push_back(meta_tablet_idx_key({instance_id_, tablet_id}));
2915
4.24k
        restore_job_keys.push_back(job_restore_tablet_key({instance_id_, tablet_id}));
2916
4.24k
        if (is_multi_version) {
2917
            // The tablet index/inverted index are recycled in recycle_versioned_tablet.
2918
6
            tablet_compact_stats_keys.push_back(
2919
6
                    versioned::tablet_compact_stats_key({instance_id_, tablet_id}));
2920
6
            tablet_load_stats_keys.push_back(
2921
6
                    versioned::tablet_load_stats_key({instance_id_, tablet_id}));
2922
6
            versioned_meta_tablet_keys.push_back(
2923
6
                    versioned::meta_tablet_key({instance_id_, tablet_id}));
2924
6
        }
2925
4.24k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
2926
4.23k
        sync_executor.add([this, &num_recycled, tid = tablet_id, range_move = use_range_remove,
2927
4.23k
                           &metrics_context, k]() mutable -> TabletKeyPair {
2928
4.23k
            if (recycle_tablet(tid, metrics_context) != 0) {
2929
1
                LOG_WARNING("failed to recycle tablet")
2930
1
                        .tag("instance_id", instance_id_)
2931
1
                        .tag("tablet_id", tid);
2932
1
                range_move = false;
2933
1
                return {std::string_view(), range_move};
2934
1
            }
2935
4.23k
            ++num_recycled;
2936
4.23k
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2937
4.23k
            return {k, range_move};
2938
4.23k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENUlvE_clEv
Line
Count
Source
2927
4.00k
                           &metrics_context, k]() mutable -> TabletKeyPair {
2928
4.00k
            if (recycle_tablet(tid, metrics_context) != 0) {
2929
0
                LOG_WARNING("failed to recycle tablet")
2930
0
                        .tag("instance_id", instance_id_)
2931
0
                        .tag("tablet_id", tid);
2932
0
                range_move = false;
2933
0
                return {std::string_view(), range_move};
2934
0
            }
2935
4.00k
            ++num_recycled;
2936
4.00k
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2937
4.00k
            return {k, range_move};
2938
4.00k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENUlvE_clEv
Line
Count
Source
2927
237
                           &metrics_context, k]() mutable -> TabletKeyPair {
2928
237
            if (recycle_tablet(tid, metrics_context) != 0) {
2929
1
                LOG_WARNING("failed to recycle tablet")
2930
1
                        .tag("instance_id", instance_id_)
2931
1
                        .tag("tablet_id", tid);
2932
1
                range_move = false;
2933
1
                return {std::string_view(), range_move};
2934
1
            }
2935
236
            ++num_recycled;
2936
236
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2937
236
            return {k, range_move};
2938
237
        });
2939
4.23k
        return 0;
2940
4.24k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
2898
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2899
8.00k
        bool use_range_remove = true;
2900
8.00k
        ++num_scanned;
2901
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
2902
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
2903
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
2904
0
            use_range_remove = false;
2905
0
            return -1;
2906
0
        }
2907
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
2908
2909
8.00k
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
2910
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
2911
4.00k
            return -1;
2912
4.00k
        }
2913
2914
4.00k
        tablet_idx_keys.push_back(meta_tablet_idx_key({instance_id_, tablet_id}));
2915
4.00k
        restore_job_keys.push_back(job_restore_tablet_key({instance_id_, tablet_id}));
2916
4.00k
        if (is_multi_version) {
2917
            // The tablet index/inverted index are recycled in recycle_versioned_tablet.
2918
0
            tablet_compact_stats_keys.push_back(
2919
0
                    versioned::tablet_compact_stats_key({instance_id_, tablet_id}));
2920
0
            tablet_load_stats_keys.push_back(
2921
0
                    versioned::tablet_load_stats_key({instance_id_, tablet_id}));
2922
0
            versioned_meta_tablet_keys.push_back(
2923
0
                    versioned::meta_tablet_key({instance_id_, tablet_id}));
2924
0
        }
2925
4.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
2926
4.00k
        sync_executor.add([this, &num_recycled, tid = tablet_id, range_move = use_range_remove,
2927
4.00k
                           &metrics_context, k]() mutable -> TabletKeyPair {
2928
4.00k
            if (recycle_tablet(tid, metrics_context) != 0) {
2929
4.00k
                LOG_WARNING("failed to recycle tablet")
2930
4.00k
                        .tag("instance_id", instance_id_)
2931
4.00k
                        .tag("tablet_id", tid);
2932
4.00k
                range_move = false;
2933
4.00k
                return {std::string_view(), range_move};
2934
4.00k
            }
2935
4.00k
            ++num_recycled;
2936
4.00k
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2937
4.00k
            return {k, range_move};
2938
4.00k
        });
2939
4.00k
        return 0;
2940
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
2898
240
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2899
240
        bool use_range_remove = true;
2900
240
        ++num_scanned;
2901
240
        doris::TabletMetaCloudPB tablet_meta_pb;
2902
240
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
2903
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
2904
0
            use_range_remove = false;
2905
0
            return -1;
2906
0
        }
2907
240
        int64_t tablet_id = tablet_meta_pb.tablet_id();
2908
2909
240
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
2910
0
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
2911
0
            return -1;
2912
0
        }
2913
2914
240
        tablet_idx_keys.push_back(meta_tablet_idx_key({instance_id_, tablet_id}));
2915
240
        restore_job_keys.push_back(job_restore_tablet_key({instance_id_, tablet_id}));
2916
240
        if (is_multi_version) {
2917
            // The tablet index/inverted index are recycled in recycle_versioned_tablet.
2918
6
            tablet_compact_stats_keys.push_back(
2919
6
                    versioned::tablet_compact_stats_key({instance_id_, tablet_id}));
2920
6
            tablet_load_stats_keys.push_back(
2921
6
                    versioned::tablet_load_stats_key({instance_id_, tablet_id}));
2922
6
            versioned_meta_tablet_keys.push_back(
2923
6
                    versioned::meta_tablet_key({instance_id_, tablet_id}));
2924
6
        }
2925
240
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
2926
237
        sync_executor.add([this, &num_recycled, tid = tablet_id, range_move = use_range_remove,
2927
237
                           &metrics_context, k]() mutable -> TabletKeyPair {
2928
237
            if (recycle_tablet(tid, metrics_context) != 0) {
2929
237
                LOG_WARNING("failed to recycle tablet")
2930
237
                        .tag("instance_id", instance_id_)
2931
237
                        .tag("tablet_id", tid);
2932
237
                range_move = false;
2933
237
                return {std::string_view(), range_move};
2934
237
            }
2935
237
            ++num_recycled;
2936
237
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2937
237
            return {k, range_move};
2938
237
        });
2939
237
        return 0;
2940
240
    };
2941
2942
    // TODO(AlexYue): Add one ut to cover use_range_remove = false
2943
49
    auto loop_done = [&, this]() -> int {
2944
49
        bool finished = true;
2945
49
        auto tablet_keys = sync_executor.when_all(&finished);
2946
49
        if (!finished) {
2947
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
2948
1
            return -1;
2949
1
        }
2950
48
        if (tablet_keys.empty() && tablet_idx_keys.empty()) return 0;
2951
46
        if (!tablet_keys.empty() &&
2952
46
            std::ranges::all_of(tablet_keys, [](const auto& k) { return k.first.empty(); })) {
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_E_clISt4pairISt17basic_string_viewIcSt11char_traitsIcEEbEEEDaS7_
Line
Count
Source
2952
2
            std::ranges::all_of(tablet_keys, [](const auto& k) { return k.first.empty(); })) {
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_E_clISt4pairISt17basic_string_viewIcSt11char_traitsIcEEbEEEDaS7_
Line
Count
Source
2952
42
            std::ranges::all_of(tablet_keys, [](const auto& k) { return k.first.empty(); })) {
2953
0
            return -1;
2954
0
        }
2955
        // sort the vector using key's order
2956
46
        std::sort(tablet_keys.begin(), tablet_keys.end(),
2957
49.4k
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_RKT0_E_clISt4pairISt17basic_string_viewIcSt11char_traitsIcEEbESI_EEDaS7_SA_
Line
Count
Source
2957
48.4k
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_RKT0_E_clISt4pairISt17basic_string_viewIcSt11char_traitsIcEEbESI_EEDaS7_SA_
Line
Count
Source
2957
944
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
2958
46
        bool use_range_remove = true;
2959
4.23k
        for (auto& [_, remove] : tablet_keys) {
2960
4.23k
            if (!remove) {
2961
0
                use_range_remove = remove;
2962
0
                break;
2963
0
            }
2964
4.23k
        }
2965
46
        DORIS_CLOUD_DEFER {
2966
46
            tablet_idx_keys.clear();
2967
46
            restore_job_keys.clear();
2968
46
            init_rs_keys.clear();
2969
46
            tablet_compact_stats_keys.clear();
2970
46
            tablet_load_stats_keys.clear();
2971
46
            versioned_meta_tablet_keys.clear();
2972
46
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2965
2
        DORIS_CLOUD_DEFER {
2966
2
            tablet_idx_keys.clear();
2967
2
            restore_job_keys.clear();
2968
2
            init_rs_keys.clear();
2969
2
            tablet_compact_stats_keys.clear();
2970
2
            tablet_load_stats_keys.clear();
2971
2
            versioned_meta_tablet_keys.clear();
2972
2
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2965
44
        DORIS_CLOUD_DEFER {
2966
44
            tablet_idx_keys.clear();
2967
44
            restore_job_keys.clear();
2968
44
            init_rs_keys.clear();
2969
44
            tablet_compact_stats_keys.clear();
2970
44
            tablet_load_stats_keys.clear();
2971
44
            versioned_meta_tablet_keys.clear();
2972
44
        };
2973
46
        std::unique_ptr<Transaction> txn;
2974
46
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2975
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
2976
0
            return -1;
2977
0
        }
2978
46
        std::string tablet_key_end;
2979
46
        if (!tablet_keys.empty()) {
2980
44
            if (use_range_remove) {
2981
44
                tablet_key_end = std::string(tablet_keys.back().first) + '\x00';
2982
44
                txn->remove(tablet_keys.front().first, tablet_key_end);
2983
44
            } else {
2984
0
                for (auto& [k, _] : tablet_keys) {
2985
0
                    txn->remove(k);
2986
0
                }
2987
0
            }
2988
44
        }
2989
46
        if (is_multi_version) {
2990
6
            for (auto& k : tablet_compact_stats_keys) {
2991
                // Remove all versions of tablet compact stats for recycled tablet
2992
6
                LOG_INFO("remove versioned tablet compact stats key")
2993
6
                        .tag("compact_stats_key", hex(k));
2994
6
                versioned_remove_all(txn.get(), k);
2995
6
            }
2996
6
            for (auto& k : tablet_load_stats_keys) {
2997
                // Remove all versions of tablet load stats for recycled tablet
2998
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
2999
6
                versioned_remove_all(txn.get(), k);
3000
6
            }
3001
6
            for (auto& k : versioned_meta_tablet_keys) {
3002
                // Remove all versions of meta tablet for recycled tablet
3003
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3004
6
                versioned_remove_all(txn.get(), k);
3005
6
            }
3006
5
        }
3007
4.24k
        for (auto& k : tablet_idx_keys) {
3008
4.24k
            txn->remove(k);
3009
4.24k
        }
3010
4.24k
        for (auto& k : restore_job_keys) {
3011
4.24k
            txn->remove(k);
3012
4.24k
        }
3013
46
        for (auto& k : init_rs_keys) {
3014
0
            txn->remove(k);
3015
0
        }
3016
46
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3017
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3018
0
                         << ", err=" << err;
3019
0
            return -1;
3020
0
        }
3021
46
        return 0;
3022
46
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
2943
4
    auto loop_done = [&, this]() -> int {
2944
4
        bool finished = true;
2945
4
        auto tablet_keys = sync_executor.when_all(&finished);
2946
4
        if (!finished) {
2947
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
2948
0
            return -1;
2949
0
        }
2950
4
        if (tablet_keys.empty() && tablet_idx_keys.empty()) return 0;
2951
2
        if (!tablet_keys.empty() &&
2952
2
            std::ranges::all_of(tablet_keys, [](const auto& k) { return k.first.empty(); })) {
2953
0
            return -1;
2954
0
        }
2955
        // sort the vector using key's order
2956
2
        std::sort(tablet_keys.begin(), tablet_keys.end(),
2957
2
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
2958
2
        bool use_range_remove = true;
2959
4.00k
        for (auto& [_, remove] : tablet_keys) {
2960
4.00k
            if (!remove) {
2961
0
                use_range_remove = remove;
2962
0
                break;
2963
0
            }
2964
4.00k
        }
2965
2
        DORIS_CLOUD_DEFER {
2966
2
            tablet_idx_keys.clear();
2967
2
            restore_job_keys.clear();
2968
2
            init_rs_keys.clear();
2969
2
            tablet_compact_stats_keys.clear();
2970
2
            tablet_load_stats_keys.clear();
2971
2
            versioned_meta_tablet_keys.clear();
2972
2
        };
2973
2
        std::unique_ptr<Transaction> txn;
2974
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2975
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
2976
0
            return -1;
2977
0
        }
2978
2
        std::string tablet_key_end;
2979
2
        if (!tablet_keys.empty()) {
2980
2
            if (use_range_remove) {
2981
2
                tablet_key_end = std::string(tablet_keys.back().first) + '\x00';
2982
2
                txn->remove(tablet_keys.front().first, tablet_key_end);
2983
2
            } else {
2984
0
                for (auto& [k, _] : tablet_keys) {
2985
0
                    txn->remove(k);
2986
0
                }
2987
0
            }
2988
2
        }
2989
2
        if (is_multi_version) {
2990
0
            for (auto& k : tablet_compact_stats_keys) {
2991
                // Remove all versions of tablet compact stats for recycled tablet
2992
0
                LOG_INFO("remove versioned tablet compact stats key")
2993
0
                        .tag("compact_stats_key", hex(k));
2994
0
                versioned_remove_all(txn.get(), k);
2995
0
            }
2996
0
            for (auto& k : tablet_load_stats_keys) {
2997
                // Remove all versions of tablet load stats for recycled tablet
2998
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
2999
0
                versioned_remove_all(txn.get(), k);
3000
0
            }
3001
0
            for (auto& k : versioned_meta_tablet_keys) {
3002
                // Remove all versions of meta tablet for recycled tablet
3003
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3004
0
                versioned_remove_all(txn.get(), k);
3005
0
            }
3006
0
        }
3007
4.00k
        for (auto& k : tablet_idx_keys) {
3008
4.00k
            txn->remove(k);
3009
4.00k
        }
3010
4.00k
        for (auto& k : restore_job_keys) {
3011
4.00k
            txn->remove(k);
3012
4.00k
        }
3013
2
        for (auto& k : init_rs_keys) {
3014
0
            txn->remove(k);
3015
0
        }
3016
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3017
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3018
0
                         << ", err=" << err;
3019
0
            return -1;
3020
0
        }
3021
2
        return 0;
3022
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
2943
45
    auto loop_done = [&, this]() -> int {
2944
45
        bool finished = true;
2945
45
        auto tablet_keys = sync_executor.when_all(&finished);
2946
45
        if (!finished) {
2947
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
2948
1
            return -1;
2949
1
        }
2950
44
        if (tablet_keys.empty() && tablet_idx_keys.empty()) return 0;
2951
44
        if (!tablet_keys.empty() &&
2952
44
            std::ranges::all_of(tablet_keys, [](const auto& k) { return k.first.empty(); })) {
2953
0
            return -1;
2954
0
        }
2955
        // sort the vector using key's order
2956
44
        std::sort(tablet_keys.begin(), tablet_keys.end(),
2957
44
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
2958
44
        bool use_range_remove = true;
2959
236
        for (auto& [_, remove] : tablet_keys) {
2960
236
            if (!remove) {
2961
0
                use_range_remove = remove;
2962
0
                break;
2963
0
            }
2964
236
        }
2965
44
        DORIS_CLOUD_DEFER {
2966
44
            tablet_idx_keys.clear();
2967
44
            restore_job_keys.clear();
2968
44
            init_rs_keys.clear();
2969
44
            tablet_compact_stats_keys.clear();
2970
44
            tablet_load_stats_keys.clear();
2971
44
            versioned_meta_tablet_keys.clear();
2972
44
        };
2973
44
        std::unique_ptr<Transaction> txn;
2974
44
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2975
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
2976
0
            return -1;
2977
0
        }
2978
44
        std::string tablet_key_end;
2979
44
        if (!tablet_keys.empty()) {
2980
42
            if (use_range_remove) {
2981
42
                tablet_key_end = std::string(tablet_keys.back().first) + '\x00';
2982
42
                txn->remove(tablet_keys.front().first, tablet_key_end);
2983
42
            } else {
2984
0
                for (auto& [k, _] : tablet_keys) {
2985
0
                    txn->remove(k);
2986
0
                }
2987
0
            }
2988
42
        }
2989
44
        if (is_multi_version) {
2990
6
            for (auto& k : tablet_compact_stats_keys) {
2991
                // Remove all versions of tablet compact stats for recycled tablet
2992
6
                LOG_INFO("remove versioned tablet compact stats key")
2993
6
                        .tag("compact_stats_key", hex(k));
2994
6
                versioned_remove_all(txn.get(), k);
2995
6
            }
2996
6
            for (auto& k : tablet_load_stats_keys) {
2997
                // Remove all versions of tablet load stats for recycled tablet
2998
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
2999
6
                versioned_remove_all(txn.get(), k);
3000
6
            }
3001
6
            for (auto& k : versioned_meta_tablet_keys) {
3002
                // Remove all versions of meta tablet for recycled tablet
3003
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3004
6
                versioned_remove_all(txn.get(), k);
3005
6
            }
3006
5
        }
3007
239
        for (auto& k : tablet_idx_keys) {
3008
239
            txn->remove(k);
3009
239
        }
3010
239
        for (auto& k : restore_job_keys) {
3011
239
            txn->remove(k);
3012
239
        }
3013
44
        for (auto& k : init_rs_keys) {
3014
0
            txn->remove(k);
3015
0
        }
3016
44
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3017
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3018
0
                         << ", err=" << err;
3019
0
            return -1;
3020
0
        }
3021
44
        return 0;
3022
44
    };
3023
3024
49
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
3025
49
                               std::move(loop_done));
3026
49
    if (ret != 0) {
3027
3
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
3028
3
        return ret;
3029
3
    }
3030
3031
    // directly remove tablet stats and tablet jobs of these dropped index or partition
3032
46
    std::unique_ptr<Transaction> txn;
3033
46
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3034
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
3035
0
        return -1;
3036
0
    }
3037
46
    txn->remove(stats_key_begin, stats_key_end);
3038
46
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
3039
46
                 << " end=" << hex(stats_key_end);
3040
46
    txn->remove(job_key_begin, job_key_end);
3041
46
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
3042
46
    std::string schema_key_begin, schema_key_end;
3043
46
    std::string schema_dict_key;
3044
46
    std::string versioned_schema_key_begin, versioned_schema_key_end;
3045
46
    if (partition_id <= 0) {
3046
        // Delete schema kv of this index
3047
14
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
3048
14
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
3049
14
        txn->remove(schema_key_begin, schema_key_end);
3050
14
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
3051
14
                     << " end=" << hex(schema_key_end);
3052
14
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
3053
14
        txn->remove(schema_dict_key);
3054
14
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
3055
14
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
3056
14
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
3057
14
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
3058
14
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
3059
14
                     << " end=" << hex(versioned_schema_key_end);
3060
14
    }
3061
3062
46
    TxnErrorCode err = txn->commit();
3063
46
    if (err != TxnErrorCode::TXN_OK) {
3064
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
3065
0
                     << " err=" << err;
3066
0
        return -1;
3067
0
    }
3068
3069
46
    return ret;
3070
46
}
3071
3072
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
3073
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
3074
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
3075
5.61k
    if (num_segments <= 0) return 0;
3076
3077
5.61k
    std::vector<std::string> file_paths;
3078
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
3079
0
        return -1;
3080
0
    }
3081
3082
    // Process inverted indexes
3083
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
3084
    // default format as v1.
3085
5.61k
    InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
3086
5.61k
    bool delete_rowset_data_by_prefix = false;
3087
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3088
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3089
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3090
0
        delete_rowset_data_by_prefix = true;
3091
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
3092
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
3093
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3094
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3095
10.0k
            }
3096
10.0k
        }
3097
4.80k
        if (rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
3098
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
3099
2.00k
        }
3100
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
3101
        // schema version and index id are not found, delete rowset data by prefix directly.
3102
0
        delete_rowset_data_by_prefix = true;
3103
809
    } else {
3104
        // otherwise, try to get schema kv
3105
809
        InvertedIndexInfo index_info;
3106
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
3107
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
3108
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3109
809
                                 &inverted_index_get_ret);
3110
809
        if (inverted_index_get_ret == 0) {
3111
809
            index_format = index_info.first;
3112
809
            index_ids = index_info.second;
3113
809
        } else if (inverted_index_get_ret == 1) {
3114
            // 1. Schema kv not found means tablet has been recycled
3115
            // Maybe some tablet recycle failed by some bugs
3116
            // We need to delete again to double check
3117
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3118
            // because we are uncertain about the inverted index information.
3119
            // If there are inverted indexes, some data might not be deleted,
3120
            // but this is acceptable as we have made our best effort to delete the data.
3121
0
            LOG_INFO(
3122
0
                    "delete rowset data schema kv not found, need to delete again to double "
3123
0
                    "check")
3124
0
                    .tag("instance_id", instance_id_)
3125
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3126
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
3127
            // Currently index_ids is guaranteed to be empty,
3128
            // but we clear it again here as a safeguard against future code changes
3129
            // that might cause index_ids to no longer be empty
3130
0
            index_format = InvertedIndexStorageFormatPB::V2;
3131
0
            index_ids.clear();
3132
0
        } else {
3133
            // failed to get schema kv, delete rowset data by prefix directly.
3134
0
            delete_rowset_data_by_prefix = true;
3135
0
        }
3136
809
    }
3137
3138
5.61k
    if (delete_rowset_data_by_prefix) {
3139
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
3140
0
                                  rs_meta_pb.rowset_id_v2());
3141
0
    }
3142
3143
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
3144
5.61k
    if (it == accessor_map_.end()) {
3145
1.59k
        LOG_WARNING("instance has no such resource id")
3146
1.59k
                .tag("instance_id", instance_id_)
3147
1.59k
                .tag("resource_id", rs_meta_pb.resource_id());
3148
1.59k
        return -1;
3149
1.59k
    }
3150
4.01k
    auto& accessor = it->second;
3151
3152
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
3153
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
3154
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
3155
20.0k
        file_paths.push_back(segment_path(tablet_id, rowset_id, i));
3156
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
3157
40.0k
            for (const auto& index_id : index_ids) {
3158
40.0k
                file_paths.push_back(inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
3159
40.0k
                                                            index_id.second));
3160
40.0k
            }
3161
20.0k
        } else if (!index_ids.empty()) {
3162
0
            file_paths.push_back(inverted_index_path_v2(tablet_id, rowset_id, i));
3163
0
        }
3164
20.0k
    }
3165
3166
    // Process delete bitmap - check where it's stored.
3167
4.01k
    DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3168
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3169
4.01k
                                                       &delete_bitmap_storage_type) != 0) {
3170
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3171
0
                .tag("instance_id", instance_id_)
3172
0
                .tag("tablet_id", tablet_id)
3173
0
                .tag("rowset_id", rowset_id);
3174
0
        return -1;
3175
0
    }
3176
4.01k
    if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3177
2.00k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3178
2.00k
    }
3179
    // TODO(AlexYue): seems could do do batch
3180
4.01k
    return accessor->delete_files(file_paths);
3181
4.01k
}
3182
3183
62.3k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3184
62.3k
    LOG_INFO("begin process_packed_file_location_index")
3185
62.3k
            .tag("instance_id", instance_id_)
3186
62.3k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3187
62.3k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3188
62.3k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3189
62.3k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3190
62.3k
    if (index_map.empty()) {
3191
62.3k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3192
62.3k
                .tag("instance_id", instance_id_)
3193
62.3k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3194
62.3k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3195
62.3k
        return 0;
3196
62.3k
    }
3197
3198
15
    struct PackedSmallFileInfo {
3199
15
        std::string small_file_path;
3200
15
    };
3201
15
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3202
15
    packed_file_updates.reserve(index_map.size());
3203
27
    for (const auto& [small_path, index_pb] : index_map) {
3204
27
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3205
0
            continue;
3206
0
        }
3207
27
        packed_file_updates[index_pb.packed_file_path()].push_back(
3208
27
                PackedSmallFileInfo {small_path});
3209
27
    }
3210
15
    if (packed_file_updates.empty()) {
3211
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3212
0
                .tag("instance_id", instance_id_)
3213
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3214
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3215
0
                .tag("index_map_size", index_map.size());
3216
0
        return 0;
3217
0
    }
3218
3219
15
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3220
15
    int ret = 0;
3221
24
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3222
24
        if (small_files.empty()) {
3223
0
            continue;
3224
0
        }
3225
3226
24
        bool success = false;
3227
24
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3228
24
            std::unique_ptr<Transaction> txn;
3229
24
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3230
24
            if (err != TxnErrorCode::TXN_OK) {
3231
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3232
0
                        .tag("instance_id", instance_id_)
3233
0
                        .tag("packed_file_path", packed_file_path)
3234
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3235
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3236
0
                        .tag("err", err);
3237
0
                ret = -1;
3238
0
                break;
3239
0
            }
3240
3241
24
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3242
24
            std::string packed_val;
3243
24
            err = txn->get(packed_key, &packed_val);
3244
24
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3245
0
                LOG_WARNING("packed file info not found when recycling rowset")
3246
0
                        .tag("instance_id", instance_id_)
3247
0
                        .tag("packed_file_path", packed_file_path)
3248
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3249
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3250
0
                        .tag("key", hex(packed_key))
3251
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3252
                // Skip this packed file entry and continue with others
3253
0
                success = true;
3254
0
                break;
3255
0
            }
3256
24
            if (err != TxnErrorCode::TXN_OK) {
3257
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
3258
0
                        .tag("instance_id", instance_id_)
3259
0
                        .tag("packed_file_path", packed_file_path)
3260
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3261
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3262
0
                        .tag("err", err);
3263
0
                ret = -1;
3264
0
                break;
3265
0
            }
3266
3267
24
            cloud::PackedFileInfoPB packed_info;
3268
24
            if (!packed_info.ParseFromString(packed_val)) {
3269
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
3270
0
                        .tag("instance_id", instance_id_)
3271
0
                        .tag("packed_file_path", packed_file_path)
3272
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3273
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3274
0
                ret = -1;
3275
0
                break;
3276
0
            }
3277
3278
24
            LOG_INFO("packed file update check")
3279
24
                    .tag("instance_id", instance_id_)
3280
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3281
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3282
24
                    .tag("merged_file_path", packed_file_path)
3283
24
                    .tag("requested_small_files", small_files.size())
3284
24
                    .tag("merge_entries", packed_info.slices_size());
3285
3286
24
            auto* small_file_entries = packed_info.mutable_slices();
3287
24
            int64_t changed_files = 0;
3288
24
            int64_t missing_entries = 0;
3289
24
            int64_t already_deleted = 0;
3290
27
            for (const auto& small_file_info : small_files) {
3291
27
                bool found = false;
3292
87
                for (auto& small_file_entry : *small_file_entries) {
3293
87
                    if (small_file_entry.path() == small_file_info.small_file_path) {
3294
27
                        if (!small_file_entry.deleted()) {
3295
27
                            small_file_entry.set_deleted(true);
3296
27
                            if (!small_file_entry.corrected()) {
3297
27
                                small_file_entry.set_corrected(true);
3298
27
                            }
3299
27
                            ++changed_files;
3300
27
                        } else {
3301
0
                            ++already_deleted;
3302
0
                        }
3303
27
                        found = true;
3304
27
                        break;
3305
27
                    }
3306
87
                }
3307
27
                if (!found) {
3308
0
                    ++missing_entries;
3309
0
                    LOG_WARNING("packed file info missing small file entry")
3310
0
                            .tag("instance_id", instance_id_)
3311
0
                            .tag("packed_file_path", packed_file_path)
3312
0
                            .tag("small_file_path", small_file_info.small_file_path)
3313
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3314
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
3315
0
                }
3316
27
            }
3317
3318
24
            if (changed_files == 0) {
3319
0
                LOG_INFO("skip merge file update: no merge entries changed")
3320
0
                        .tag("instance_id", instance_id_)
3321
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3322
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3323
0
                        .tag("merged_file_path", packed_file_path)
3324
0
                        .tag("missing_entries", missing_entries)
3325
0
                        .tag("already_deleted", already_deleted)
3326
0
                        .tag("requested_small_files", small_files.size())
3327
0
                        .tag("merge_entries", packed_info.slices_size());
3328
0
                success = true;
3329
0
                break;
3330
0
            }
3331
3332
            // Calculate remaining files
3333
24
            int64_t left_file_count = 0;
3334
24
            int64_t left_file_bytes = 0;
3335
141
            for (const auto& small_file_entry : packed_info.slices()) {
3336
141
                if (!small_file_entry.deleted()) {
3337
57
                    ++left_file_count;
3338
57
                    left_file_bytes += small_file_entry.size();
3339
57
                }
3340
141
            }
3341
24
            packed_info.set_remaining_slice_bytes(left_file_bytes);
3342
24
            packed_info.set_ref_cnt(left_file_count);
3343
24
            LOG_INFO("updated packed file reference info")
3344
24
                    .tag("instance_id", instance_id_)
3345
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3346
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3347
24
                    .tag("packed_file_path", packed_file_path)
3348
24
                    .tag("ref_cnt", left_file_count)
3349
24
                    .tag("left_file_bytes", left_file_bytes);
3350
3351
24
            if (left_file_count == 0) {
3352
7
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3353
7
            }
3354
3355
24
            std::string updated_val;
3356
24
            if (!packed_info.SerializeToString(&updated_val)) {
3357
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
3358
0
                        .tag("instance_id", instance_id_)
3359
0
                        .tag("packed_file_path", packed_file_path)
3360
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3361
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3362
0
                ret = -1;
3363
0
                break;
3364
0
            }
3365
3366
24
            txn->put(packed_key, updated_val);
3367
24
            err = txn->commit();
3368
24
            if (err == TxnErrorCode::TXN_OK) {
3369
24
                success = true;
3370
24
                if (left_file_count == 0) {
3371
7
                    LOG_INFO("packed file ready to delete, deleting immediately")
3372
7
                            .tag("instance_id", instance_id_)
3373
7
                            .tag("packed_file_path", packed_file_path);
3374
7
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3375
0
                        ret = -1;
3376
0
                    }
3377
7
                }
3378
24
                break;
3379
24
            }
3380
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
3381
0
                if (attempt >= max_retry_times) {
3382
0
                    LOG_WARNING("packed file info update conflict after max retry")
3383
0
                            .tag("instance_id", instance_id_)
3384
0
                            .tag("packed_file_path", packed_file_path)
3385
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3386
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
3387
0
                            .tag("changed_files", changed_files)
3388
0
                            .tag("attempt", attempt);
3389
0
                    ret = -1;
3390
0
                    break;
3391
0
                }
3392
0
                LOG_WARNING("packed file info update conflict, retrying")
3393
0
                        .tag("instance_id", instance_id_)
3394
0
                        .tag("packed_file_path", packed_file_path)
3395
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3396
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3397
0
                        .tag("changed_files", changed_files)
3398
0
                        .tag("attempt", attempt);
3399
0
                sleep_for_packed_file_retry();
3400
0
                continue;
3401
0
            }
3402
3403
0
            LOG_WARNING("failed to commit packed file info update")
3404
0
                    .tag("instance_id", instance_id_)
3405
0
                    .tag("packed_file_path", packed_file_path)
3406
0
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3407
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3408
0
                    .tag("err", err)
3409
0
                    .tag("changed_files", changed_files);
3410
0
            ret = -1;
3411
0
            break;
3412
0
        }
3413
3414
24
        if (!success) {
3415
0
            ret = -1;
3416
0
        }
3417
24
    }
3418
3419
15
    return ret;
3420
15
}
3421
3422
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(
3423
        int64_t tablet_id, const std::string& rowset_id,
3424
58.2k
        DeleteBitmapStorageType* out_storage_type) {
3425
58.2k
    if (out_storage_type) {
3426
58.2k
        *out_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3427
58.2k
    }
3428
3429
    // Get delete bitmap storage info from FDB
3430
58.2k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
3431
58.2k
    std::unique_ptr<Transaction> txn;
3432
58.2k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
3433
58.2k
    if (err != TxnErrorCode::TXN_OK) {
3434
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
3435
0
                .tag("instance_id", instance_id_)
3436
0
                .tag("tablet_id", tablet_id)
3437
0
                .tag("rowset_id", rowset_id)
3438
0
                .tag("err", err);
3439
0
        return -1;
3440
0
    }
3441
3442
58.2k
    std::string dbm_val;
3443
58.2k
    err = txn->get(dbm_key, &dbm_val);
3444
58.2k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3445
        // No delete bitmap for this rowset, nothing to do
3446
4.63k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
3447
4.63k
                .tag("instance_id", instance_id_)
3448
4.63k
                .tag("tablet_id", tablet_id)
3449
4.63k
                .tag("rowset_id", rowset_id);
3450
4.63k
        return 0;
3451
4.63k
    }
3452
53.5k
    if (err != TxnErrorCode::TXN_OK) {
3453
0
        LOG_WARNING("failed to get delete bitmap storage")
3454
0
                .tag("instance_id", instance_id_)
3455
0
                .tag("tablet_id", tablet_id)
3456
0
                .tag("rowset_id", rowset_id)
3457
0
                .tag("err", err);
3458
0
        return -1;
3459
0
    }
3460
3461
53.5k
    DeleteBitmapStoragePB storage;
3462
53.5k
    if (!storage.ParseFromString(dbm_val)) {
3463
0
        LOG_WARNING("failed to parse delete bitmap storage")
3464
0
                .tag("instance_id", instance_id_)
3465
0
                .tag("tablet_id", tablet_id)
3466
0
                .tag("rowset_id", rowset_id);
3467
0
        return -1;
3468
0
    }
3469
3470
53.5k
    if (storage.store_in_fdb()) {
3471
0
        if (out_storage_type) {
3472
0
            *out_storage_type = DeleteBitmapStorageType::IN_FDB;
3473
0
        }
3474
0
        return 0;
3475
0
    }
3476
3477
    // Check if delete bitmap is stored in standalone file.
3478
53.5k
    if (!storage.has_packed_slice_location() ||
3479
53.5k
        storage.packed_slice_location().packed_file_path().empty()) {
3480
53.5k
        if (out_storage_type) {
3481
53.5k
            *out_storage_type = DeleteBitmapStorageType::STANDALONE_FILE;
3482
53.5k
        }
3483
53.5k
        return 0;
3484
53.5k
    }
3485
3486
18.4E
    if (out_storage_type) {
3487
0
        *out_storage_type = DeleteBitmapStorageType::PACKED_FILE;
3488
0
    }
3489
3490
18.4E
    const auto& packed_loc = storage.packed_slice_location();
3491
18.4E
    const std::string& packed_file_path = packed_loc.packed_file_path();
3492
3493
18.4E
    LOG_INFO("decrementing delete bitmap packed file ref count")
3494
18.4E
            .tag("instance_id", instance_id_)
3495
18.4E
            .tag("tablet_id", tablet_id)
3496
18.4E
            .tag("rowset_id", rowset_id)
3497
18.4E
            .tag("packed_file_path", packed_file_path);
3498
3499
18.4E
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3500
18.4E
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3501
0
        std::unique_ptr<Transaction> update_txn;
3502
0
        err = txn_kv_->create_txn(&update_txn);
3503
0
        if (err != TxnErrorCode::TXN_OK) {
3504
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
3505
0
                    .tag("instance_id", instance_id_)
3506
0
                    .tag("tablet_id", tablet_id)
3507
0
                    .tag("rowset_id", rowset_id)
3508
0
                    .tag("err", err);
3509
0
            return -1;
3510
0
        }
3511
3512
0
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3513
0
        std::string packed_val;
3514
0
        err = update_txn->get(packed_key, &packed_val);
3515
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3516
0
            LOG_WARNING("packed file info not found for delete bitmap")
3517
0
                    .tag("instance_id", instance_id_)
3518
0
                    .tag("tablet_id", tablet_id)
3519
0
                    .tag("rowset_id", rowset_id)
3520
0
                    .tag("packed_file_path", packed_file_path);
3521
0
            return 0;
3522
0
        }
3523
0
        if (err != TxnErrorCode::TXN_OK) {
3524
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
3525
0
                    .tag("instance_id", instance_id_)
3526
0
                    .tag("tablet_id", tablet_id)
3527
0
                    .tag("rowset_id", rowset_id)
3528
0
                    .tag("packed_file_path", packed_file_path)
3529
0
                    .tag("err", err);
3530
0
            return -1;
3531
0
        }
3532
3533
0
        cloud::PackedFileInfoPB packed_info;
3534
0
        if (!packed_info.ParseFromString(packed_val)) {
3535
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
3536
0
                    .tag("instance_id", instance_id_)
3537
0
                    .tag("tablet_id", tablet_id)
3538
0
                    .tag("rowset_id", rowset_id)
3539
0
                    .tag("packed_file_path", packed_file_path);
3540
0
            return -1;
3541
0
        }
3542
3543
        // Find and mark the small file entry as deleted
3544
        // Use tablet_id and rowset_id to match entry instead of path,
3545
        // because path format may vary with path_version (with or without shard prefix)
3546
0
        auto* entries = packed_info.mutable_slices();
3547
0
        bool found = false;
3548
0
        bool already_deleted = false;
3549
0
        for (auto& entry : *entries) {
3550
0
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
3551
0
                if (!entry.deleted()) {
3552
0
                    entry.set_deleted(true);
3553
0
                    if (!entry.corrected()) {
3554
0
                        entry.set_corrected(true);
3555
0
                    }
3556
0
                } else {
3557
0
                    already_deleted = true;
3558
0
                }
3559
0
                found = true;
3560
0
                break;
3561
0
            }
3562
0
        }
3563
3564
0
        if (!found) {
3565
0
            LOG_WARNING("delete bitmap entry not found in packed file")
3566
0
                    .tag("instance_id", instance_id_)
3567
0
                    .tag("tablet_id", tablet_id)
3568
0
                    .tag("rowset_id", rowset_id)
3569
0
                    .tag("packed_file_path", packed_file_path);
3570
0
            return 0;
3571
0
        }
3572
3573
0
        if (already_deleted) {
3574
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
3575
0
                    .tag("instance_id", instance_id_)
3576
0
                    .tag("tablet_id", tablet_id)
3577
0
                    .tag("rowset_id", rowset_id)
3578
0
                    .tag("packed_file_path", packed_file_path);
3579
0
            return 0;
3580
0
        }
3581
3582
        // Calculate remaining files
3583
0
        int64_t left_file_count = 0;
3584
0
        int64_t left_file_bytes = 0;
3585
0
        for (const auto& entry : packed_info.slices()) {
3586
0
            if (!entry.deleted()) {
3587
0
                ++left_file_count;
3588
0
                left_file_bytes += entry.size();
3589
0
            }
3590
0
        }
3591
0
        packed_info.set_remaining_slice_bytes(left_file_bytes);
3592
0
        packed_info.set_ref_cnt(left_file_count);
3593
3594
0
        if (left_file_count == 0) {
3595
0
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3596
0
        }
3597
3598
0
        std::string updated_val;
3599
0
        if (!packed_info.SerializeToString(&updated_val)) {
3600
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
3601
0
                    .tag("instance_id", instance_id_)
3602
0
                    .tag("tablet_id", tablet_id)
3603
0
                    .tag("rowset_id", rowset_id)
3604
0
                    .tag("packed_file_path", packed_file_path);
3605
0
            return -1;
3606
0
        }
3607
3608
0
        update_txn->put(packed_key, updated_val);
3609
0
        err = update_txn->commit();
3610
0
        if (err == TxnErrorCode::TXN_OK) {
3611
0
            LOG_INFO("delete bitmap packed file ref count decremented")
3612
0
                    .tag("instance_id", instance_id_)
3613
0
                    .tag("tablet_id", tablet_id)
3614
0
                    .tag("rowset_id", rowset_id)
3615
0
                    .tag("packed_file_path", packed_file_path)
3616
0
                    .tag("left_file_count", left_file_count);
3617
0
            if (left_file_count == 0) {
3618
0
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3619
0
                    return -1;
3620
0
                }
3621
0
            }
3622
0
            return 0;
3623
0
        }
3624
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
3625
0
            if (attempt >= max_retry_times) {
3626
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
3627
0
                        .tag("instance_id", instance_id_)
3628
0
                        .tag("tablet_id", tablet_id)
3629
0
                        .tag("rowset_id", rowset_id)
3630
0
                        .tag("packed_file_path", packed_file_path)
3631
0
                        .tag("attempt", attempt);
3632
0
                return -1;
3633
0
            }
3634
0
            sleep_for_packed_file_retry();
3635
0
            continue;
3636
0
        }
3637
3638
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
3639
0
                .tag("instance_id", instance_id_)
3640
0
                .tag("tablet_id", tablet_id)
3641
0
                .tag("rowset_id", rowset_id)
3642
0
                .tag("packed_file_path", packed_file_path)
3643
0
                .tag("err", err);
3644
0
        return -1;
3645
0
    }
3646
3647
18.4E
    return -1;
3648
18.4E
}
3649
3650
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
3651
                                                const std::string& packed_key,
3652
7
                                                const cloud::PackedFileInfoPB& packed_info) {
3653
7
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
3654
0
        LOG_WARNING("packed file missing resource id when recycling")
3655
0
                .tag("instance_id", instance_id_)
3656
0
                .tag("packed_file_path", packed_file_path);
3657
0
        return -1;
3658
0
    }
3659
3660
7
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
3661
7
    if (!accessor) {
3662
0
        LOG_WARNING("no accessor available to delete packed file")
3663
0
                .tag("instance_id", instance_id_)
3664
0
                .tag("packed_file_path", packed_file_path)
3665
0
                .tag("resource_id", packed_info.resource_id());
3666
0
        return -1;
3667
0
    }
3668
3669
7
    int del_ret = accessor->delete_file(packed_file_path);
3670
7
    if (del_ret != 0 && del_ret != 1) {
3671
0
        LOG_WARNING("failed to delete packed file")
3672
0
                .tag("instance_id", instance_id_)
3673
0
                .tag("packed_file_path", packed_file_path)
3674
0
                .tag("resource_id", resource_id)
3675
0
                .tag("ret", del_ret);
3676
0
        return -1;
3677
0
    }
3678
7
    if (del_ret == 1) {
3679
0
        LOG_INFO("packed file already removed")
3680
0
                .tag("instance_id", instance_id_)
3681
0
                .tag("packed_file_path", packed_file_path)
3682
0
                .tag("resource_id", resource_id);
3683
7
    } else {
3684
7
        LOG_INFO("deleted packed file")
3685
7
                .tag("instance_id", instance_id_)
3686
7
                .tag("packed_file_path", packed_file_path)
3687
7
                .tag("resource_id", resource_id);
3688
7
    }
3689
3690
7
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
3691
7
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3692
7
        std::unique_ptr<Transaction> del_txn;
3693
7
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
3694
7
        if (err != TxnErrorCode::TXN_OK) {
3695
0
            LOG_WARNING("failed to create txn when removing packed file kv")
3696
0
                    .tag("instance_id", instance_id_)
3697
0
                    .tag("packed_file_path", packed_file_path)
3698
0
                    .tag("attempt", attempt)
3699
0
                    .tag("err", err);
3700
0
            return -1;
3701
0
        }
3702
3703
7
        std::string latest_val;
3704
7
        err = del_txn->get(packed_key, &latest_val);
3705
7
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3706
0
            return 0;
3707
0
        }
3708
7
        if (err != TxnErrorCode::TXN_OK) {
3709
0
            LOG_WARNING("failed to re-read packed file kv before removal")
3710
0
                    .tag("instance_id", instance_id_)
3711
0
                    .tag("packed_file_path", packed_file_path)
3712
0
                    .tag("attempt", attempt)
3713
0
                    .tag("err", err);
3714
0
            return -1;
3715
0
        }
3716
3717
7
        cloud::PackedFileInfoPB latest_info;
3718
7
        if (!latest_info.ParseFromString(latest_val)) {
3719
0
            LOG_WARNING("failed to parse packed file info before removal")
3720
0
                    .tag("instance_id", instance_id_)
3721
0
                    .tag("packed_file_path", packed_file_path)
3722
0
                    .tag("attempt", attempt);
3723
0
            return -1;
3724
0
        }
3725
3726
7
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
3727
7
              latest_info.ref_cnt() == 0)) {
3728
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
3729
0
                    .tag("instance_id", instance_id_)
3730
0
                    .tag("packed_file_path", packed_file_path)
3731
0
                    .tag("attempt", attempt);
3732
0
            return 0;
3733
0
        }
3734
3735
7
        del_txn->remove(packed_key);
3736
7
        err = del_txn->commit();
3737
7
        if (err == TxnErrorCode::TXN_OK) {
3738
7
            LOG_INFO("removed packed file metadata")
3739
7
                    .tag("instance_id", instance_id_)
3740
7
                    .tag("packed_file_path", packed_file_path);
3741
7
            return 0;
3742
7
        }
3743
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
3744
0
            if (attempt >= max_retry_times) {
3745
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
3746
0
                        .tag("instance_id", instance_id_)
3747
0
                        .tag("packed_file_path", packed_file_path)
3748
0
                        .tag("attempt", attempt);
3749
0
                return -1;
3750
0
            }
3751
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
3752
0
                    .tag("instance_id", instance_id_)
3753
0
                    .tag("packed_file_path", packed_file_path)
3754
0
                    .tag("attempt", attempt);
3755
0
            sleep_for_packed_file_retry();
3756
0
            continue;
3757
0
        }
3758
0
        LOG_WARNING("failed to remove packed file kv")
3759
0
                .tag("instance_id", instance_id_)
3760
0
                .tag("packed_file_path", packed_file_path)
3761
0
                .tag("attempt", attempt)
3762
0
                .tag("err", err);
3763
0
        return -1;
3764
0
    }
3765
0
    return -1;
3766
7
}
3767
3768
int InstanceRecycler::delete_rowset_data(
3769
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
3770
98
        RecyclerMetricsContext& metrics_context) {
3771
98
    int ret = 0;
3772
    // resource_id -> file_paths
3773
98
    std::map<std::string, std::vector<std::string>> resource_file_paths;
3774
    // (resource_id, tablet_id, rowset_id)
3775
98
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
3776
98
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
3777
3778
57.1k
    for (const auto& [_, rs] : rowsets) {
3779
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
3780
        // due to aborted schema change.
3781
57.1k
        if (is_formal_rowset) {
3782
3.15k
            std::lock_guard lock(recycled_tablets_mtx_);
3783
3.15k
            if (recycled_tablets_.count(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
3784
                // Tablet has been recycled and this rowset has no packed slices, so file data
3785
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
3786
                // slice info must still run to decrement packed file ref counts.
3787
0
                continue;
3788
0
            }
3789
3.15k
        }
3790
3791
57.1k
        int64_t num_segments = rs.num_segments();
3792
        // Check num_segments before accessor lookup, because empty rowsets
3793
        // (e.g. base compaction output of empty rowsets) may have no resource_id
3794
        // set. Skipping them early avoids a spurious "no such resource id" error
3795
        // that marks the entire batch as failed and prevents txn_remove from
3796
        // cleaning up recycle KV keys.
3797
57.1k
        if (num_segments <= 0) {
3798
0
            metrics_context.total_recycled_num++;
3799
0
            metrics_context.total_recycled_data_size += rs.total_disk_size();
3800
0
            continue;
3801
0
        }
3802
3803
57.1k
        auto it = accessor_map_.find(rs.resource_id());
3804
        // possible if the accessor is not initilized correctly
3805
57.1k
        if (it == accessor_map_.end()) [[unlikely]] {
3806
3.00k
            LOG_WARNING("instance has no such resource id")
3807
3.00k
                    .tag("instance_id", instance_id_)
3808
3.00k
                    .tag("resource_id", rs.resource_id());
3809
3.00k
            ret = -1;
3810
3.00k
            continue;
3811
3.00k
        }
3812
3813
54.1k
        auto& file_paths = resource_file_paths[rs.resource_id()];
3814
54.1k
        const auto& rowset_id = rs.rowset_id_v2();
3815
54.1k
        int64_t tablet_id = rs.tablet_id();
3816
54.1k
        LOG_INFO("recycle rowset merge index size")
3817
54.1k
                .tag("instance_id", instance_id_)
3818
54.1k
                .tag("tablet_id", tablet_id)
3819
54.1k
                .tag("rowset_id", rowset_id)
3820
54.1k
                .tag("merge_index_size", rs.packed_slice_locations_size());
3821
54.1k
        if (decrement_packed_file_ref_counts(rs) != 0) {
3822
0
            ret = -1;
3823
0
            continue;
3824
0
        }
3825
3826
        // Process delete bitmap - check where it's stored.
3827
54.1k
        DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3828
54.1k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3829
54.1k
                                                           &delete_bitmap_storage_type) != 0) {
3830
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3831
0
                    .tag("instance_id", instance_id_)
3832
0
                    .tag("tablet_id", tablet_id)
3833
0
                    .tag("rowset_id", rowset_id);
3834
0
            ret = -1;
3835
0
            continue;
3836
0
        }
3837
54.1k
        if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3838
51.5k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3839
51.5k
        }
3840
3841
        // Process inverted indexes
3842
54.1k
        std::vector<std::pair<int64_t, std::string>> index_ids;
3843
        // default format as v1.
3844
54.1k
        InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
3845
54.1k
        int inverted_index_get_ret = 0;
3846
54.1k
        if (rs.has_tablet_schema()) {
3847
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
3848
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3849
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3850
53.5k
                }
3851
53.5k
            }
3852
26.6k
            if (rs.tablet_schema().has_inverted_index_storage_format()) {
3853
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
3854
26.5k
            }
3855
27.5k
        } else {
3856
27.5k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
3857
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
3858
0
                                "instance_id="
3859
0
                             << instance_id_ << " tablet_id=" << tablet_id
3860
0
                             << " rowset_id=" << rowset_id;
3861
0
                ret = -1;
3862
0
                continue;
3863
0
            }
3864
27.5k
            InvertedIndexInfo index_info;
3865
27.5k
            inverted_index_get_ret =
3866
27.5k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
3867
27.5k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3868
27.5k
                                     &inverted_index_get_ret);
3869
27.5k
            if (inverted_index_get_ret == 0) {
3870
27.0k
                index_format = index_info.first;
3871
27.0k
                index_ids = index_info.second;
3872
27.0k
            } else if (inverted_index_get_ret == 1) {
3873
                // 1. Schema kv not found means tablet has been recycled
3874
                // Maybe some tablet recycle failed by some bugs
3875
                // We need to delete again to double check
3876
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3877
                // because we are uncertain about the inverted index information.
3878
                // If there are inverted indexes, some data might not be deleted,
3879
                // but this is acceptable as we have made our best effort to delete the data.
3880
503
                LOG_INFO(
3881
503
                        "delete rowset data schema kv not found, need to delete again to "
3882
503
                        "double "
3883
503
                        "check")
3884
503
                        .tag("instance_id", instance_id_)
3885
503
                        .tag("tablet_id", tablet_id)
3886
503
                        .tag("rowset", rs.ShortDebugString());
3887
                // Currently index_ids is guaranteed to be empty,
3888
                // but we clear it again here as a safeguard against future code changes
3889
                // that might cause index_ids to no longer be empty
3890
503
                index_format = InvertedIndexStorageFormatPB::V2;
3891
503
                index_ids.clear();
3892
18.4E
            } else {
3893
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
3894
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
3895
18.4E
                ret = -1;
3896
18.4E
                continue;
3897
18.4E
            }
3898
27.5k
        }
3899
54.2k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3900
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3901
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3902
5
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
3903
5
            continue;
3904
5
        }
3905
323k
        for (int64_t i = 0; i < num_segments; ++i) {
3906
268k
            file_paths.push_back(segment_path(tablet_id, rowset_id, i));
3907
268k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
3908
531k
                for (const auto& index_id : index_ids) {
3909
531k
                    file_paths.push_back(inverted_index_path_v1(tablet_id, rowset_id, i,
3910
531k
                                                                index_id.first, index_id.second));
3911
531k
                }
3912
266k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
3913
                // try to recycle inverted index v2 when get_ret == 1
3914
                // we treat schema not found as if it has a v2 format inverted index
3915
                // to reduce chance of data leakage
3916
2.50k
                if (inverted_index_get_ret == 1) {
3917
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
3918
2.50k
                            .tag("instance_id", instance_id_)
3919
2.50k
                            .tag("inverted index v2 path",
3920
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, i));
3921
2.50k
                }
3922
2.50k
                file_paths.push_back(inverted_index_path_v2(tablet_id, rowset_id, i));
3923
2.50k
            }
3924
268k
        }
3925
54.1k
    }
3926
3927
98
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
3928
98
                                                 "delete_rowset_data",
3929
98
                                                 [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clERKi
Line
Count
Source
3929
5
                                                 [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clERKi
Line
Count
Source
3929
51
                                                 [](const int& ret) { return ret != 0; });
3930
98
    for (auto& [resource_id, file_paths] : resource_file_paths) {
3931
51
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
3932
51
            DCHECK(accessor_map_.count(*rid))
3933
0
                    << "uninitilized accessor, instance_id=" << instance_id_
3934
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
3935
51
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
3936
51
                                     &accessor_map_);
3937
51
            if (!accessor_map_.contains(*rid)) {
3938
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
3939
0
                        .tag("resource_id", resource_id)
3940
0
                        .tag("instance_id", instance_id_);
3941
0
                return -1;
3942
0
            }
3943
51
            auto& accessor = accessor_map_[*rid];
3944
51
            int ret = accessor->delete_files(*paths);
3945
51
            if (!ret) {
3946
                // deduplication of different files with the same rowset id
3947
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
3948
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
3949
51
                std::set<std::string> deleted_rowset_id;
3950
3951
51
                std::for_each(paths->begin(), paths->end(),
3952
51
                              [&metrics_context, &rowsets, &deleted_rowset_id,
3953
857k
                               this](const std::string& path) {
3954
857k
                                  std::vector<std::string> str;
3955
857k
                                  butil::SplitString(path, '/', &str);
3956
857k
                                  std::string rowset_id;
3957
857k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3958
852k
                                      rowset_id = str.back().substr(0, pos);
3959
852k
                                  } else {
3960
5.27k
                                      if (path.find("packed_file/") != std::string::npos) {
3961
0
                                          return; // packed files do not have rowset_id encoded
3962
0
                                      }
3963
5.27k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3964
5.27k
                                      return;
3965
5.27k
                                  }
3966
852k
                                  auto rs_meta = rowsets.find(rowset_id);
3967
852k
                                  if (rs_meta != rowsets.end() &&
3968
858k
                                      !deleted_rowset_id.contains(rowset_id)) {
3969
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
3970
54.1k
                                      metrics_context.total_recycled_data_size +=
3971
54.1k
                                              rs_meta->second.total_disk_size();
3972
54.1k
                                      segment_metrics_context_.total_recycled_num +=
3973
54.1k
                                              rs_meta->second.num_segments();
3974
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
3975
54.1k
                                              rs_meta->second.total_disk_size();
3976
54.1k
                                      metrics_context.total_recycled_num++;
3977
54.1k
                                  }
3978
852k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
3953
7
                               this](const std::string& path) {
3954
7
                                  std::vector<std::string> str;
3955
7
                                  butil::SplitString(path, '/', &str);
3956
7
                                  std::string rowset_id;
3957
7
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3958
7
                                      rowset_id = str.back().substr(0, pos);
3959
7
                                  } else {
3960
0
                                      if (path.find("packed_file/") != std::string::npos) {
3961
0
                                          return; // packed files do not have rowset_id encoded
3962
0
                                      }
3963
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3964
0
                                      return;
3965
0
                                  }
3966
7
                                  auto rs_meta = rowsets.find(rowset_id);
3967
7
                                  if (rs_meta != rowsets.end() &&
3968
7
                                      !deleted_rowset_id.contains(rowset_id)) {
3969
7
                                      deleted_rowset_id.emplace(rowset_id);
3970
7
                                      metrics_context.total_recycled_data_size +=
3971
7
                                              rs_meta->second.total_disk_size();
3972
7
                                      segment_metrics_context_.total_recycled_num +=
3973
7
                                              rs_meta->second.num_segments();
3974
7
                                      segment_metrics_context_.total_recycled_data_size +=
3975
7
                                              rs_meta->second.total_disk_size();
3976
7
                                      metrics_context.total_recycled_num++;
3977
7
                                  }
3978
7
                              });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
3953
857k
                               this](const std::string& path) {
3954
857k
                                  std::vector<std::string> str;
3955
857k
                                  butil::SplitString(path, '/', &str);
3956
857k
                                  std::string rowset_id;
3957
857k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3958
852k
                                      rowset_id = str.back().substr(0, pos);
3959
852k
                                  } else {
3960
5.27k
                                      if (path.find("packed_file/") != std::string::npos) {
3961
0
                                          return; // packed files do not have rowset_id encoded
3962
0
                                      }
3963
5.27k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3964
5.27k
                                      return;
3965
5.27k
                                  }
3966
852k
                                  auto rs_meta = rowsets.find(rowset_id);
3967
852k
                                  if (rs_meta != rowsets.end() &&
3968
858k
                                      !deleted_rowset_id.contains(rowset_id)) {
3969
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
3970
54.1k
                                      metrics_context.total_recycled_data_size +=
3971
54.1k
                                              rs_meta->second.total_disk_size();
3972
54.1k
                                      segment_metrics_context_.total_recycled_num +=
3973
54.1k
                                              rs_meta->second.num_segments();
3974
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
3975
54.1k
                                              rs_meta->second.total_disk_size();
3976
54.1k
                                      metrics_context.total_recycled_num++;
3977
54.1k
                                  }
3978
852k
                              });
3979
51
            }
3980
51
            return ret;
3981
51
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
3931
5
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
3932
5
            DCHECK(accessor_map_.count(*rid))
3933
0
                    << "uninitilized accessor, instance_id=" << instance_id_
3934
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
3935
5
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
3936
5
                                     &accessor_map_);
3937
5
            if (!accessor_map_.contains(*rid)) {
3938
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
3939
0
                        .tag("resource_id", resource_id)
3940
0
                        .tag("instance_id", instance_id_);
3941
0
                return -1;
3942
0
            }
3943
5
            auto& accessor = accessor_map_[*rid];
3944
5
            int ret = accessor->delete_files(*paths);
3945
5
            if (!ret) {
3946
                // deduplication of different files with the same rowset id
3947
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
3948
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
3949
5
                std::set<std::string> deleted_rowset_id;
3950
3951
5
                std::for_each(paths->begin(), paths->end(),
3952
5
                              [&metrics_context, &rowsets, &deleted_rowset_id,
3953
5
                               this](const std::string& path) {
3954
5
                                  std::vector<std::string> str;
3955
5
                                  butil::SplitString(path, '/', &str);
3956
5
                                  std::string rowset_id;
3957
5
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3958
5
                                      rowset_id = str.back().substr(0, pos);
3959
5
                                  } else {
3960
5
                                      if (path.find("packed_file/") != std::string::npos) {
3961
5
                                          return; // packed files do not have rowset_id encoded
3962
5
                                      }
3963
5
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3964
5
                                      return;
3965
5
                                  }
3966
5
                                  auto rs_meta = rowsets.find(rowset_id);
3967
5
                                  if (rs_meta != rowsets.end() &&
3968
5
                                      !deleted_rowset_id.contains(rowset_id)) {
3969
5
                                      deleted_rowset_id.emplace(rowset_id);
3970
5
                                      metrics_context.total_recycled_data_size +=
3971
5
                                              rs_meta->second.total_disk_size();
3972
5
                                      segment_metrics_context_.total_recycled_num +=
3973
5
                                              rs_meta->second.num_segments();
3974
5
                                      segment_metrics_context_.total_recycled_data_size +=
3975
5
                                              rs_meta->second.total_disk_size();
3976
5
                                      metrics_context.total_recycled_num++;
3977
5
                                  }
3978
5
                              });
3979
5
            }
3980
5
            return ret;
3981
5
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
3931
46
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
3932
46
            DCHECK(accessor_map_.count(*rid))
3933
0
                    << "uninitilized accessor, instance_id=" << instance_id_
3934
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
3935
46
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
3936
46
                                     &accessor_map_);
3937
46
            if (!accessor_map_.contains(*rid)) {
3938
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
3939
0
                        .tag("resource_id", resource_id)
3940
0
                        .tag("instance_id", instance_id_);
3941
0
                return -1;
3942
0
            }
3943
46
            auto& accessor = accessor_map_[*rid];
3944
46
            int ret = accessor->delete_files(*paths);
3945
46
            if (!ret) {
3946
                // deduplication of different files with the same rowset id
3947
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
3948
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
3949
46
                std::set<std::string> deleted_rowset_id;
3950
3951
46
                std::for_each(paths->begin(), paths->end(),
3952
46
                              [&metrics_context, &rowsets, &deleted_rowset_id,
3953
46
                               this](const std::string& path) {
3954
46
                                  std::vector<std::string> str;
3955
46
                                  butil::SplitString(path, '/', &str);
3956
46
                                  std::string rowset_id;
3957
46
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3958
46
                                      rowset_id = str.back().substr(0, pos);
3959
46
                                  } else {
3960
46
                                      if (path.find("packed_file/") != std::string::npos) {
3961
46
                                          return; // packed files do not have rowset_id encoded
3962
46
                                      }
3963
46
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3964
46
                                      return;
3965
46
                                  }
3966
46
                                  auto rs_meta = rowsets.find(rowset_id);
3967
46
                                  if (rs_meta != rowsets.end() &&
3968
46
                                      !deleted_rowset_id.contains(rowset_id)) {
3969
46
                                      deleted_rowset_id.emplace(rowset_id);
3970
46
                                      metrics_context.total_recycled_data_size +=
3971
46
                                              rs_meta->second.total_disk_size();
3972
46
                                      segment_metrics_context_.total_recycled_num +=
3973
46
                                              rs_meta->second.num_segments();
3974
46
                                      segment_metrics_context_.total_recycled_data_size +=
3975
46
                                              rs_meta->second.total_disk_size();
3976
46
                                      metrics_context.total_recycled_num++;
3977
46
                                  }
3978
46
                              });
3979
46
            }
3980
46
            return ret;
3981
46
        });
3982
51
    }
3983
98
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
3984
5
        LOG_INFO(
3985
5
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
3986
5
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
3987
5
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
3988
5
        concurrent_delete_executor.add([&]() -> int {
3989
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
3990
5
            if (!ret) {
3991
5
                auto rs = rowsets.at(rowset_id);
3992
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
3993
5
                metrics_context.total_recycled_num++;
3994
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
3995
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
3996
5
            }
3997
5
            return ret;
3998
5
        });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_2clEv
Line
Count
Source
3988
5
        concurrent_delete_executor.add([&]() -> int {
3989
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
3990
5
            if (!ret) {
3991
5
                auto rs = rowsets.at(rowset_id);
3992
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
3993
5
                metrics_context.total_recycled_num++;
3994
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
3995
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
3996
5
            }
3997
5
            return ret;
3998
5
        });
3999
5
    }
4000
4001
98
    bool finished = true;
4002
98
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4003
98
    for (int r : rets) {
4004
56
        if (r != 0) {
4005
0
            ret = -1;
4006
0
            break;
4007
0
        }
4008
56
    }
4009
98
    ret = finished ? ret : -1;
4010
98
    return ret;
4011
98
}
4012
4013
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
4014
3.30k
                                         const std::string& rowset_id) {
4015
3.30k
    auto it = accessor_map_.find(resource_id);
4016
3.30k
    if (it == accessor_map_.end()) {
4017
400
        LOG_WARNING("instance has no such resource id")
4018
400
                .tag("instance_id", instance_id_)
4019
400
                .tag("resource_id", resource_id)
4020
400
                .tag("tablet_id", tablet_id)
4021
400
                .tag("rowset_id", rowset_id);
4022
400
        return -1;
4023
400
    }
4024
2.90k
    auto& accessor = it->second;
4025
2.90k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
4026
3.30k
}
4027
4028
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
4029
4
    if (key.empty()) {
4030
0
        return false;
4031
0
    }
4032
4
    std::string_view key_view = key;
4033
4
    key_view.remove_prefix(1); // remove keyspace prefix
4034
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
4035
4
    if (decode_key(&key_view, &decoded) != 0) {
4036
0
        return false;
4037
0
    }
4038
4
    if (decoded.size() < 4) {
4039
0
        return false;
4040
0
    }
4041
4
    try {
4042
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
4043
4
    } catch (const std::bad_variant_access&) {
4044
0
        return false;
4045
0
    }
4046
4
    return true;
4047
4
}
4048
4049
14
int InstanceRecycler::recycle_packed_files() {
4050
14
    const std::string task_name = "recycle_packed_files";
4051
14
    auto start_tp = steady_clock::now();
4052
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
4053
14
    int ret = 0;
4054
14
    PackedFileRecycleStats stats;
4055
4056
14
    register_recycle_task(task_name, start_time);
4057
14
    DORIS_CLOUD_DEFER {
4058
14
        unregister_recycle_task(task_name);
4059
14
        int64_t cost =
4060
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4061
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4062
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4063
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4064
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4065
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4066
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4067
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4068
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4069
14
                                                             stats.bytes_object_deleted);
4070
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4071
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4072
14
                .tag("instance_id", instance_id_)
4073
14
                .tag("num_scanned", stats.num_scanned)
4074
14
                .tag("num_corrected", stats.num_corrected)
4075
14
                .tag("num_deleted", stats.num_deleted)
4076
14
                .tag("num_failed", stats.num_failed)
4077
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4078
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4079
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4080
14
                .tag("bytes_deleted", stats.bytes_deleted)
4081
14
                .tag("ret", ret);
4082
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
4057
14
    DORIS_CLOUD_DEFER {
4058
14
        unregister_recycle_task(task_name);
4059
14
        int64_t cost =
4060
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4061
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4062
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4063
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4064
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4065
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4066
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4067
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4068
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4069
14
                                                             stats.bytes_object_deleted);
4070
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4071
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4072
14
                .tag("instance_id", instance_id_)
4073
14
                .tag("num_scanned", stats.num_scanned)
4074
14
                .tag("num_corrected", stats.num_corrected)
4075
14
                .tag("num_deleted", stats.num_deleted)
4076
14
                .tag("num_failed", stats.num_failed)
4077
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4078
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4079
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4080
14
                .tag("bytes_deleted", stats.bytes_deleted)
4081
14
                .tag("ret", ret);
4082
14
    };
4083
4084
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4085
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4086
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4087
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
4084
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4085
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4086
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4087
4
    };
4088
4089
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
4090
4091
14
    std::string begin = packed_file_key({instance_id_, ""});
4092
14
    std::string end = packed_file_key({instance_id_, "\xff"});
4093
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
4094
0
        ret = -1;
4095
0
    }
4096
4097
14
    return ret;
4098
14
}
4099
4100
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
4101
                                                  RecyclerMetricsContext& metrics_context,
4102
0
                                                  int64_t partition_id, bool is_empty_tablet) {
4103
0
    std::string tablet_key_begin, tablet_key_end;
4104
4105
0
    if (partition_id > 0) {
4106
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
4107
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
4108
0
    } else {
4109
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
4110
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
4111
0
    }
4112
    // for calculate the total num or bytes of recyled objects
4113
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
4114
0
                                                          std::string_view v) -> int {
4115
0
        doris::TabletMetaCloudPB tablet_meta_pb;
4116
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
4117
0
            return 0;
4118
0
        }
4119
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
4120
4121
0
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
4122
0
            return 0;
4123
0
        }
4124
4125
0
        if (!is_empty_tablet) {
4126
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
4127
0
                return 0;
4128
0
            }
4129
0
            tablet_metrics_context_.total_need_recycle_num++;
4130
0
        }
4131
0
        return 0;
4132
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_
4133
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
4134
0
    metrics_context.report(true);
4135
0
    tablet_metrics_context_.report(true);
4136
0
    segment_metrics_context_.report(true);
4137
0
    return ret;
4138
0
}
4139
4140
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
4141
0
                                                 RecyclerMetricsContext& metrics_context) {
4142
0
    int ret = 0;
4143
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
4144
0
    std::unique_ptr<Transaction> txn;
4145
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4146
0
        LOG_WARNING("failed to recycle tablet ")
4147
0
                .tag("tablet id", tablet_id)
4148
0
                .tag("instance_id", instance_id_)
4149
0
                .tag("reason", "failed to create txn");
4150
0
        ret = -1;
4151
0
    }
4152
0
    GetRowsetResponse resp;
4153
0
    std::string msg;
4154
0
    MetaServiceCode code = MetaServiceCode::OK;
4155
    // get rowsets in tablet
4156
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4157
0
                        tablet_id, code, msg, &resp);
4158
0
    if (code != MetaServiceCode::OK) {
4159
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4160
0
                .tag("tablet id", tablet_id)
4161
0
                .tag("msg", msg)
4162
0
                .tag("code", code)
4163
0
                .tag("instance id", instance_id_);
4164
0
        ret = -1;
4165
0
    }
4166
0
    for (const auto& rs_meta : resp.rowset_meta()) {
4167
        /*
4168
        * For compatibility, we skip the loop for [0-1] here.
4169
        * The purpose of this loop is to delete object files,
4170
        * and since [0-1] only has meta and doesn't have object files,
4171
        * skipping it doesn't affect system correctness.
4172
        *
4173
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
4174
        * would return error -1 directly, causing the recycle operation to fail.
4175
        *
4176
        * [0-1] doesn't have resource id is a bug.
4177
        * In the future, we will fix this problem, after that,
4178
        * we can remove this if statement.
4179
        *
4180
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
4181
        */
4182
4183
0
        if (rs_meta.end_version() == 1) {
4184
            // Assert that [0-1] has no resource_id to make sure
4185
            // this if statement will not be forgetted to remove
4186
            // when the resource id bug is fixed
4187
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4188
0
            continue;
4189
0
        }
4190
0
        if (!rs_meta.has_resource_id()) {
4191
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4192
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4193
0
                    .tag("instance_id", instance_id_)
4194
0
                    .tag("tablet_id", tablet_id);
4195
0
            continue;
4196
0
        }
4197
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4198
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4199
        // possible if the accessor is not initilized correctly
4200
0
        if (it == accessor_map_.end()) [[unlikely]] {
4201
0
            LOG_WARNING(
4202
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4203
0
                    "recycle process")
4204
0
                    .tag("tablet id", tablet_id)
4205
0
                    .tag("instance_id", instance_id_)
4206
0
                    .tag("resource_id", rs_meta.resource_id())
4207
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4208
0
            continue;
4209
0
        }
4210
4211
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
4212
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4213
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4214
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
4215
0
    }
4216
0
    return ret;
4217
0
}
4218
4219
4.25k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
4220
4.25k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
4221
4.25k
            .tag("instance_id", instance_id_)
4222
4.25k
            .tag("tablet_id", tablet_id);
4223
4224
4.25k
    if (should_recycle_versioned_keys()) {
4225
11
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
4226
11
        if (ret != 0) {
4227
0
            return ret;
4228
0
        }
4229
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
4230
        // during the recycle_versioned_tablet process.
4231
        //
4232
        // .. And remove restore job rowsets of this tablet too
4233
11
    }
4234
4235
4.25k
    int ret = 0;
4236
4.25k
    auto start_time = steady_clock::now();
4237
4238
4.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4239
4240
    // collect resource ids
4241
248
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4242
248
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4243
248
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4244
248
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4245
248
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
4246
248
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
4247
4248
248
    std::set<std::string> resource_ids;
4249
248
    int64_t recycle_rowsets_number = 0;
4250
248
    int64_t recycle_segments_number = 0;
4251
248
    int64_t recycle_rowsets_data_size = 0;
4252
248
    int64_t recycle_rowsets_index_size = 0;
4253
248
    int64_t recycle_restore_job_rowsets_number = 0;
4254
248
    int64_t recycle_restore_job_segments_number = 0;
4255
248
    int64_t recycle_restore_job_rowsets_data_size = 0;
4256
248
    int64_t recycle_restore_job_rowsets_index_size = 0;
4257
248
    int64_t max_rowset_version = 0;
4258
248
    int64_t min_rowset_creation_time = INT64_MAX;
4259
248
    int64_t max_rowset_creation_time = 0;
4260
248
    int64_t min_rowset_expiration_time = INT64_MAX;
4261
248
    int64_t max_rowset_expiration_time = 0;
4262
4263
248
    DORIS_CLOUD_DEFER {
4264
248
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4265
248
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4266
248
                .tag("instance_id", instance_id_)
4267
248
                .tag("tablet_id", tablet_id)
4268
248
                .tag("recycle rowsets number", recycle_rowsets_number)
4269
248
                .tag("recycle segments number", recycle_segments_number)
4270
248
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4271
248
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4272
248
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4273
248
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4274
248
                .tag("all restore job rowsets recycle data size",
4275
248
                     recycle_restore_job_rowsets_data_size)
4276
248
                .tag("all restore job rowsets recycle index size",
4277
248
                     recycle_restore_job_rowsets_index_size)
4278
248
                .tag("max rowset version", max_rowset_version)
4279
248
                .tag("min rowset creation time", min_rowset_creation_time)
4280
248
                .tag("max rowset creation time", max_rowset_creation_time)
4281
248
                .tag("min rowset expiration time", min_rowset_expiration_time)
4282
248
                .tag("max rowset expiration time", max_rowset_expiration_time)
4283
248
                .tag("task type", metrics_context.operation_type)
4284
248
                .tag("ret", ret);
4285
248
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4263
248
    DORIS_CLOUD_DEFER {
4264
248
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4265
248
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4266
248
                .tag("instance_id", instance_id_)
4267
248
                .tag("tablet_id", tablet_id)
4268
248
                .tag("recycle rowsets number", recycle_rowsets_number)
4269
248
                .tag("recycle segments number", recycle_segments_number)
4270
248
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4271
248
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4272
248
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4273
248
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4274
248
                .tag("all restore job rowsets recycle data size",
4275
248
                     recycle_restore_job_rowsets_data_size)
4276
248
                .tag("all restore job rowsets recycle index size",
4277
248
                     recycle_restore_job_rowsets_index_size)
4278
248
                .tag("max rowset version", max_rowset_version)
4279
248
                .tag("min rowset creation time", min_rowset_creation_time)
4280
248
                .tag("max rowset creation time", max_rowset_creation_time)
4281
248
                .tag("min rowset expiration time", min_rowset_expiration_time)
4282
248
                .tag("max rowset expiration time", max_rowset_expiration_time)
4283
248
                .tag("task type", metrics_context.operation_type)
4284
248
                .tag("ret", ret);
4285
248
    };
4286
4287
248
    std::unique_ptr<Transaction> txn;
4288
248
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4289
0
        LOG_WARNING("failed to recycle tablet ")
4290
0
                .tag("tablet id", tablet_id)
4291
0
                .tag("instance_id", instance_id_)
4292
0
                .tag("reason", "failed to create txn");
4293
0
        ret = -1;
4294
0
    }
4295
248
    GetRowsetResponse resp;
4296
248
    std::string msg;
4297
248
    MetaServiceCode code = MetaServiceCode::OK;
4298
    // get rowsets in tablet
4299
248
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4300
248
                        tablet_id, code, msg, &resp);
4301
248
    if (code != MetaServiceCode::OK) {
4302
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4303
0
                .tag("tablet id", tablet_id)
4304
0
                .tag("msg", msg)
4305
0
                .tag("code", code)
4306
0
                .tag("instance id", instance_id_);
4307
0
        ret = -1;
4308
0
    }
4309
248
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
4310
4311
2.51k
    for (const auto& rs_meta : resp.rowset_meta()) {
4312
        // The rowset has no resource id and segments when it was generated by compaction
4313
        // with multiple hole rowsets or it's version is [0-1], so we can skip it.
4314
2.51k
        if (!rs_meta.has_resource_id() && rs_meta.num_segments() == 0) {
4315
0
            LOG_INFO("rowset meta does not have a resource id and no segments, skip this rowset")
4316
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4317
0
                    .tag("instance_id", instance_id_)
4318
0
                    .tag("tablet_id", tablet_id);
4319
0
            recycle_rowsets_number += 1;
4320
0
            continue;
4321
0
        }
4322
2.51k
        if (!rs_meta.has_resource_id()) {
4323
1
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4324
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
4325
1
                    .tag("instance_id", instance_id_)
4326
1
                    .tag("tablet_id", tablet_id);
4327
1
            return -1;
4328
1
        }
4329
18.4E
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4330
2.51k
        auto it = accessor_map_.find(rs_meta.resource_id());
4331
        // possible if the accessor is not initilized correctly
4332
2.51k
        if (it == accessor_map_.end()) [[unlikely]] {
4333
1
            LOG_WARNING(
4334
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4335
1
                    "recycle process")
4336
1
                    .tag("tablet id", tablet_id)
4337
1
                    .tag("instance_id", instance_id_)
4338
1
                    .tag("resource_id", rs_meta.resource_id())
4339
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4340
1
            return -1;
4341
1
        }
4342
2.51k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4343
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
4344
0
                    .tag("instance_id", instance_id_)
4345
0
                    .tag("tablet_id", tablet_id)
4346
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4347
0
            return -1;
4348
0
        }
4349
2.51k
        recycle_rowsets_number += 1;
4350
2.51k
        recycle_segments_number += rs_meta.num_segments();
4351
2.51k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4352
2.51k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4353
2.51k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4354
2.51k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4355
2.51k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4356
2.51k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4357
2.51k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4358
2.51k
        resource_ids.emplace(rs_meta.resource_id());
4359
2.51k
    }
4360
4361
    // get restore job rowset in tablet
4362
246
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
4363
246
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
4364
246
    if (code != MetaServiceCode::OK) {
4365
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
4366
0
                .tag("tablet id", tablet_id)
4367
0
                .tag("msg", msg)
4368
0
                .tag("code", code)
4369
0
                .tag("instance id", instance_id_);
4370
0
        return -1;
4371
0
    }
4372
4373
246
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
4374
0
        if (!rs_meta.has_resource_id()) {
4375
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4376
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4377
0
                    .tag("instance_id", instance_id_)
4378
0
                    .tag("tablet_id", tablet_id);
4379
0
            return -1;
4380
0
        }
4381
4382
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4383
        // possible if the accessor is not initilized correctly
4384
0
        if (it == accessor_map_.end()) [[unlikely]] {
4385
0
            LOG_WARNING(
4386
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4387
0
                    "recycle process")
4388
0
                    .tag("tablet id", tablet_id)
4389
0
                    .tag("instance_id", instance_id_)
4390
0
                    .tag("resource_id", rs_meta.resource_id())
4391
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4392
0
            return -1;
4393
0
        }
4394
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4395
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
4396
0
                    .tag("instance_id", instance_id_)
4397
0
                    .tag("tablet_id", tablet_id)
4398
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4399
0
            return -1;
4400
0
        }
4401
0
        recycle_restore_job_rowsets_number += 1;
4402
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
4403
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
4404
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
4405
0
        resource_ids.emplace(rs_meta.resource_id());
4406
0
    }
4407
4408
246
    LOG_INFO("recycle tablet start to delete object")
4409
246
            .tag("instance id", instance_id_)
4410
246
            .tag("tablet id", tablet_id)
4411
246
            .tag("recycle tablet resource ids are",
4412
246
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
4413
246
                                 [](std::string rs_id, const auto& it) {
4414
206
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4415
206
                                 }));
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
4413
206
                                 [](std::string rs_id, const auto& it) {
4414
206
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4415
206
                                 }));
4416
4417
246
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
4418
246
            _thread_pool_group.s3_producer_pool,
4419
246
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4420
246
            [](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
4420
206
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
4421
4422
    // delete all rowset data in this tablet
4423
    // ATTN: there may be data leak if not all accessor initilized successfully
4424
    //       partial data deleted if the tablet is stored cross-storage vault
4425
    //       vault id is not attached to TabletMeta...
4426
246
    for (const auto& resource_id : resource_ids) {
4427
206
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
4428
206
        concurrent_delete_executor.add(
4429
206
                [&, rs_id = resource_id,
4430
206
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4431
206
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4432
206
                    if (res != 0) {
4433
2
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4434
2
                                     << " path=" << accessor_ptr->uri()
4435
2
                                     << " task type=" << metrics_context.operation_type;
4436
2
                        return std::make_pair(-1, rs_id);
4437
2
                    }
4438
204
                    return std::make_pair(0, rs_id);
4439
206
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
4430
206
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4431
206
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4432
206
                    if (res != 0) {
4433
2
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4434
2
                                     << " path=" << accessor_ptr->uri()
4435
2
                                     << " task type=" << metrics_context.operation_type;
4436
2
                        return std::make_pair(-1, rs_id);
4437
2
                    }
4438
204
                    return std::make_pair(0, rs_id);
4439
206
                });
4440
206
    }
4441
4442
246
    bool finished = true;
4443
246
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
4444
246
    for (auto& r : rets) {
4445
206
        if (r.first != 0) {
4446
2
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
4447
2
            ret = -1;
4448
2
        }
4449
206
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
4450
206
    }
4451
246
    ret = finished ? ret : -1;
4452
4453
246
    if (ret != 0) { // failed recycle tablet data
4454
2
        LOG_WARNING("ret!=0")
4455
2
                .tag("finished", finished)
4456
2
                .tag("ret", ret)
4457
2
                .tag("instance_id", instance_id_)
4458
2
                .tag("tablet_id", tablet_id);
4459
2
        return ret;
4460
2
    }
4461
4462
244
    tablet_metrics_context_.total_recycled_data_size +=
4463
244
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4464
244
    tablet_metrics_context_.total_recycled_num += 1;
4465
244
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
4466
244
    segment_metrics_context_.total_recycled_data_size +=
4467
244
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4468
244
    metrics_context.total_recycled_data_size +=
4469
244
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4470
244
    tablet_metrics_context_.report();
4471
244
    segment_metrics_context_.report();
4472
244
    metrics_context.report();
4473
4474
244
    txn.reset();
4475
244
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4476
0
        LOG_WARNING("failed to recycle tablet ")
4477
0
                .tag("tablet id", tablet_id)
4478
0
                .tag("instance_id", instance_id_)
4479
0
                .tag("reason", "failed to create txn");
4480
0
        ret = -1;
4481
0
    }
4482
    // delete all rowset kv in this tablet
4483
244
    txn->remove(rs_key0, rs_key1);
4484
244
    txn->remove(recyc_rs_key0, recyc_rs_key1);
4485
244
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
4486
4487
    // remove delete bitmap for MoW table
4488
244
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
4489
244
    txn->remove(pending_key);
4490
244
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
4491
244
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
4492
244
    txn->remove(delete_bitmap_start, delete_bitmap_end);
4493
4494
244
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
4495
244
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
4496
244
    txn->remove(dbm_start_key, dbm_end_key);
4497
244
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
4498
244
              << " end=" << hex(dbm_end_key);
4499
4500
244
    TxnErrorCode err = txn->commit();
4501
244
    if (err != TxnErrorCode::TXN_OK) {
4502
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
4503
0
        ret = -1;
4504
0
    }
4505
4506
244
    if (ret == 0) {
4507
        // All object files under tablet have been deleted
4508
244
        std::lock_guard lock(recycled_tablets_mtx_);
4509
244
        recycled_tablets_.insert(tablet_id);
4510
244
    }
4511
4512
244
    return ret;
4513
246
}
4514
4515
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
4516
11
                                               RecyclerMetricsContext& metrics_context) {
4517
11
    int ret = 0;
4518
11
    auto start_time = steady_clock::now();
4519
4520
11
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4521
4522
    // collect resource ids
4523
11
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4524
11
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4525
11
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4526
11
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4527
4528
11
    int64_t recycle_rowsets_number = 0;
4529
11
    int64_t recycle_segments_number = 0;
4530
11
    int64_t recycle_rowsets_data_size = 0;
4531
11
    int64_t recycle_rowsets_index_size = 0;
4532
11
    int64_t max_rowset_version = 0;
4533
11
    int64_t min_rowset_creation_time = INT64_MAX;
4534
11
    int64_t max_rowset_creation_time = 0;
4535
11
    int64_t min_rowset_expiration_time = INT64_MAX;
4536
11
    int64_t max_rowset_expiration_time = 0;
4537
4538
11
    DORIS_CLOUD_DEFER {
4539
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4540
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4541
11
                .tag("instance_id", instance_id_)
4542
11
                .tag("tablet_id", tablet_id)
4543
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4544
11
                .tag("recycle segments number", recycle_segments_number)
4545
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4546
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4547
11
                .tag("max rowset version", max_rowset_version)
4548
11
                .tag("min rowset creation time", min_rowset_creation_time)
4549
11
                .tag("max rowset creation time", max_rowset_creation_time)
4550
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4551
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4552
11
                .tag("ret", ret);
4553
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4538
11
    DORIS_CLOUD_DEFER {
4539
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4540
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4541
11
                .tag("instance_id", instance_id_)
4542
11
                .tag("tablet_id", tablet_id)
4543
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4544
11
                .tag("recycle segments number", recycle_segments_number)
4545
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4546
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4547
11
                .tag("max rowset version", max_rowset_version)
4548
11
                .tag("min rowset creation time", min_rowset_creation_time)
4549
11
                .tag("max rowset creation time", max_rowset_creation_time)
4550
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4551
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4552
11
                .tag("ret", ret);
4553
11
    };
4554
4555
11
    std::unique_ptr<Transaction> txn;
4556
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4557
0
        LOG_WARNING("failed to recycle tablet ")
4558
0
                .tag("tablet id", tablet_id)
4559
0
                .tag("instance_id", instance_id_)
4560
0
                .tag("reason", "failed to create txn");
4561
0
        ret = -1;
4562
0
    }
4563
4564
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
4565
    // by the related operation logs.
4566
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
4567
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
4568
11
    MetaReader meta_reader(instance_id_);
4569
11
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
4570
11
    if (err == TxnErrorCode::TXN_OK) {
4571
11
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
4572
11
    }
4573
11
    if (err != TxnErrorCode::TXN_OK) {
4574
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4575
0
                .tag("tablet id", tablet_id)
4576
0
                .tag("err", err)
4577
0
                .tag("instance id", instance_id_);
4578
0
        ret = -1;
4579
0
    }
4580
4581
11
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
4582
11
             load_rowset_metas.size(), compact_rowset_metas.size())
4583
11
            .tag("instance_id", instance_id_)
4584
11
            .tag("tablet_id", tablet_id);
4585
4586
11
    SyncExecutor<int> concurrent_delete_executor(
4587
11
            _thread_pool_group.s3_producer_pool,
4588
11
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4589
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
4590
4591
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
4592
60
        recycle_rowsets_number += 1;
4593
60
        recycle_segments_number += rs_meta.num_segments();
4594
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4595
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4596
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4597
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4598
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4599
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4600
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4601
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
4591
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
4592
60
        recycle_rowsets_number += 1;
4593
60
        recycle_segments_number += rs_meta.num_segments();
4594
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4595
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4596
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4597
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4598
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4599
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4600
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4601
60
    };
4602
4603
11
    std::vector<RowsetDeleteTask> all_tasks;
4604
60
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
4605
60
        update_rowset_stats(rs_meta);
4606
        // Version 0-1 rowset has no resource_id and no actual data files,
4607
        // but still needs ref_count key cleanup, so we add it to all_tasks.
4608
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
4609
60
        RowsetDeleteTask task;
4610
60
        task.rowset_meta = rs_meta;
4611
60
        task.versioned_rowset_key =
4612
60
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
4613
60
        task.non_versioned_rowset_key =
4614
60
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
4615
60
        task.versionstamp = versionstamp;
4616
60
        all_tasks.push_back(std::move(task));
4617
60
    }
4618
4619
11
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
4620
0
        update_rowset_stats(rs_meta);
4621
        // Version 0-1 rowset has no resource_id and no actual data files,
4622
        // but still needs ref_count key cleanup, so we add it to all_tasks.
4623
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
4624
0
        RowsetDeleteTask task;
4625
0
        task.rowset_meta = rs_meta;
4626
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
4627
0
                {instance_id_, tablet_id, rs_meta.end_version()});
4628
0
        task.non_versioned_rowset_key =
4629
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
4630
0
        task.versionstamp = versionstamp;
4631
0
        all_tasks.push_back(std::move(task));
4632
0
    }
4633
4634
11
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
4635
0
        RecycleRowsetPB recycle_rowset;
4636
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
4637
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4638
0
            return -1;
4639
0
        }
4640
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
4641
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
4642
                // in old version, keep this key-value pair and it needs to be checked manually
4643
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4644
0
                return -1;
4645
0
            }
4646
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
4647
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
4648
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
4649
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
4650
0
                return -1;
4651
0
            }
4652
            // decode rowset_id
4653
0
            auto k1 = k;
4654
0
            k1.remove_prefix(1);
4655
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
4656
0
            decode_key(&k1, &out);
4657
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
4658
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
4659
0
            LOG_INFO("delete old-version rowset data")
4660
0
                    .tag("instance_id", instance_id_)
4661
0
                    .tag("tablet_id", tablet_id)
4662
0
                    .tag("rowset_id", rowset_id);
4663
4664
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
4665
            // so we must use prefix deletion directly instead of batch delete.
4666
0
            concurrent_delete_executor.add(
4667
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
4668
                        // delete by prefix, the recycle rowset key will be deleted by range later.
4669
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
4670
0
                    });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Unexecuted instantiation: recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
4671
0
        } else {
4672
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
4673
            // Version 0-1 rowset has no resource_id and no actual data files,
4674
            // but still needs ref_count key cleanup, so we add it to all_tasks.
4675
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
4676
0
            RowsetDeleteTask task;
4677
0
            task.rowset_meta = rowset_meta;
4678
0
            task.recycle_rowset_key = k;
4679
0
            all_tasks.push_back(std::move(task));
4680
0
        }
4681
0
        return 0;
4682
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
4683
4684
11
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
4685
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
4686
0
                .tag("tablet id", tablet_id)
4687
0
                .tag("instance_id", instance_id_)
4688
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
4689
0
        ret = -1;
4690
0
    }
4691
4692
    // Phase 1: Classify tasks by ref_count
4693
11
    std::vector<RowsetDeleteTask> batch_delete_tasks;
4694
60
    for (auto& task : all_tasks) {
4695
60
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
4696
60
        if (classify_ret < 0) {
4697
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
4698
0
                    .tag("instance_id", instance_id_)
4699
0
                    .tag("tablet_id", tablet_id)
4700
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
4701
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
4702
0
                return recycle_rowset_meta_and_data(t);
4703
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_4clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_4clEv
4704
0
        }
4705
60
    }
4706
4707
11
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
4708
4709
11
    LOG_INFO("batch delete plan created")
4710
11
            .tag("instance_id", instance_id_)
4711
11
            .tag("tablet_id", tablet_id)
4712
11
            .tag("plan_count", batch_delete_tasks.size());
4713
4714
    // Phase 2: Execute batch delete using existing delete_rowset_data
4715
11
    if (!batch_delete_tasks.empty()) {
4716
10
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
4717
49
        for (const auto& task : batch_delete_tasks) {
4718
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
4719
49
            if (task.rowset_meta.resource_id().empty()) {
4720
10
                LOG_INFO("skip rowset with empty resource_id in batch delete")
4721
10
                        .tag("instance_id", instance_id_)
4722
10
                        .tag("tablet_id", tablet_id)
4723
10
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
4724
10
                continue;
4725
10
            }
4726
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
4727
39
        }
4728
4729
        // Only call delete_rowset_data if there are rowsets with actual data to delete
4730
10
        bool delete_success = true;
4731
10
        if (!rowsets_to_delete.empty()) {
4732
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
4733
9
                                                         "batch_delete_versioned_tablet");
4734
9
            int delete_ret = delete_rowset_data(
4735
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
4736
9
            if (delete_ret != 0) {
4737
0
                LOG_WARNING("batch delete execution failed")
4738
0
                        .tag("instance_id", instance_id_)
4739
0
                        .tag("tablet_id", tablet_id);
4740
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
4741
0
                ret = -1;
4742
0
                delete_success = false;
4743
0
            }
4744
9
        }
4745
4746
        // Phase 3: Only cleanup metadata if data deletion succeeded.
4747
        // If deletion failed, keep recycle_rowset_key so next round will retry.
4748
10
        if (delete_success) {
4749
10
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
4750
10
            if (cleanup_ret != 0) {
4751
0
                LOG_WARNING("batch delete cleanup failed")
4752
0
                        .tag("instance_id", instance_id_)
4753
0
                        .tag("tablet_id", tablet_id);
4754
0
                ret = -1;
4755
0
            }
4756
10
        }
4757
10
    }
4758
4759
    // Always wait for fallback tasks to complete before returning
4760
11
    bool finished = true;
4761
11
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4762
11
    for (int r : rets) {
4763
0
        if (r != 0) {
4764
0
            ret = -1;
4765
0
        }
4766
0
    }
4767
4768
11
    ret = finished ? ret : -1;
4769
4770
11
    if (ret != 0) { // failed recycle tablet data
4771
0
        LOG_WARNING("recycle versioned tablet failed")
4772
0
                .tag("finished", finished)
4773
0
                .tag("ret", ret)
4774
0
                .tag("instance_id", instance_id_)
4775
0
                .tag("tablet_id", tablet_id);
4776
0
        return ret;
4777
0
    }
4778
4779
11
    tablet_metrics_context_.total_recycled_data_size +=
4780
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4781
11
    tablet_metrics_context_.total_recycled_num += 1;
4782
11
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
4783
11
    segment_metrics_context_.total_recycled_data_size +=
4784
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4785
11
    metrics_context.total_recycled_data_size +=
4786
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4787
11
    tablet_metrics_context_.report();
4788
11
    segment_metrics_context_.report();
4789
11
    metrics_context.report();
4790
4791
11
    txn.reset();
4792
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4793
0
        LOG_WARNING("failed to recycle tablet ")
4794
0
                .tag("tablet id", tablet_id)
4795
0
                .tag("instance_id", instance_id_)
4796
0
                .tag("reason", "failed to create txn");
4797
0
        ret = -1;
4798
0
    }
4799
    // delete all rowset kv in this tablet
4800
11
    txn->remove(rs_key0, rs_key1);
4801
11
    txn->remove(recyc_rs_key0, recyc_rs_key1);
4802
4803
    // remove delete bitmap for MoW table
4804
11
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
4805
11
    txn->remove(pending_key);
4806
11
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
4807
11
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
4808
11
    txn->remove(delete_bitmap_start, delete_bitmap_end);
4809
4810
11
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
4811
11
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
4812
11
    txn->remove(dbm_start_key, dbm_end_key);
4813
11
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
4814
11
              << " end=" << hex(dbm_end_key);
4815
4816
11
    std::string versioned_idx_key = versioned::tablet_index_key({instance_id_, tablet_id});
4817
11
    std::string tablet_index_val;
4818
11
    err = txn->get(versioned_idx_key, &tablet_index_val);
4819
11
    if (err != TxnErrorCode::TXN_KEY_NOT_FOUND && err != TxnErrorCode::TXN_OK) {
4820
0
        LOG_WARNING("failed to get tablet index kv")
4821
0
                .tag("instance_id", instance_id_)
4822
0
                .tag("tablet_id", tablet_id)
4823
0
                .tag("err", err);
4824
0
        ret = -1;
4825
11
    } else if (err == TxnErrorCode::TXN_OK) {
4826
        // If the tablet index kv exists, we need to delete it
4827
10
        TabletIndexPB tablet_index_pb;
4828
10
        if (!tablet_index_pb.ParseFromString(tablet_index_val)) {
4829
0
            LOG_WARNING("failed to parse tablet index pb")
4830
0
                    .tag("instance_id", instance_id_)
4831
0
                    .tag("tablet_id", tablet_id);
4832
0
            ret = -1;
4833
10
        } else {
4834
10
            std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
4835
10
                    {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
4836
10
                     tablet_index_pb.index_id(), tablet_index_pb.partition_id(), tablet_id});
4837
10
            txn->remove(versioned_inverted_idx_key);
4838
10
            txn->remove(versioned_idx_key);
4839
10
        }
4840
10
    }
4841
4842
11
    err = txn->commit();
4843
11
    if (err != TxnErrorCode::TXN_OK) {
4844
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
4845
0
        ret = -1;
4846
0
    }
4847
4848
11
    if (ret == 0) {
4849
        // All object files under tablet have been deleted
4850
11
        std::lock_guard lock(recycled_tablets_mtx_);
4851
11
        recycled_tablets_.insert(tablet_id);
4852
11
    }
4853
4854
11
    return ret;
4855
11
}
4856
4857
27
int InstanceRecycler::recycle_rowsets() {
4858
27
    if (should_recycle_versioned_keys()) {
4859
5
        return recycle_versioned_rowsets();
4860
5
    }
4861
4862
22
    const std::string task_name = "recycle_rowsets";
4863
22
    int64_t num_scanned = 0;
4864
22
    int64_t num_expired = 0;
4865
22
    int64_t num_prepare = 0;
4866
22
    int64_t num_compacted = 0;
4867
22
    int64_t num_empty_rowset = 0;
4868
22
    size_t total_rowset_key_size = 0;
4869
22
    size_t total_rowset_value_size = 0;
4870
22
    size_t expired_rowset_size = 0;
4871
22
    std::atomic_long num_recycled = 0;
4872
22
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
4873
4874
22
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
4875
22
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
4876
22
    std::string recyc_rs_key0;
4877
22
    std::string recyc_rs_key1;
4878
22
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
4879
22
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
4880
4881
22
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
4882
4883
22
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
4884
22
    register_recycle_task(task_name, start_time);
4885
4886
22
    DORIS_CLOUD_DEFER {
4887
22
        unregister_recycle_task(task_name);
4888
22
        int64_t cost =
4889
22
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4890
22
        metrics_context.finish_report();
4891
22
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
4892
22
                .tag("instance_id", instance_id_)
4893
22
                .tag("num_scanned", num_scanned)
4894
22
                .tag("num_expired", num_expired)
4895
22
                .tag("num_recycled", num_recycled)
4896
22
                .tag("num_recycled.prepare", num_prepare)
4897
22
                .tag("num_recycled.compacted", num_compacted)
4898
22
                .tag("num_recycled.empty_rowset", num_empty_rowset)
4899
22
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
4900
22
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
4901
22
                .tag("expired_rowset_meta_size", expired_rowset_size);
4902
22
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
4886
7
    DORIS_CLOUD_DEFER {
4887
7
        unregister_recycle_task(task_name);
4888
7
        int64_t cost =
4889
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4890
7
        metrics_context.finish_report();
4891
7
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
4892
7
                .tag("instance_id", instance_id_)
4893
7
                .tag("num_scanned", num_scanned)
4894
7
                .tag("num_expired", num_expired)
4895
7
                .tag("num_recycled", num_recycled)
4896
7
                .tag("num_recycled.prepare", num_prepare)
4897
7
                .tag("num_recycled.compacted", num_compacted)
4898
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
4899
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
4900
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
4901
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
4902
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
4886
15
    DORIS_CLOUD_DEFER {
4887
15
        unregister_recycle_task(task_name);
4888
15
        int64_t cost =
4889
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4890
15
        metrics_context.finish_report();
4891
15
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
4892
15
                .tag("instance_id", instance_id_)
4893
15
                .tag("num_scanned", num_scanned)
4894
15
                .tag("num_expired", num_expired)
4895
15
                .tag("num_recycled", num_recycled)
4896
15
                .tag("num_recycled.prepare", num_prepare)
4897
15
                .tag("num_recycled.compacted", num_compacted)
4898
15
                .tag("num_recycled.empty_rowset", num_empty_rowset)
4899
15
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
4900
15
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
4901
15
                .tag("expired_rowset_meta_size", expired_rowset_size);
4902
15
    };
4903
4904
22
    std::vector<std::string> rowset_keys;
4905
22
    std::vector<std::string> rowset_keys_to_mark_recycled;
4906
22
    std::vector<std::string> rowset_keys_to_abort;
4907
22
    std::vector<std::string> prepare_rowset_keys_to_delete;
4908
    // rowset_id -> rowset_meta
4909
    // store rowset id and meta for statistics rs size when delete
4910
22
    std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
4911
4912
    // Store keys of rowset recycled by background workers
4913
22
    std::mutex async_recycled_rowset_keys_mutex;
4914
22
    std::vector<std::string> async_recycled_rowset_keys;
4915
22
    auto worker_pool = std::make_unique<SimpleThreadPool>(
4916
22
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
4917
22
    worker_pool->start();
4918
    // TODO bacth delete
4919
4.00k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
4920
4.00k
        std::string dbm_start_key =
4921
4.00k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4922
4.00k
        std::string dbm_end_key = dbm_start_key;
4923
4.00k
        encode_int64(INT64_MAX, &dbm_end_key);
4924
4.00k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4925
4.00k
        if (ret != 0) {
4926
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
4927
0
                         << instance_id_;
4928
0
        }
4929
4.00k
        return ret;
4930
4.00k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
4919
2
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
4920
2
        std::string dbm_start_key =
4921
2
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4922
2
        std::string dbm_end_key = dbm_start_key;
4923
2
        encode_int64(INT64_MAX, &dbm_end_key);
4924
2
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4925
2
        if (ret != 0) {
4926
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
4927
0
                         << instance_id_;
4928
0
        }
4929
2
        return ret;
4930
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
4919
4.00k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
4920
4.00k
        std::string dbm_start_key =
4921
4.00k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4922
4.00k
        std::string dbm_end_key = dbm_start_key;
4923
4.00k
        encode_int64(INT64_MAX, &dbm_end_key);
4924
4.00k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4925
4.00k
        if (ret != 0) {
4926
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
4927
0
                         << instance_id_;
4928
0
        }
4929
4.00k
        return ret;
4930
4.00k
    };
4931
22
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
4932
250
                                            int64_t tablet_id, const std::string& rowset_id) {
4933
        // Try to delete rowset data in background thread
4934
250
        int ret = worker_pool->submit_with_timeout(
4935
250
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4936
246
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4937
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4938
0
                        return;
4939
0
                    }
4940
246
                    std::vector<std::string> keys;
4941
246
                    {
4942
246
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4943
246
                        async_recycled_rowset_keys.push_back(std::move(key));
4944
246
                        if (async_recycled_rowset_keys.size() > 100) {
4945
2
                            keys.swap(async_recycled_rowset_keys);
4946
2
                        }
4947
246
                    }
4948
246
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4949
246
                    if (keys.empty()) return;
4950
2
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4951
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4952
0
                                     << instance_id_;
4953
2
                    } else {
4954
2
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4955
2
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4956
2
                                           num_recycled, start_time);
4957
2
                    }
4958
2
                },
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
4935
246
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4936
246
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4937
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4938
0
                        return;
4939
0
                    }
4940
246
                    std::vector<std::string> keys;
4941
246
                    {
4942
246
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4943
246
                        async_recycled_rowset_keys.push_back(std::move(key));
4944
246
                        if (async_recycled_rowset_keys.size() > 100) {
4945
2
                            keys.swap(async_recycled_rowset_keys);
4946
2
                        }
4947
246
                    }
4948
246
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4949
246
                    if (keys.empty()) return;
4950
2
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4951
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4952
0
                                     << instance_id_;
4953
2
                    } else {
4954
2
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4955
2
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4956
2
                                           num_recycled, start_time);
4957
2
                    }
4958
2
                },
4959
250
                0);
4960
250
        if (ret == 0) return 0;
4961
        // Submit task failed, delete rowset data in current thread
4962
4
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4963
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4964
0
            return -1;
4965
0
        }
4966
4
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
4967
0
            return -1;
4968
0
        }
4969
4
        rowset_keys.push_back(std::move(key));
4970
4
        return 0;
4971
4
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
4932
250
                                            int64_t tablet_id, const std::string& rowset_id) {
4933
        // Try to delete rowset data in background thread
4934
250
        int ret = worker_pool->submit_with_timeout(
4935
250
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4936
250
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4937
250
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4938
250
                        return;
4939
250
                    }
4940
250
                    std::vector<std::string> keys;
4941
250
                    {
4942
250
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4943
250
                        async_recycled_rowset_keys.push_back(std::move(key));
4944
250
                        if (async_recycled_rowset_keys.size() > 100) {
4945
250
                            keys.swap(async_recycled_rowset_keys);
4946
250
                        }
4947
250
                    }
4948
250
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4949
250
                    if (keys.empty()) return;
4950
250
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4951
250
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4952
250
                                     << instance_id_;
4953
250
                    } else {
4954
250
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4955
250
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4956
250
                                           num_recycled, start_time);
4957
250
                    }
4958
250
                },
4959
250
                0);
4960
250
        if (ret == 0) return 0;
4961
        // Submit task failed, delete rowset data in current thread
4962
4
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4963
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4964
0
            return -1;
4965
0
        }
4966
4
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
4967
0
            return -1;
4968
0
        }
4969
4
        rowset_keys.push_back(std::move(key));
4970
4
        return 0;
4971
4
    };
4972
4973
22
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
4974
4975
7.75k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
4976
7.75k
        ++num_scanned;
4977
7.75k
        total_rowset_key_size += k.size();
4978
7.75k
        total_rowset_value_size += v.size();
4979
7.75k
        RecycleRowsetPB rowset;
4980
7.75k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
4981
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4982
0
            return -1;
4983
0
        }
4984
4985
7.75k
        int64_t current_time = ::time(nullptr);
4986
7.75k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
4987
4988
7.75k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
4989
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
4990
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
4991
7.75k
        if (current_time < expiration) { // not expired
4992
0
            return 0;
4993
0
        }
4994
7.75k
        ++num_expired;
4995
7.75k
        expired_rowset_size += v.size();
4996
4997
7.75k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
4998
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
4999
                // in old version, keep this key-value pair and it needs to be checked manually
5000
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5001
0
                return -1;
5002
0
            }
5003
250
            if (rowset.resource_id().empty()) [[unlikely]] {
5004
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5005
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5006
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5007
0
                rowset_keys.emplace_back(k);
5008
0
                return -1;
5009
0
            }
5010
            // decode rowset_id
5011
250
            auto k1 = k;
5012
250
            k1.remove_prefix(1);
5013
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5014
250
            decode_key(&k1, &out);
5015
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5016
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5017
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5018
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5019
250
                      << " task_type=" << metrics_context.operation_type;
5020
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5021
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5022
0
                return -1;
5023
0
            }
5024
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5025
250
            metrics_context.total_recycled_num++;
5026
250
            segment_metrics_context_.total_recycled_data_size +=
5027
250
                    rowset.rowset_meta().total_disk_size();
5028
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5029
250
            return 0;
5030
250
        }
5031
5032
7.50k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5033
7.50k
        if (config::enable_mark_delete_rowset_before_recycle) {
5034
7.50k
            if (need_mark_rowset_as_recycled(rowset)) {
5035
3.75k
                rowset_keys_to_mark_recycled.emplace_back(k);
5036
3.75k
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5037
3.75k
                             "at next turn, instance_id="
5038
3.75k
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5039
3.75k
                          << " version=[" << rowset_meta->start_version() << '-'
5040
3.75k
                          << rowset_meta->end_version() << "]";
5041
3.75k
                return 0;
5042
3.75k
            }
5043
7.50k
        }
5044
5045
3.75k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5046
3.75k
            rowset_meta->end_version() != 1) {
5047
3.75k
            if (make_deferred_abort_task(rowset).has_value()) {
5048
2
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5049
2
                             "instance_id="
5050
2
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5051
2
                          << " version=[" << rowset_meta->start_version() << '-'
5052
2
                          << rowset_meta->end_version() << "]";
5053
2
                rowset_keys_to_abort.emplace_back(k);
5054
2
            }
5055
3.75k
        }
5056
5057
        // TODO(plat1ko): check rowset not referenced
5058
3.75k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5059
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5060
0
                LOG_INFO("recycle rowset that has empty resource id");
5061
0
            } else {
5062
                // other situations, keep this key-value pair and it needs to be checked manually
5063
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5064
0
                return -1;
5065
0
            }
5066
0
        }
5067
3.75k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5068
3.75k
                  << " tablet_id=" << rowset_meta->tablet_id()
5069
3.75k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5070
3.75k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5071
3.75k
                  << "] txn_id=" << rowset_meta->txn_id()
5072
3.75k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5073
3.75k
                  << " rowset_meta_size=" << v.size()
5074
3.75k
                  << " creation_time=" << rowset_meta->creation_time()
5075
3.75k
                  << " task_type=" << metrics_context.operation_type;
5076
3.75k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5077
            // unable to calculate file path, can only be deleted by rowset id prefix
5078
652
            num_prepare += 1;
5079
652
            prepare_rowset_keys_to_delete.emplace_back(k);
5080
3.10k
        } else {
5081
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5082
3.10k
            rowset_keys.emplace_back(k);
5083
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5084
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5085
3.10k
                ++num_empty_rowset;
5086
3.10k
            }
5087
3.10k
        }
5088
3.75k
        return 0;
5089
3.75k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
4975
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
4976
7
        ++num_scanned;
4977
7
        total_rowset_key_size += k.size();
4978
7
        total_rowset_value_size += v.size();
4979
7
        RecycleRowsetPB rowset;
4980
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
4981
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4982
0
            return -1;
4983
0
        }
4984
4985
7
        int64_t current_time = ::time(nullptr);
4986
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
4987
4988
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
4989
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
4990
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
4991
7
        if (current_time < expiration) { // not expired
4992
0
            return 0;
4993
0
        }
4994
7
        ++num_expired;
4995
7
        expired_rowset_size += v.size();
4996
4997
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
4998
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
4999
                // in old version, keep this key-value pair and it needs to be checked manually
5000
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5001
0
                return -1;
5002
0
            }
5003
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5004
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5005
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5006
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5007
0
                rowset_keys.emplace_back(k);
5008
0
                return -1;
5009
0
            }
5010
            // decode rowset_id
5011
0
            auto k1 = k;
5012
0
            k1.remove_prefix(1);
5013
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5014
0
            decode_key(&k1, &out);
5015
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5016
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5017
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5018
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5019
0
                      << " task_type=" << metrics_context.operation_type;
5020
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5021
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5022
0
                return -1;
5023
0
            }
5024
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5025
0
            metrics_context.total_recycled_num++;
5026
0
            segment_metrics_context_.total_recycled_data_size +=
5027
0
                    rowset.rowset_meta().total_disk_size();
5028
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5029
0
            return 0;
5030
0
        }
5031
5032
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
5033
7
        if (config::enable_mark_delete_rowset_before_recycle) {
5034
7
            if (need_mark_rowset_as_recycled(rowset)) {
5035
5
                rowset_keys_to_mark_recycled.emplace_back(k);
5036
5
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5037
5
                             "at next turn, instance_id="
5038
5
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5039
5
                          << " version=[" << rowset_meta->start_version() << '-'
5040
5
                          << rowset_meta->end_version() << "]";
5041
5
                return 0;
5042
5
            }
5043
7
        }
5044
5045
2
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5046
2
            rowset_meta->end_version() != 1) {
5047
2
            if (make_deferred_abort_task(rowset).has_value()) {
5048
2
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5049
2
                             "instance_id="
5050
2
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5051
2
                          << " version=[" << rowset_meta->start_version() << '-'
5052
2
                          << rowset_meta->end_version() << "]";
5053
2
                rowset_keys_to_abort.emplace_back(k);
5054
2
            }
5055
2
        }
5056
5057
        // TODO(plat1ko): check rowset not referenced
5058
2
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5059
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5060
0
                LOG_INFO("recycle rowset that has empty resource id");
5061
0
            } else {
5062
                // other situations, keep this key-value pair and it needs to be checked manually
5063
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5064
0
                return -1;
5065
0
            }
5066
0
        }
5067
2
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5068
2
                  << " tablet_id=" << rowset_meta->tablet_id()
5069
2
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5070
2
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5071
2
                  << "] txn_id=" << rowset_meta->txn_id()
5072
2
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5073
2
                  << " rowset_meta_size=" << v.size()
5074
2
                  << " creation_time=" << rowset_meta->creation_time()
5075
2
                  << " task_type=" << metrics_context.operation_type;
5076
2
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5077
            // unable to calculate file path, can only be deleted by rowset id prefix
5078
2
            num_prepare += 1;
5079
2
            prepare_rowset_keys_to_delete.emplace_back(k);
5080
2
        } else {
5081
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5082
0
            rowset_keys.emplace_back(k);
5083
0
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5084
0
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5085
0
                ++num_empty_rowset;
5086
0
            }
5087
0
        }
5088
2
        return 0;
5089
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
4975
7.75k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
4976
7.75k
        ++num_scanned;
4977
7.75k
        total_rowset_key_size += k.size();
4978
7.75k
        total_rowset_value_size += v.size();
4979
7.75k
        RecycleRowsetPB rowset;
4980
7.75k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
4981
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4982
0
            return -1;
4983
0
        }
4984
4985
7.75k
        int64_t current_time = ::time(nullptr);
4986
7.75k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
4987
4988
7.75k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
4989
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
4990
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
4991
7.75k
        if (current_time < expiration) { // not expired
4992
0
            return 0;
4993
0
        }
4994
7.75k
        ++num_expired;
4995
7.75k
        expired_rowset_size += v.size();
4996
4997
7.75k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
4998
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
4999
                // in old version, keep this key-value pair and it needs to be checked manually
5000
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5001
0
                return -1;
5002
0
            }
5003
250
            if (rowset.resource_id().empty()) [[unlikely]] {
5004
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5005
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5006
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5007
0
                rowset_keys.emplace_back(k);
5008
0
                return -1;
5009
0
            }
5010
            // decode rowset_id
5011
250
            auto k1 = k;
5012
250
            k1.remove_prefix(1);
5013
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5014
250
            decode_key(&k1, &out);
5015
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5016
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5017
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5018
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5019
250
                      << " task_type=" << metrics_context.operation_type;
5020
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5021
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5022
0
                return -1;
5023
0
            }
5024
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5025
250
            metrics_context.total_recycled_num++;
5026
250
            segment_metrics_context_.total_recycled_data_size +=
5027
250
                    rowset.rowset_meta().total_disk_size();
5028
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5029
250
            return 0;
5030
250
        }
5031
5032
7.50k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5033
7.50k
        if (config::enable_mark_delete_rowset_before_recycle) {
5034
7.50k
            if (need_mark_rowset_as_recycled(rowset)) {
5035
3.75k
                rowset_keys_to_mark_recycled.emplace_back(k);
5036
3.75k
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5037
3.75k
                             "at next turn, instance_id="
5038
3.75k
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5039
3.75k
                          << " version=[" << rowset_meta->start_version() << '-'
5040
3.75k
                          << rowset_meta->end_version() << "]";
5041
3.75k
                return 0;
5042
3.75k
            }
5043
7.50k
        }
5044
5045
3.75k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5046
3.75k
            rowset_meta->end_version() != 1) {
5047
3.75k
            if (make_deferred_abort_task(rowset).has_value()) {
5048
0
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5049
0
                             "instance_id="
5050
0
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5051
0
                          << " version=[" << rowset_meta->start_version() << '-'
5052
0
                          << rowset_meta->end_version() << "]";
5053
0
                rowset_keys_to_abort.emplace_back(k);
5054
0
            }
5055
3.75k
        }
5056
5057
        // TODO(plat1ko): check rowset not referenced
5058
3.75k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5059
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5060
0
                LOG_INFO("recycle rowset that has empty resource id");
5061
0
            } else {
5062
                // other situations, keep this key-value pair and it needs to be checked manually
5063
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5064
0
                return -1;
5065
0
            }
5066
0
        }
5067
3.75k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5068
3.75k
                  << " tablet_id=" << rowset_meta->tablet_id()
5069
3.75k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5070
3.75k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5071
3.75k
                  << "] txn_id=" << rowset_meta->txn_id()
5072
3.75k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5073
3.75k
                  << " rowset_meta_size=" << v.size()
5074
3.75k
                  << " creation_time=" << rowset_meta->creation_time()
5075
3.75k
                  << " task_type=" << metrics_context.operation_type;
5076
3.75k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5077
            // unable to calculate file path, can only be deleted by rowset id prefix
5078
650
            num_prepare += 1;
5079
650
            prepare_rowset_keys_to_delete.emplace_back(k);
5080
3.10k
        } else {
5081
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5082
3.10k
            rowset_keys.emplace_back(k);
5083
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5084
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5085
3.10k
                ++num_empty_rowset;
5086
3.10k
            }
5087
3.10k
        }
5088
3.75k
        return 0;
5089
3.75k
    };
5090
5091
49
    auto loop_done = [&]() -> int {
5092
49
        std::vector<std::string> rowset_keys_to_delete;
5093
49
        std::vector<std::string> mark_keys_to_process;
5094
49
        std::vector<std::string> abort_keys_to_process;
5095
49
        std::vector<std::string> prepare_keys_to_process;
5096
        // rowset_id -> rowset_meta
5097
        // store rowset id and meta for statistics rs size when delete
5098
49
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5099
49
        rowset_keys_to_delete.swap(rowset_keys);
5100
49
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5101
49
        abort_keys_to_process.swap(rowset_keys_to_abort);
5102
49
        prepare_keys_to_process.swap(prepare_rowset_keys_to_delete);
5103
49
        rowsets_to_delete.swap(rowsets);
5104
49
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5105
49
                             rowsets_to_delete = std::move(rowsets_to_delete),
5106
49
                             prepare_keys_to_process = std::move(prepare_keys_to_process),
5107
49
                             mark_keys_to_process = std::move(mark_keys_to_process),
5108
49
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5109
49
            if (!mark_keys_to_process.empty() &&
5110
49
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5111
26
                                                                mark_keys_to_process) != 0) {
5112
0
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5113
0
                             << instance_id_;
5114
0
                return;
5115
0
            }
5116
49
            if (!abort_keys_to_process.empty() &&
5117
49
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5118
2
                        0) {
5119
0
                return;
5120
0
            }
5121
49
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5122
49
            if (!prepare_keys_to_process.empty() &&
5123
49
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5124
23
                                             &prepare_delete_tasks) != 0) {
5125
0
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5126
0
                             << instance_id_;
5127
0
                return;
5128
0
            }
5129
49
            if (!prepare_delete_tasks.empty()) {
5130
23
                std::vector<std::string> prepare_rowset_keys_to_delete;
5131
23
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5132
652
                for (const auto& task : prepare_delete_tasks) {
5133
652
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5134
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5135
0
                        return;
5136
0
                    }
5137
652
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5138
0
                        return;
5139
0
                    }
5140
652
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5141
652
                }
5142
23
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5143
0
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5144
0
                                 << instance_id_;
5145
0
                    return;
5146
0
                }
5147
23
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5148
23
                                       std::memory_order_relaxed);
5149
23
            }
5150
49
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5151
49
                                   metrics_context) != 0) {
5152
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5153
0
                return;
5154
0
            }
5155
3.10k
            for (const auto& [_, rs] : rowsets_to_delete) {
5156
3.10k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5157
0
                    return;
5158
0
                }
5159
3.10k
            }
5160
49
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5161
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5162
0
                return;
5163
0
            }
5164
49
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5165
49
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5108
7
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5109
7
            if (!mark_keys_to_process.empty() &&
5110
7
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5111
5
                                                                mark_keys_to_process) != 0) {
5112
0
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5113
0
                             << instance_id_;
5114
0
                return;
5115
0
            }
5116
7
            if (!abort_keys_to_process.empty() &&
5117
7
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5118
2
                        0) {
5119
0
                return;
5120
0
            }
5121
7
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5122
7
            if (!prepare_keys_to_process.empty() &&
5123
7
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5124
2
                                             &prepare_delete_tasks) != 0) {
5125
0
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5126
0
                             << instance_id_;
5127
0
                return;
5128
0
            }
5129
7
            if (!prepare_delete_tasks.empty()) {
5130
2
                std::vector<std::string> prepare_rowset_keys_to_delete;
5131
2
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5132
2
                for (const auto& task : prepare_delete_tasks) {
5133
2
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5134
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5135
0
                        return;
5136
0
                    }
5137
2
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5138
0
                        return;
5139
0
                    }
5140
2
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5141
2
                }
5142
2
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5143
0
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5144
0
                                 << instance_id_;
5145
0
                    return;
5146
0
                }
5147
2
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5148
2
                                       std::memory_order_relaxed);
5149
2
            }
5150
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5151
7
                                   metrics_context) != 0) {
5152
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5153
0
                return;
5154
0
            }
5155
7
            for (const auto& [_, rs] : rowsets_to_delete) {
5156
0
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5157
0
                    return;
5158
0
                }
5159
0
            }
5160
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5161
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5162
0
                return;
5163
0
            }
5164
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5165
7
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5108
42
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5109
42
            if (!mark_keys_to_process.empty() &&
5110
42
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5111
21
                                                                mark_keys_to_process) != 0) {
5112
0
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5113
0
                             << instance_id_;
5114
0
                return;
5115
0
            }
5116
42
            if (!abort_keys_to_process.empty() &&
5117
42
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5118
0
                        0) {
5119
0
                return;
5120
0
            }
5121
42
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5122
42
            if (!prepare_keys_to_process.empty() &&
5123
42
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5124
21
                                             &prepare_delete_tasks) != 0) {
5125
0
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5126
0
                             << instance_id_;
5127
0
                return;
5128
0
            }
5129
42
            if (!prepare_delete_tasks.empty()) {
5130
21
                std::vector<std::string> prepare_rowset_keys_to_delete;
5131
21
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5132
650
                for (const auto& task : prepare_delete_tasks) {
5133
650
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5134
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5135
0
                        return;
5136
0
                    }
5137
650
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5138
0
                        return;
5139
0
                    }
5140
650
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5141
650
                }
5142
21
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5143
0
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5144
0
                                 << instance_id_;
5145
0
                    return;
5146
0
                }
5147
21
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5148
21
                                       std::memory_order_relaxed);
5149
21
            }
5150
42
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5151
42
                                   metrics_context) != 0) {
5152
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5153
0
                return;
5154
0
            }
5155
3.10k
            for (const auto& [_, rs] : rowsets_to_delete) {
5156
3.10k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5157
0
                    return;
5158
0
                }
5159
3.10k
            }
5160
42
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5161
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5162
0
                return;
5163
0
            }
5164
42
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5165
42
        });
5166
49
        return 0;
5167
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5091
7
    auto loop_done = [&]() -> int {
5092
7
        std::vector<std::string> rowset_keys_to_delete;
5093
7
        std::vector<std::string> mark_keys_to_process;
5094
7
        std::vector<std::string> abort_keys_to_process;
5095
7
        std::vector<std::string> prepare_keys_to_process;
5096
        // rowset_id -> rowset_meta
5097
        // store rowset id and meta for statistics rs size when delete
5098
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5099
7
        rowset_keys_to_delete.swap(rowset_keys);
5100
7
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5101
7
        abort_keys_to_process.swap(rowset_keys_to_abort);
5102
7
        prepare_keys_to_process.swap(prepare_rowset_keys_to_delete);
5103
7
        rowsets_to_delete.swap(rowsets);
5104
7
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5105
7
                             rowsets_to_delete = std::move(rowsets_to_delete),
5106
7
                             prepare_keys_to_process = std::move(prepare_keys_to_process),
5107
7
                             mark_keys_to_process = std::move(mark_keys_to_process),
5108
7
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5109
7
            if (!mark_keys_to_process.empty() &&
5110
7
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5111
7
                                                                mark_keys_to_process) != 0) {
5112
7
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5113
7
                             << instance_id_;
5114
7
                return;
5115
7
            }
5116
7
            if (!abort_keys_to_process.empty() &&
5117
7
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5118
7
                        0) {
5119
7
                return;
5120
7
            }
5121
7
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5122
7
            if (!prepare_keys_to_process.empty() &&
5123
7
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5124
7
                                             &prepare_delete_tasks) != 0) {
5125
7
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5126
7
                             << instance_id_;
5127
7
                return;
5128
7
            }
5129
7
            if (!prepare_delete_tasks.empty()) {
5130
7
                std::vector<std::string> prepare_rowset_keys_to_delete;
5131
7
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5132
7
                for (const auto& task : prepare_delete_tasks) {
5133
7
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5134
7
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5135
7
                        return;
5136
7
                    }
5137
7
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5138
7
                        return;
5139
7
                    }
5140
7
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5141
7
                }
5142
7
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5143
7
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5144
7
                                 << instance_id_;
5145
7
                    return;
5146
7
                }
5147
7
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5148
7
                                       std::memory_order_relaxed);
5149
7
            }
5150
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5151
7
                                   metrics_context) != 0) {
5152
7
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5153
7
                return;
5154
7
            }
5155
7
            for (const auto& [_, rs] : rowsets_to_delete) {
5156
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5157
7
                    return;
5158
7
                }
5159
7
            }
5160
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5161
7
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5162
7
                return;
5163
7
            }
5164
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5165
7
        });
5166
7
        return 0;
5167
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5091
42
    auto loop_done = [&]() -> int {
5092
42
        std::vector<std::string> rowset_keys_to_delete;
5093
42
        std::vector<std::string> mark_keys_to_process;
5094
42
        std::vector<std::string> abort_keys_to_process;
5095
42
        std::vector<std::string> prepare_keys_to_process;
5096
        // rowset_id -> rowset_meta
5097
        // store rowset id and meta for statistics rs size when delete
5098
42
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5099
42
        rowset_keys_to_delete.swap(rowset_keys);
5100
42
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5101
42
        abort_keys_to_process.swap(rowset_keys_to_abort);
5102
42
        prepare_keys_to_process.swap(prepare_rowset_keys_to_delete);
5103
42
        rowsets_to_delete.swap(rowsets);
5104
42
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5105
42
                             rowsets_to_delete = std::move(rowsets_to_delete),
5106
42
                             prepare_keys_to_process = std::move(prepare_keys_to_process),
5107
42
                             mark_keys_to_process = std::move(mark_keys_to_process),
5108
42
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5109
42
            if (!mark_keys_to_process.empty() &&
5110
42
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5111
42
                                                                mark_keys_to_process) != 0) {
5112
42
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5113
42
                             << instance_id_;
5114
42
                return;
5115
42
            }
5116
42
            if (!abort_keys_to_process.empty() &&
5117
42
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5118
42
                        0) {
5119
42
                return;
5120
42
            }
5121
42
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5122
42
            if (!prepare_keys_to_process.empty() &&
5123
42
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5124
42
                                             &prepare_delete_tasks) != 0) {
5125
42
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5126
42
                             << instance_id_;
5127
42
                return;
5128
42
            }
5129
42
            if (!prepare_delete_tasks.empty()) {
5130
42
                std::vector<std::string> prepare_rowset_keys_to_delete;
5131
42
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5132
42
                for (const auto& task : prepare_delete_tasks) {
5133
42
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5134
42
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5135
42
                        return;
5136
42
                    }
5137
42
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5138
42
                        return;
5139
42
                    }
5140
42
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5141
42
                }
5142
42
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5143
42
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5144
42
                                 << instance_id_;
5145
42
                    return;
5146
42
                }
5147
42
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5148
42
                                       std::memory_order_relaxed);
5149
42
            }
5150
42
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5151
42
                                   metrics_context) != 0) {
5152
42
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5153
42
                return;
5154
42
            }
5155
42
            for (const auto& [_, rs] : rowsets_to_delete) {
5156
42
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5157
42
                    return;
5158
42
                }
5159
42
            }
5160
42
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5161
42
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5162
42
                return;
5163
42
            }
5164
42
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5165
42
        });
5166
42
        return 0;
5167
42
    };
5168
5169
22
    if (config::enable_recycler_stats_metrics) {
5170
0
        scan_and_statistics_rowsets();
5171
0
    }
5172
    // recycle_func and loop_done for scan and recycle
5173
22
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
5174
22
                               std::move(loop_done));
5175
5176
22
    worker_pool->stop();
5177
5178
22
    if (!async_recycled_rowset_keys.empty()) {
5179
1
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5180
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5181
0
            return -1;
5182
1
        } else {
5183
1
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5184
1
        }
5185
1
    }
5186
5187
    // Report final metrics after all concurrent tasks completed
5188
22
    segment_metrics_context_.report();
5189
22
    metrics_context.report();
5190
5191
22
    return ret;
5192
22
}
5193
5194
13
int InstanceRecycler::recycle_restore_jobs() {
5195
13
    const std::string task_name = "recycle_restore_jobs";
5196
13
    int64_t num_scanned = 0;
5197
13
    int64_t num_expired = 0;
5198
13
    int64_t num_recycled = 0;
5199
13
    int64_t num_aborted = 0;
5200
5201
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5202
5203
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
5204
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
5205
13
    std::string restore_job_key0;
5206
13
    std::string restore_job_key1;
5207
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
5208
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
5209
5210
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
5211
5212
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5213
13
    register_recycle_task(task_name, start_time);
5214
5215
13
    DORIS_CLOUD_DEFER {
5216
13
        unregister_recycle_task(task_name);
5217
13
        int64_t cost =
5218
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5219
13
        metrics_context.finish_report();
5220
5221
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5222
13
                .tag("instance_id", instance_id_)
5223
13
                .tag("num_scanned", num_scanned)
5224
13
                .tag("num_expired", num_expired)
5225
13
                .tag("num_recycled", num_recycled)
5226
13
                .tag("num_aborted", num_aborted);
5227
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
5215
13
    DORIS_CLOUD_DEFER {
5216
13
        unregister_recycle_task(task_name);
5217
13
        int64_t cost =
5218
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5219
13
        metrics_context.finish_report();
5220
5221
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5222
13
                .tag("instance_id", instance_id_)
5223
13
                .tag("num_scanned", num_scanned)
5224
13
                .tag("num_expired", num_expired)
5225
13
                .tag("num_recycled", num_recycled)
5226
13
                .tag("num_aborted", num_aborted);
5227
13
    };
5228
5229
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5230
5231
13
    std::vector<std::string_view> restore_job_keys;
5232
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5233
41
        ++num_scanned;
5234
41
        RestoreJobCloudPB restore_job_pb;
5235
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5236
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5237
0
            return -1;
5238
0
        }
5239
41
        int64_t expiration =
5240
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5241
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5242
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5243
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5244
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5245
0
                   << " state=" << restore_job_pb.state();
5246
41
        int64_t current_time = ::time(nullptr);
5247
41
        if (current_time < expiration) { // not expired
5248
0
            return 0;
5249
0
        }
5250
41
        ++num_expired;
5251
5252
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5253
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5254
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5255
5256
41
        std::unique_ptr<Transaction> txn;
5257
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5258
41
        if (err != TxnErrorCode::TXN_OK) {
5259
0
            LOG_WARNING("failed to recycle restore job")
5260
0
                    .tag("err", err)
5261
0
                    .tag("tablet id", tablet_id)
5262
0
                    .tag("instance_id", instance_id_)
5263
0
                    .tag("reason", "failed to create txn");
5264
0
            return -1;
5265
0
        }
5266
5267
41
        std::string val;
5268
41
        err = txn->get(k, &val);
5269
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5270
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5271
0
            return 0;
5272
0
        }
5273
41
        if (err != TxnErrorCode::TXN_OK) {
5274
0
            LOG_WARNING("failed to get kv");
5275
0
            return -1;
5276
0
        }
5277
41
        restore_job_pb.Clear();
5278
41
        if (!restore_job_pb.ParseFromString(val)) {
5279
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5280
0
            return -1;
5281
0
        }
5282
5283
        // PREPARED or COMMITTED, change state to DROPPED and return
5284
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5285
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5286
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5287
0
            restore_job_pb.set_need_recycle_data(true);
5288
0
            txn->put(k, restore_job_pb.SerializeAsString());
5289
0
            err = txn->commit();
5290
0
            if (err != TxnErrorCode::TXN_OK) {
5291
0
                LOG_WARNING("failed to commit txn: {}", err);
5292
0
                return -1;
5293
0
            }
5294
0
            num_aborted++;
5295
0
            return 0;
5296
0
        }
5297
5298
        // Change state to RECYCLING
5299
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5300
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5301
21
            txn->put(k, restore_job_pb.SerializeAsString());
5302
21
            err = txn->commit();
5303
21
            if (err != TxnErrorCode::TXN_OK) {
5304
0
                LOG_WARNING("failed to commit txn: {}", err);
5305
0
                return -1;
5306
0
            }
5307
21
            return 0;
5308
21
        }
5309
5310
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5311
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5312
5313
        // Recycle all data associated with the restore job.
5314
        // This includes rowsets, segments, and related resources.
5315
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5316
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5317
0
            LOG_WARNING("failed to recycle tablet")
5318
0
                    .tag("tablet_id", tablet_id)
5319
0
                    .tag("instance_id", instance_id_);
5320
0
            return -1;
5321
0
        }
5322
5323
        // delete all restore job rowset kv
5324
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5325
5326
20
        err = txn->commit();
5327
20
        if (err != TxnErrorCode::TXN_OK) {
5328
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5329
0
                    .tag("err", err)
5330
0
                    .tag("tablet id", tablet_id)
5331
0
                    .tag("instance_id", instance_id_)
5332
0
                    .tag("reason", "failed to commit txn");
5333
0
            return -1;
5334
0
        }
5335
5336
20
        metrics_context.total_recycled_num = ++num_recycled;
5337
20
        metrics_context.report();
5338
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5339
20
        restore_job_keys.push_back(k);
5340
5341
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5342
20
                  << " tablet_id=" << tablet_id;
5343
20
        return 0;
5344
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
5232
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5233
41
        ++num_scanned;
5234
41
        RestoreJobCloudPB restore_job_pb;
5235
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5236
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5237
0
            return -1;
5238
0
        }
5239
41
        int64_t expiration =
5240
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5241
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5242
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5243
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5244
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5245
0
                   << " state=" << restore_job_pb.state();
5246
41
        int64_t current_time = ::time(nullptr);
5247
41
        if (current_time < expiration) { // not expired
5248
0
            return 0;
5249
0
        }
5250
41
        ++num_expired;
5251
5252
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5253
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5254
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5255
5256
41
        std::unique_ptr<Transaction> txn;
5257
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5258
41
        if (err != TxnErrorCode::TXN_OK) {
5259
0
            LOG_WARNING("failed to recycle restore job")
5260
0
                    .tag("err", err)
5261
0
                    .tag("tablet id", tablet_id)
5262
0
                    .tag("instance_id", instance_id_)
5263
0
                    .tag("reason", "failed to create txn");
5264
0
            return -1;
5265
0
        }
5266
5267
41
        std::string val;
5268
41
        err = txn->get(k, &val);
5269
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5270
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5271
0
            return 0;
5272
0
        }
5273
41
        if (err != TxnErrorCode::TXN_OK) {
5274
0
            LOG_WARNING("failed to get kv");
5275
0
            return -1;
5276
0
        }
5277
41
        restore_job_pb.Clear();
5278
41
        if (!restore_job_pb.ParseFromString(val)) {
5279
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5280
0
            return -1;
5281
0
        }
5282
5283
        // PREPARED or COMMITTED, change state to DROPPED and return
5284
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5285
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5286
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5287
0
            restore_job_pb.set_need_recycle_data(true);
5288
0
            txn->put(k, restore_job_pb.SerializeAsString());
5289
0
            err = txn->commit();
5290
0
            if (err != TxnErrorCode::TXN_OK) {
5291
0
                LOG_WARNING("failed to commit txn: {}", err);
5292
0
                return -1;
5293
0
            }
5294
0
            num_aborted++;
5295
0
            return 0;
5296
0
        }
5297
5298
        // Change state to RECYCLING
5299
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5300
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5301
21
            txn->put(k, restore_job_pb.SerializeAsString());
5302
21
            err = txn->commit();
5303
21
            if (err != TxnErrorCode::TXN_OK) {
5304
0
                LOG_WARNING("failed to commit txn: {}", err);
5305
0
                return -1;
5306
0
            }
5307
21
            return 0;
5308
21
        }
5309
5310
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5311
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5312
5313
        // Recycle all data associated with the restore job.
5314
        // This includes rowsets, segments, and related resources.
5315
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5316
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5317
0
            LOG_WARNING("failed to recycle tablet")
5318
0
                    .tag("tablet_id", tablet_id)
5319
0
                    .tag("instance_id", instance_id_);
5320
0
            return -1;
5321
0
        }
5322
5323
        // delete all restore job rowset kv
5324
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5325
5326
20
        err = txn->commit();
5327
20
        if (err != TxnErrorCode::TXN_OK) {
5328
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5329
0
                    .tag("err", err)
5330
0
                    .tag("tablet id", tablet_id)
5331
0
                    .tag("instance_id", instance_id_)
5332
0
                    .tag("reason", "failed to commit txn");
5333
0
            return -1;
5334
0
        }
5335
5336
20
        metrics_context.total_recycled_num = ++num_recycled;
5337
20
        metrics_context.report();
5338
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5339
20
        restore_job_keys.push_back(k);
5340
5341
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5342
20
                  << " tablet_id=" << tablet_id;
5343
20
        return 0;
5344
20
    };
5345
5346
13
    auto loop_done = [&restore_job_keys, this]() -> int {
5347
3
        if (restore_job_keys.empty()) return 0;
5348
1
        DORIS_CLOUD_DEFER {
5349
1
            restore_job_keys.clear();
5350
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5348
1
        DORIS_CLOUD_DEFER {
5349
1
            restore_job_keys.clear();
5350
1
        };
5351
5352
1
        std::unique_ptr<Transaction> txn;
5353
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5354
1
        if (err != TxnErrorCode::TXN_OK) {
5355
0
            LOG_WARNING("failed to recycle restore job")
5356
0
                    .tag("err", err)
5357
0
                    .tag("instance_id", instance_id_)
5358
0
                    .tag("reason", "failed to create txn");
5359
0
            return -1;
5360
0
        }
5361
20
        for (auto& k : restore_job_keys) {
5362
20
            txn->remove(k);
5363
20
        }
5364
1
        err = txn->commit();
5365
1
        if (err != TxnErrorCode::TXN_OK) {
5366
0
            LOG_WARNING("failed to recycle restore job")
5367
0
                    .tag("err", err)
5368
0
                    .tag("instance_id", instance_id_)
5369
0
                    .tag("reason", "failed to commit txn");
5370
0
            return -1;
5371
0
        }
5372
1
        return 0;
5373
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
5346
3
    auto loop_done = [&restore_job_keys, this]() -> int {
5347
3
        if (restore_job_keys.empty()) return 0;
5348
1
        DORIS_CLOUD_DEFER {
5349
1
            restore_job_keys.clear();
5350
1
        };
5351
5352
1
        std::unique_ptr<Transaction> txn;
5353
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5354
1
        if (err != TxnErrorCode::TXN_OK) {
5355
0
            LOG_WARNING("failed to recycle restore job")
5356
0
                    .tag("err", err)
5357
0
                    .tag("instance_id", instance_id_)
5358
0
                    .tag("reason", "failed to create txn");
5359
0
            return -1;
5360
0
        }
5361
20
        for (auto& k : restore_job_keys) {
5362
20
            txn->remove(k);
5363
20
        }
5364
1
        err = txn->commit();
5365
1
        if (err != TxnErrorCode::TXN_OK) {
5366
0
            LOG_WARNING("failed to recycle restore job")
5367
0
                    .tag("err", err)
5368
0
                    .tag("instance_id", instance_id_)
5369
0
                    .tag("reason", "failed to commit txn");
5370
0
            return -1;
5371
0
        }
5372
1
        return 0;
5373
1
    };
5374
5375
13
    if (config::enable_recycler_stats_metrics) {
5376
0
        scan_and_statistics_restore_jobs();
5377
0
    }
5378
5379
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
5380
13
                            std::move(loop_done));
5381
13
}
5382
5383
10
int InstanceRecycler::recycle_versioned_rowsets() {
5384
10
    const std::string task_name = "recycle_rowsets";
5385
10
    int64_t num_scanned = 0;
5386
10
    int64_t num_expired = 0;
5387
10
    int64_t num_prepare = 0;
5388
10
    int64_t num_compacted = 0;
5389
10
    int64_t num_empty_rowset = 0;
5390
10
    size_t total_rowset_key_size = 0;
5391
10
    size_t total_rowset_value_size = 0;
5392
10
    size_t expired_rowset_size = 0;
5393
10
    std::atomic_long num_recycled = 0;
5394
10
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5395
5396
10
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5397
10
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5398
10
    std::string recyc_rs_key0;
5399
10
    std::string recyc_rs_key1;
5400
10
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5401
10
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5402
5403
10
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5404
5405
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5406
10
    register_recycle_task(task_name, start_time);
5407
5408
10
    DORIS_CLOUD_DEFER {
5409
10
        unregister_recycle_task(task_name);
5410
10
        int64_t cost =
5411
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5412
10
        metrics_context.finish_report();
5413
10
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5414
10
                .tag("instance_id", instance_id_)
5415
10
                .tag("num_scanned", num_scanned)
5416
10
                .tag("num_expired", num_expired)
5417
10
                .tag("num_recycled", num_recycled)
5418
10
                .tag("num_recycled.prepare", num_prepare)
5419
10
                .tag("num_recycled.compacted", num_compacted)
5420
10
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5421
10
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5422
10
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5423
10
                .tag("expired_rowset_meta_size", expired_rowset_size);
5424
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
5408
10
    DORIS_CLOUD_DEFER {
5409
10
        unregister_recycle_task(task_name);
5410
10
        int64_t cost =
5411
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5412
10
        metrics_context.finish_report();
5413
10
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5414
10
                .tag("instance_id", instance_id_)
5415
10
                .tag("num_scanned", num_scanned)
5416
10
                .tag("num_expired", num_expired)
5417
10
                .tag("num_recycled", num_recycled)
5418
10
                .tag("num_recycled.prepare", num_prepare)
5419
10
                .tag("num_recycled.compacted", num_compacted)
5420
10
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5421
10
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5422
10
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5423
10
                .tag("expired_rowset_meta_size", expired_rowset_size);
5424
10
    };
5425
5426
10
    std::vector<std::string> orphan_rowset_keys;
5427
5428
    // Store keys of rowset recycled by background workers
5429
10
    std::mutex async_recycled_rowset_keys_mutex;
5430
10
    std::vector<std::string> async_recycled_rowset_keys;
5431
10
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5432
10
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5433
10
    worker_pool->start();
5434
10
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5435
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5436
        // Try to delete rowset data in background thread
5437
400
        int ret = worker_pool->submit_with_timeout(
5438
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5439
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5440
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5441
400
                        return;
5442
400
                    }
5443
                    // The async recycled rowsets are staled format or has not been used,
5444
                    // so we don't need to check the rowset ref count key.
5445
0
                    std::vector<std::string> keys;
5446
0
                    {
5447
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5448
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5449
0
                        if (async_recycled_rowset_keys.size() > 100) {
5450
0
                            keys.swap(async_recycled_rowset_keys);
5451
0
                        }
5452
0
                    }
5453
0
                    if (keys.empty()) return;
5454
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5455
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5456
0
                                     << instance_id_;
5457
0
                    } else {
5458
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5459
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5460
0
                                           num_recycled, start_time);
5461
0
                    }
5462
0
                },
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
5438
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5439
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5440
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5441
400
                        return;
5442
400
                    }
5443
                    // The async recycled rowsets are staled format or has not been used,
5444
                    // so we don't need to check the rowset ref count key.
5445
0
                    std::vector<std::string> keys;
5446
0
                    {
5447
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5448
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5449
0
                        if (async_recycled_rowset_keys.size() > 100) {
5450
0
                            keys.swap(async_recycled_rowset_keys);
5451
0
                        }
5452
0
                    }
5453
0
                    if (keys.empty()) return;
5454
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5455
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5456
0
                                     << instance_id_;
5457
0
                    } else {
5458
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5459
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5460
0
                                           num_recycled, start_time);
5461
0
                    }
5462
0
                },
5463
400
                0);
5464
400
        if (ret == 0) return 0;
5465
        // Submit task failed, delete rowset data in current thread
5466
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5467
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5468
0
            return -1;
5469
0
        }
5470
0
        orphan_rowset_keys.push_back(std::move(key));
5471
0
        return 0;
5472
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
5435
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5436
        // Try to delete rowset data in background thread
5437
400
        int ret = worker_pool->submit_with_timeout(
5438
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5439
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5440
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5441
400
                        return;
5442
400
                    }
5443
                    // The async recycled rowsets are staled format or has not been used,
5444
                    // so we don't need to check the rowset ref count key.
5445
400
                    std::vector<std::string> keys;
5446
400
                    {
5447
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5448
400
                        async_recycled_rowset_keys.push_back(std::move(key));
5449
400
                        if (async_recycled_rowset_keys.size() > 100) {
5450
400
                            keys.swap(async_recycled_rowset_keys);
5451
400
                        }
5452
400
                    }
5453
400
                    if (keys.empty()) return;
5454
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5455
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5456
400
                                     << instance_id_;
5457
400
                    } else {
5458
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5459
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5460
400
                                           num_recycled, start_time);
5461
400
                    }
5462
400
                },
5463
400
                0);
5464
400
        if (ret == 0) return 0;
5465
        // Submit task failed, delete rowset data in current thread
5466
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5467
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5468
0
            return -1;
5469
0
        }
5470
0
        orphan_rowset_keys.push_back(std::move(key));
5471
0
        return 0;
5472
0
    };
5473
5474
10
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5475
5476
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
5477
2.01k
        ++num_scanned;
5478
2.01k
        total_rowset_key_size += k.size();
5479
2.01k
        total_rowset_value_size += v.size();
5480
2.01k
        RecycleRowsetPB rowset;
5481
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5482
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5483
0
            return -1;
5484
0
        }
5485
5486
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5487
5488
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5489
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
5490
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5491
2.01k
        int64_t current_time = ::time(nullptr);
5492
2.01k
        if (current_time < final_expiration) { // not expired
5493
0
            return 0;
5494
0
        }
5495
2.01k
        ++num_expired;
5496
2.01k
        expired_rowset_size += v.size();
5497
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5498
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5499
                // in old version, keep this key-value pair and it needs to be checked manually
5500
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5501
0
                return -1;
5502
0
            }
5503
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5504
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5505
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5506
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5507
0
                orphan_rowset_keys.emplace_back(k);
5508
0
                return -1;
5509
0
            }
5510
            // decode rowset_id
5511
0
            auto k1 = k;
5512
0
            k1.remove_prefix(1);
5513
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5514
0
            decode_key(&k1, &out);
5515
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5516
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5517
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5518
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
5519
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5520
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5521
0
                return -1;
5522
0
            }
5523
0
            return 0;
5524
0
        }
5525
        // TODO(plat1ko): check rowset not referenced
5526
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
5527
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5528
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5529
0
                LOG_INFO("recycle rowset that has empty resource id");
5530
0
            } else {
5531
                // other situations, keep this key-value pair and it needs to be checked manually
5532
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5533
0
                return -1;
5534
0
            }
5535
0
        }
5536
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5537
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
5538
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5539
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5540
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
5541
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5542
2.01k
                  << " rowset_meta_size=" << v.size()
5543
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
5544
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5545
            // unable to calculate file path, can only be deleted by rowset id prefix
5546
400
            num_prepare += 1;
5547
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5548
400
                                             rowset_meta->tablet_id(),
5549
400
                                             rowset_meta->rowset_id_v2()) != 0) {
5550
0
                return -1;
5551
0
            }
5552
1.61k
        } else {
5553
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
5554
1.61k
            worker_pool->submit(
5555
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5556
                        // The load & compact rowset keys are recycled during recycling operation logs.
5557
1.61k
                        RowsetDeleteTask task;
5558
1.61k
                        task.rowset_meta = rowset_meta;
5559
1.61k
                        task.recycle_rowset_key = k;
5560
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
5561
1.60k
                            return;
5562
1.60k
                        }
5563
13
                        num_compacted += is_compacted;
5564
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5565
13
                        if (rowset_meta.num_segments() == 0) {
5566
0
                            ++num_empty_rowset;
5567
0
                        }
5568
13
                    });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlvE_clEv
Line
Count
Source
5555
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5556
                        // The load & compact rowset keys are recycled during recycling operation logs.
5557
1.61k
                        RowsetDeleteTask task;
5558
1.61k
                        task.rowset_meta = rowset_meta;
5559
1.61k
                        task.recycle_rowset_key = k;
5560
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
5561
1.60k
                            return;
5562
1.60k
                        }
5563
13
                        num_compacted += is_compacted;
5564
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5565
13
                        if (rowset_meta.num_segments() == 0) {
5566
0
                            ++num_empty_rowset;
5567
0
                        }
5568
13
                    });
5569
1.61k
        }
5570
2.01k
        return 0;
5571
2.01k
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5476
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
5477
2.01k
        ++num_scanned;
5478
2.01k
        total_rowset_key_size += k.size();
5479
2.01k
        total_rowset_value_size += v.size();
5480
2.01k
        RecycleRowsetPB rowset;
5481
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5482
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5483
0
            return -1;
5484
0
        }
5485
5486
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5487
5488
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5489
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
5490
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5491
2.01k
        int64_t current_time = ::time(nullptr);
5492
2.01k
        if (current_time < final_expiration) { // not expired
5493
0
            return 0;
5494
0
        }
5495
2.01k
        ++num_expired;
5496
2.01k
        expired_rowset_size += v.size();
5497
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5498
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5499
                // in old version, keep this key-value pair and it needs to be checked manually
5500
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5501
0
                return -1;
5502
0
            }
5503
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5504
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5505
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5506
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5507
0
                orphan_rowset_keys.emplace_back(k);
5508
0
                return -1;
5509
0
            }
5510
            // decode rowset_id
5511
0
            auto k1 = k;
5512
0
            k1.remove_prefix(1);
5513
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5514
0
            decode_key(&k1, &out);
5515
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5516
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5517
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5518
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
5519
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5520
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5521
0
                return -1;
5522
0
            }
5523
0
            return 0;
5524
0
        }
5525
        // TODO(plat1ko): check rowset not referenced
5526
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
5527
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5528
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5529
0
                LOG_INFO("recycle rowset that has empty resource id");
5530
0
            } else {
5531
                // other situations, keep this key-value pair and it needs to be checked manually
5532
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5533
0
                return -1;
5534
0
            }
5535
0
        }
5536
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5537
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
5538
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5539
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5540
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
5541
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5542
2.01k
                  << " rowset_meta_size=" << v.size()
5543
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
5544
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5545
            // unable to calculate file path, can only be deleted by rowset id prefix
5546
400
            num_prepare += 1;
5547
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5548
400
                                             rowset_meta->tablet_id(),
5549
400
                                             rowset_meta->rowset_id_v2()) != 0) {
5550
0
                return -1;
5551
0
            }
5552
1.61k
        } else {
5553
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
5554
1.61k
            worker_pool->submit(
5555
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5556
                        // The load & compact rowset keys are recycled during recycling operation logs.
5557
1.61k
                        RowsetDeleteTask task;
5558
1.61k
                        task.rowset_meta = rowset_meta;
5559
1.61k
                        task.recycle_rowset_key = k;
5560
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
5561
1.61k
                            return;
5562
1.61k
                        }
5563
1.61k
                        num_compacted += is_compacted;
5564
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5565
1.61k
                        if (rowset_meta.num_segments() == 0) {
5566
1.61k
                            ++num_empty_rowset;
5567
1.61k
                        }
5568
1.61k
                    });
5569
1.61k
        }
5570
2.01k
        return 0;
5571
2.01k
    };
5572
5573
10
    if (config::enable_recycler_stats_metrics) {
5574
0
        scan_and_statistics_rowsets();
5575
0
    }
5576
5577
10
    auto loop_done = [&]() -> int {
5578
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
5579
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5580
0
        }
5581
6
        orphan_rowset_keys.clear();
5582
6
        return 0;
5583
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
Line
Count
Source
5577
6
    auto loop_done = [&]() -> int {
5578
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
5579
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5580
0
        }
5581
6
        orphan_rowset_keys.clear();
5582
6
        return 0;
5583
6
    };
5584
5585
    // recycle_func and loop_done for scan and recycle
5586
10
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
5587
10
                               std::move(loop_done));
5588
5589
10
    worker_pool->stop();
5590
5591
10
    if (!async_recycled_rowset_keys.empty()) {
5592
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5593
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5594
0
            return -1;
5595
0
        } else {
5596
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5597
0
        }
5598
0
    }
5599
5600
    // Report final metrics after all concurrent tasks completed
5601
10
    segment_metrics_context_.report();
5602
10
    metrics_context.report();
5603
5604
10
    return ret;
5605
10
}
5606
5607
1.61k
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task) {
5608
1.61k
    constexpr int MAX_RETRY = 10;
5609
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
5610
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
5611
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
5612
1.61k
    std::string_view reference_instance_id = instance_id_;
5613
1.61k
    if (rowset_meta.has_reference_instance_id()) {
5614
8
        reference_instance_id = rowset_meta.reference_instance_id();
5615
8
    }
5616
5617
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
5618
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
5619
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
5620
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
5621
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
5622
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
5623
1.61k
        std::unique_ptr<Transaction> txn;
5624
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5625
1.61k
        if (err != TxnErrorCode::TXN_OK) {
5626
0
            LOG_WARNING("failed to create txn").tag("err", err);
5627
0
            return -1;
5628
0
        }
5629
5630
1.61k
        std::string rowset_ref_count_key =
5631
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
5632
1.61k
        int64_t ref_count = 0;
5633
1.61k
        {
5634
1.61k
            std::string value;
5635
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
5636
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
5637
                // This is the old version rowset, we could recycle it directly.
5638
1.60k
                ref_count = 1;
5639
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
5640
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
5641
0
                return -1;
5642
10
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
5643
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
5644
0
                return -1;
5645
0
            }
5646
1.61k
        }
5647
5648
1.61k
        if (ref_count == 1) {
5649
            // It would not be added since it is recycling.
5650
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
5651
1.60k
                LOG_WARNING("failed to delete rowset data");
5652
1.60k
                return -1;
5653
1.60k
            }
5654
5655
            // Reset the transaction to avoid timeout.
5656
10
            err = txn_kv_->create_txn(&txn);
5657
10
            if (err != TxnErrorCode::TXN_OK) {
5658
0
                LOG_WARNING("failed to create txn").tag("err", err);
5659
0
                return -1;
5660
0
            }
5661
10
            txn->remove(rowset_ref_count_key);
5662
10
            LOG_INFO("delete rowset data ref count key")
5663
10
                    .tag("txn_id", rowset_meta.txn_id())
5664
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
5665
5666
10
            std::string dbm_start_key =
5667
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
5668
10
            std::string dbm_end_key = meta_delete_bitmap_key(
5669
10
                    {reference_instance_id, tablet_id, rowset_id,
5670
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
5671
10
            txn->remove(dbm_start_key, dbm_end_key);
5672
10
            LOG_INFO("remove delete bitmap kv")
5673
10
                    .tag("begin", hex(dbm_start_key))
5674
10
                    .tag("end", hex(dbm_end_key));
5675
5676
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
5677
10
                    {reference_instance_id, tablet_id, rowset_id});
5678
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
5679
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
5680
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
5681
10
            LOG_INFO("remove versioned delete bitmap kv")
5682
10
                    .tag("begin", hex(versioned_dbm_start_key))
5683
10
                    .tag("end", hex(versioned_dbm_end_key));
5684
10
        } else {
5685
            // Decrease the rowset ref count.
5686
            //
5687
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
5688
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
5689
2
            txn->atomic_add(rowset_ref_count_key, -1);
5690
2
            LOG_INFO("decrease rowset data ref count")
5691
2
                    .tag("txn_id", rowset_meta.txn_id())
5692
2
                    .tag("ref_count", ref_count - 1)
5693
2
                    .tag("ref_count_key", hex(rowset_ref_count_key));
5694
2
        }
5695
5696
12
        if (!task.versioned_rowset_key.empty()) {
5697
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
5698
0
                                                          task.versionstamp);
5699
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
5700
0
        }
5701
5702
12
        if (!task.non_versioned_rowset_key.empty()) {
5703
0
            txn->remove(task.non_versioned_rowset_key);
5704
0
            LOG_INFO("remove non versioned rowset key")
5705
0
                    .tag("key", hex(task.non_versioned_rowset_key));
5706
0
        }
5707
5708
        // empty when recycle ref rowsets for deleted instance
5709
13
        if (!task.recycle_rowset_key.empty()) {
5710
13
            txn->remove(task.recycle_rowset_key);
5711
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
5712
13
        }
5713
5714
12
        err = txn->commit();
5715
12
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
5716
            // The rowset ref count key has been changed, we need to retry.
5717
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
5718
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
5719
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
5720
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
5721
0
            continue;
5722
12
        } else if (err != TxnErrorCode::TXN_OK) {
5723
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
5724
0
            return -1;
5725
0
        }
5726
12
        LOG_INFO("recycle rowset meta and data success");
5727
12
        return 0;
5728
12
    }
5729
1
    LOG_WARNING("failed to recycle rowset meta and data after retry")
5730
1
            .tag("tablet_id", tablet_id)
5731
1
            .tag("rowset_id", rowset_id)
5732
1
            .tag("retry", MAX_RETRY);
5733
1
    return -1;
5734
1.61k
}
5735
5736
39
int InstanceRecycler::recycle_tmp_rowsets() {
5737
39
    const std::string task_name = "recycle_tmp_rowsets";
5738
39
    int64_t num_scanned = 0;
5739
39
    int64_t num_expired = 0;
5740
39
    std::atomic_long num_recycled = 0;
5741
39
    size_t expired_rowset_size = 0;
5742
39
    size_t total_rowset_key_size = 0;
5743
39
    size_t total_rowset_value_size = 0;
5744
39
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5745
5746
39
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
5747
39
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
5748
39
    std::string tmp_rs_key0;
5749
39
    std::string tmp_rs_key1;
5750
39
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
5751
39
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
5752
5753
39
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
5754
5755
39
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5756
39
    register_recycle_task(task_name, start_time);
5757
5758
39
    DORIS_CLOUD_DEFER {
5759
39
        unregister_recycle_task(task_name);
5760
39
        int64_t cost =
5761
39
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5762
39
        metrics_context.finish_report();
5763
39
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5764
39
                .tag("instance_id", instance_id_)
5765
39
                .tag("num_scanned", num_scanned)
5766
39
                .tag("num_expired", num_expired)
5767
39
                .tag("num_recycled", num_recycled)
5768
39
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5769
39
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5770
39
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5771
39
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
5758
12
    DORIS_CLOUD_DEFER {
5759
12
        unregister_recycle_task(task_name);
5760
12
        int64_t cost =
5761
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5762
12
        metrics_context.finish_report();
5763
12
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5764
12
                .tag("instance_id", instance_id_)
5765
12
                .tag("num_scanned", num_scanned)
5766
12
                .tag("num_expired", num_expired)
5767
12
                .tag("num_recycled", num_recycled)
5768
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5769
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5770
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5771
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
5758
27
    DORIS_CLOUD_DEFER {
5759
27
        unregister_recycle_task(task_name);
5760
27
        int64_t cost =
5761
27
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5762
27
        metrics_context.finish_report();
5763
27
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5764
27
                .tag("instance_id", instance_id_)
5765
27
                .tag("num_scanned", num_scanned)
5766
27
                .tag("num_expired", num_expired)
5767
27
                .tag("num_recycled", num_recycled)
5768
27
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5769
27
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5770
27
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5771
27
    };
5772
5773
    // Elements in `tmp_rowset_keys` has the same lifetime as `it`
5774
5775
39
    std::vector<std::string> tmp_rowset_keys;
5776
39
    std::vector<std::string> tmp_rowset_ref_count_keys;
5777
39
    std::vector<std::string> tmp_rowset_keys_to_mark_recycled;
5778
39
    std::vector<std::string> tmp_rowset_keys_to_abort;
5779
5780
    // rowset_id -> rowset_meta
5781
    // store tmp_rowset id and meta for statistics rs size when delete
5782
39
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
5783
39
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5784
39
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
5785
39
    worker_pool->start();
5786
5787
39
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5788
5789
39
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &tmp_rowsets,
5790
39
                             &expired_rowset_size, &total_rowset_key_size, &total_rowset_value_size,
5791
39
                             &earlest_ts, &tmp_rowset_ref_count_keys,
5792
39
                             &tmp_rowset_keys_to_mark_recycled, &tmp_rowset_keys_to_abort, this,
5793
106k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5794
106k
        ++num_scanned;
5795
106k
        total_rowset_key_size += k.size();
5796
106k
        total_rowset_value_size += v.size();
5797
106k
        doris::RowsetMetaCloudPB rowset;
5798
106k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5799
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5800
0
            return -1;
5801
0
        }
5802
106k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5803
106k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5804
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5805
0
                   << " txn_expiration=" << rowset.txn_expiration()
5806
0
                   << " rowset_creation_time=" << rowset.creation_time();
5807
106k
        int64_t current_time = ::time(nullptr);
5808
106k
        if (current_time < expiration) { // not expired
5809
0
            return 0;
5810
0
        }
5811
5812
106k
        if (config::enable_mark_delete_rowset_before_recycle) {
5813
106k
            if (need_mark_rowset_as_recycled(rowset)) {
5814
52.0k
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
5815
52.0k
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5816
52.0k
                             "at next turn, instance_id="
5817
52.0k
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5818
52.0k
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
5819
52.0k
                return 0;
5820
52.0k
            }
5821
106k
        }
5822
5823
54.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
5824
54.0k
            if (make_deferred_abort_task(rowset).has_value()) {
5825
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5826
3
                             "instance_id="
5827
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5828
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
5829
3
                tmp_rowset_keys_to_abort.emplace_back(k);
5830
3
            }
5831
54.0k
        }
5832
5833
54.0k
        ++num_expired;
5834
54.0k
        expired_rowset_size += v.size();
5835
54.0k
        if (!rowset.has_resource_id()) {
5836
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
5837
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
5838
0
                return -1;
5839
0
            }
5840
            // might be a delete pred rowset
5841
0
            tmp_rowset_keys.emplace_back(k);
5842
0
            return 0;
5843
0
        }
5844
        // TODO(plat1ko): check rowset not referenced
5845
54.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5846
54.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
5847
54.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
5848
54.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
5849
54.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
5850
54.0k
                  << " num_expired=" << num_expired
5851
54.0k
                  << " task_type=" << metrics_context.operation_type;
5852
5853
54.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
5854
        // Remove the rowset ref count key directly since it has not been used.
5855
54.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
5856
54.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
5857
54.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
5858
54.0k
                  << "key=" << hex(rowset_ref_count_key);
5859
54.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
5860
5861
54.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
5862
54.0k
        return 0;
5863
54.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5793
16
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5794
16
        ++num_scanned;
5795
16
        total_rowset_key_size += k.size();
5796
16
        total_rowset_value_size += v.size();
5797
16
        doris::RowsetMetaCloudPB rowset;
5798
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5799
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5800
0
            return -1;
5801
0
        }
5802
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5803
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5804
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5805
0
                   << " txn_expiration=" << rowset.txn_expiration()
5806
0
                   << " rowset_creation_time=" << rowset.creation_time();
5807
16
        int64_t current_time = ::time(nullptr);
5808
16
        if (current_time < expiration) { // not expired
5809
0
            return 0;
5810
0
        }
5811
5812
16
        if (config::enable_mark_delete_rowset_before_recycle) {
5813
16
            if (need_mark_rowset_as_recycled(rowset)) {
5814
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
5815
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5816
9
                             "at next turn, instance_id="
5817
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5818
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
5819
9
                return 0;
5820
9
            }
5821
16
        }
5822
5823
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
5824
7
            if (make_deferred_abort_task(rowset).has_value()) {
5825
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5826
3
                             "instance_id="
5827
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5828
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
5829
3
                tmp_rowset_keys_to_abort.emplace_back(k);
5830
3
            }
5831
7
        }
5832
5833
7
        ++num_expired;
5834
7
        expired_rowset_size += v.size();
5835
7
        if (!rowset.has_resource_id()) {
5836
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
5837
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
5838
0
                return -1;
5839
0
            }
5840
            // might be a delete pred rowset
5841
0
            tmp_rowset_keys.emplace_back(k);
5842
0
            return 0;
5843
0
        }
5844
        // TODO(plat1ko): check rowset not referenced
5845
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5846
7
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
5847
7
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
5848
7
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
5849
7
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
5850
7
                  << " num_expired=" << num_expired
5851
7
                  << " task_type=" << metrics_context.operation_type;
5852
5853
7
        tmp_rowset_keys.emplace_back(k.data(), k.size());
5854
        // Remove the rowset ref count key directly since it has not been used.
5855
7
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
5856
7
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
5857
7
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
5858
7
                  << "key=" << hex(rowset_ref_count_key);
5859
7
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
5860
5861
7
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
5862
7
        return 0;
5863
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5793
106k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5794
106k
        ++num_scanned;
5795
106k
        total_rowset_key_size += k.size();
5796
106k
        total_rowset_value_size += v.size();
5797
106k
        doris::RowsetMetaCloudPB rowset;
5798
106k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5799
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5800
0
            return -1;
5801
0
        }
5802
106k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5803
106k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5804
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5805
0
                   << " txn_expiration=" << rowset.txn_expiration()
5806
0
                   << " rowset_creation_time=" << rowset.creation_time();
5807
106k
        int64_t current_time = ::time(nullptr);
5808
106k
        if (current_time < expiration) { // not expired
5809
0
            return 0;
5810
0
        }
5811
5812
106k
        if (config::enable_mark_delete_rowset_before_recycle) {
5813
106k
            if (need_mark_rowset_as_recycled(rowset)) {
5814
52.0k
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
5815
52.0k
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5816
52.0k
                             "at next turn, instance_id="
5817
52.0k
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5818
52.0k
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
5819
52.0k
                return 0;
5820
52.0k
            }
5821
106k
        }
5822
5823
54.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
5824
54.0k
            if (make_deferred_abort_task(rowset).has_value()) {
5825
0
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5826
0
                             "instance_id="
5827
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5828
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
5829
0
                tmp_rowset_keys_to_abort.emplace_back(k);
5830
0
            }
5831
54.0k
        }
5832
5833
54.0k
        ++num_expired;
5834
54.0k
        expired_rowset_size += v.size();
5835
54.0k
        if (!rowset.has_resource_id()) {
5836
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
5837
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
5838
0
                return -1;
5839
0
            }
5840
            // might be a delete pred rowset
5841
0
            tmp_rowset_keys.emplace_back(k);
5842
0
            return 0;
5843
0
        }
5844
        // TODO(plat1ko): check rowset not referenced
5845
54.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5846
54.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
5847
54.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
5848
54.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
5849
54.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
5850
54.0k
                  << " num_expired=" << num_expired
5851
54.0k
                  << " task_type=" << metrics_context.operation_type;
5852
5853
54.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
5854
        // Remove the rowset ref count key directly since it has not been used.
5855
54.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
5856
54.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
5857
54.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
5858
54.0k
                  << "key=" << hex(rowset_ref_count_key);
5859
54.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
5860
5861
54.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
5862
54.0k
        return 0;
5863
54.0k
    };
5864
5865
    // TODO bacth delete
5866
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5867
51.0k
        std::string dbm_start_key =
5868
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5869
51.0k
        std::string dbm_end_key = dbm_start_key;
5870
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
5871
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5872
51.0k
        if (ret != 0) {
5873
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5874
0
                         << instance_id_ << ", tablet_id=" << tablet_id
5875
0
                         << ", rowset_id=" << rowset_id;
5876
0
        }
5877
51.0k
        return ret;
5878
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5866
7
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5867
7
        std::string dbm_start_key =
5868
7
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5869
7
        std::string dbm_end_key = dbm_start_key;
5870
7
        encode_int64(INT64_MAX, &dbm_end_key);
5871
7
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5872
7
        if (ret != 0) {
5873
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5874
0
                         << instance_id_ << ", tablet_id=" << tablet_id
5875
0
                         << ", rowset_id=" << rowset_id;
5876
0
        }
5877
7
        return ret;
5878
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5866
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5867
51.0k
        std::string dbm_start_key =
5868
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5869
51.0k
        std::string dbm_end_key = dbm_start_key;
5870
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
5871
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5872
51.0k
        if (ret != 0) {
5873
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5874
0
                         << instance_id_ << ", tablet_id=" << tablet_id
5875
0
                         << ", rowset_id=" << rowset_id;
5876
0
        }
5877
51.0k
        return ret;
5878
51.0k
    };
5879
5880
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5881
51.0k
        auto delete_bitmap_start =
5882
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
5883
51.0k
        auto delete_bitmap_end =
5884
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
5885
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
5886
51.0k
        if (ret != 0) {
5887
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
5888
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
5889
0
        }
5890
51.0k
        return ret;
5891
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5880
7
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5881
7
        auto delete_bitmap_start =
5882
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
5883
7
        auto delete_bitmap_end =
5884
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
5885
7
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
5886
7
        if (ret != 0) {
5887
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
5888
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
5889
0
        }
5890
7
        return ret;
5891
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5880
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5881
51.0k
        auto delete_bitmap_start =
5882
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
5883
51.0k
        auto delete_bitmap_end =
5884
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
5885
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
5886
51.0k
        if (ret != 0) {
5887
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
5888
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
5889
0
        }
5890
51.0k
        return ret;
5891
51.0k
    };
5892
5893
39
    auto loop_done = [&]() -> int {
5894
32
        std::vector<std::string> tmp_rowset_keys_to_delete;
5895
32
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
5896
32
        std::vector<std::string> mark_keys_to_process;
5897
32
        std::vector<std::string> abort_keys_to_process;
5898
32
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
5899
32
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
5900
32
        tmp_rowsets_to_delete.swap(tmp_rowsets);
5901
32
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
5902
32
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
5903
32
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
5904
32
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
5905
32
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
5906
32
                             tmp_rowset_ref_count_keys_to_delete =
5907
32
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
5908
32
                             mark_keys_to_process = std::move(mark_keys_to_process),
5909
32
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5910
32
            if (!mark_keys_to_process.empty() &&
5911
32
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
5912
16
                                                                  mark_keys_to_process) != 0) {
5913
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
5914
0
                             << instance_id_;
5915
0
                return;
5916
0
            }
5917
32
            if (!abort_keys_to_process.empty() &&
5918
32
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
5919
3
                                                                      false) != 0) {
5920
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
5921
0
                             << instance_id_;
5922
0
                return;
5923
0
            }
5924
32
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5925
32
                                   metrics_context) != 0) {
5926
3
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5927
3
                return;
5928
3
            }
5929
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5930
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5931
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5932
0
                                 << rs.ShortDebugString();
5933
0
                    return;
5934
0
                }
5935
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5936
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5937
0
                                 << rs.ShortDebugString();
5938
0
                    return;
5939
0
                }
5940
51.0k
            }
5941
29
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5942
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5943
0
                return;
5944
0
            }
5945
29
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5946
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5947
0
                return;
5948
0
            }
5949
29
            num_recycled += tmp_rowset_keys_to_delete.size();
5950
29
            return;
5951
29
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5909
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5910
12
            if (!mark_keys_to_process.empty() &&
5911
12
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
5912
7
                                                                  mark_keys_to_process) != 0) {
5913
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
5914
0
                             << instance_id_;
5915
0
                return;
5916
0
            }
5917
12
            if (!abort_keys_to_process.empty() &&
5918
12
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
5919
3
                                                                      false) != 0) {
5920
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
5921
0
                             << instance_id_;
5922
0
                return;
5923
0
            }
5924
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5925
12
                                   metrics_context) != 0) {
5926
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5927
0
                return;
5928
0
            }
5929
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5930
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5931
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5932
0
                                 << rs.ShortDebugString();
5933
0
                    return;
5934
0
                }
5935
7
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5936
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5937
0
                                 << rs.ShortDebugString();
5938
0
                    return;
5939
0
                }
5940
7
            }
5941
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5942
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5943
0
                return;
5944
0
            }
5945
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5946
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5947
0
                return;
5948
0
            }
5949
12
            num_recycled += tmp_rowset_keys_to_delete.size();
5950
12
            return;
5951
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5909
20
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5910
20
            if (!mark_keys_to_process.empty() &&
5911
20
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
5912
9
                                                                  mark_keys_to_process) != 0) {
5913
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
5914
0
                             << instance_id_;
5915
0
                return;
5916
0
            }
5917
20
            if (!abort_keys_to_process.empty() &&
5918
20
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
5919
0
                                                                      false) != 0) {
5920
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
5921
0
                             << instance_id_;
5922
0
                return;
5923
0
            }
5924
20
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5925
20
                                   metrics_context) != 0) {
5926
3
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5927
3
                return;
5928
3
            }
5929
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5930
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5931
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5932
0
                                 << rs.ShortDebugString();
5933
0
                    return;
5934
0
                }
5935
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5936
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5937
0
                                 << rs.ShortDebugString();
5938
0
                    return;
5939
0
                }
5940
51.0k
            }
5941
17
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5942
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5943
0
                return;
5944
0
            }
5945
17
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5946
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5947
0
                return;
5948
0
            }
5949
17
            num_recycled += tmp_rowset_keys_to_delete.size();
5950
17
            return;
5951
17
        });
5952
32
        return 0;
5953
32
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEv
Line
Count
Source
5893
12
    auto loop_done = [&]() -> int {
5894
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
5895
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
5896
12
        std::vector<std::string> mark_keys_to_process;
5897
12
        std::vector<std::string> abort_keys_to_process;
5898
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
5899
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
5900
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
5901
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
5902
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
5903
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
5904
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
5905
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
5906
12
                             tmp_rowset_ref_count_keys_to_delete =
5907
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
5908
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
5909
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5910
12
            if (!mark_keys_to_process.empty() &&
5911
12
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
5912
12
                                                                  mark_keys_to_process) != 0) {
5913
12
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
5914
12
                             << instance_id_;
5915
12
                return;
5916
12
            }
5917
12
            if (!abort_keys_to_process.empty() &&
5918
12
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
5919
12
                                                                      false) != 0) {
5920
12
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
5921
12
                             << instance_id_;
5922
12
                return;
5923
12
            }
5924
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5925
12
                                   metrics_context) != 0) {
5926
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5927
12
                return;
5928
12
            }
5929
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5930
12
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5931
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5932
12
                                 << rs.ShortDebugString();
5933
12
                    return;
5934
12
                }
5935
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5936
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5937
12
                                 << rs.ShortDebugString();
5938
12
                    return;
5939
12
                }
5940
12
            }
5941
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5942
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5943
12
                return;
5944
12
            }
5945
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5946
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5947
12
                return;
5948
12
            }
5949
12
            num_recycled += tmp_rowset_keys_to_delete.size();
5950
12
            return;
5951
12
        });
5952
12
        return 0;
5953
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEv
Line
Count
Source
5893
20
    auto loop_done = [&]() -> int {
5894
20
        std::vector<std::string> tmp_rowset_keys_to_delete;
5895
20
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
5896
20
        std::vector<std::string> mark_keys_to_process;
5897
20
        std::vector<std::string> abort_keys_to_process;
5898
20
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
5899
20
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
5900
20
        tmp_rowsets_to_delete.swap(tmp_rowsets);
5901
20
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
5902
20
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
5903
20
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
5904
20
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
5905
20
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
5906
20
                             tmp_rowset_ref_count_keys_to_delete =
5907
20
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
5908
20
                             mark_keys_to_process = std::move(mark_keys_to_process),
5909
20
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5910
20
            if (!mark_keys_to_process.empty() &&
5911
20
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
5912
20
                                                                  mark_keys_to_process) != 0) {
5913
20
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
5914
20
                             << instance_id_;
5915
20
                return;
5916
20
            }
5917
20
            if (!abort_keys_to_process.empty() &&
5918
20
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
5919
20
                                                                      false) != 0) {
5920
20
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
5921
20
                             << instance_id_;
5922
20
                return;
5923
20
            }
5924
20
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5925
20
                                   metrics_context) != 0) {
5926
20
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5927
20
                return;
5928
20
            }
5929
20
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5930
20
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5931
20
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5932
20
                                 << rs.ShortDebugString();
5933
20
                    return;
5934
20
                }
5935
20
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5936
20
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5937
20
                                 << rs.ShortDebugString();
5938
20
                    return;
5939
20
                }
5940
20
            }
5941
20
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5942
20
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5943
20
                return;
5944
20
            }
5945
20
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5946
20
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5947
20
                return;
5948
20
            }
5949
20
            num_recycled += tmp_rowset_keys_to_delete.size();
5950
20
            return;
5951
20
        });
5952
20
        return 0;
5953
20
    };
5954
5955
39
    if (config::enable_recycler_stats_metrics) {
5956
0
        scan_and_statistics_tmp_rowsets();
5957
0
    }
5958
    // recycle_func and loop_done for scan and recycle
5959
39
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
5960
39
                               std::move(loop_done));
5961
5962
39
    worker_pool->stop();
5963
5964
    // Report final metrics after all concurrent tasks completed
5965
39
    segment_metrics_context_.report();
5966
39
    metrics_context.report();
5967
5968
39
    return ret;
5969
39
}
5970
5971
int InstanceRecycler::scan_and_recycle(
5972
        std::string begin, std::string_view end,
5973
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
5974
268
        std::function<int()> loop_done) {
5975
268
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
5976
268
    int ret = 0;
5977
268
    int64_t cnt = 0;
5978
268
    int get_range_retried = 0;
5979
268
    std::string err;
5980
268
    DORIS_CLOUD_DEFER_COPY(begin, end) {
5981
268
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
5982
268
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
5983
268
                  << " ret=" << ret << " err=" << err;
5984
268
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
5980
31
    DORIS_CLOUD_DEFER_COPY(begin, end) {
5981
31
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
5982
31
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
5983
31
                  << " ret=" << ret << " err=" << err;
5984
31
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
5980
237
    DORIS_CLOUD_DEFER_COPY(begin, end) {
5981
237
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
5982
237
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
5983
237
                  << " ret=" << ret << " err=" << err;
5984
237
    };
5985
5986
268
    std::unique_ptr<RangeGetIterator> it;
5987
449
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
5988
321
        if (get_range_retried > 1000) {
5989
0
            err = "txn_get exceeds max retry(1000), may not scan all keys";
5990
0
            ret = -3;
5991
0
            return ret;
5992
0
        }
5993
321
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
5994
321
        if (get_ret != 0) { // txn kv may complain "Request for future version"
5995
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
5996
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
5997
0
                         << " get_range_retried=" << get_range_retried;
5998
0
            ++get_range_retried;
5999
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6000
0
            continue; // try again
6001
0
        }
6002
321
        if (!it->has_next()) {
6003
140
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
6004
140
            break; // scan finished
6005
140
        }
6006
154k
        while (it->has_next()) {
6007
154k
            ++cnt;
6008
            // recycle corresponding resources
6009
154k
            auto [k, v] = it->next();
6010
154k
            if (!it->has_next()) {
6011
181
                begin = k;
6012
181
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
6013
181
            }
6014
            // FIXME(gavin): if we want to continue scanning, the recycle_func should not return non-zero
6015
154k
            if (recycle_func(k, v) != 0) {
6016
4.00k
                err = "recycle_func error";
6017
4.00k
                ret = -1;
6018
4.00k
            }
6019
154k
        }
6020
181
        begin.push_back('\x00'); // Update to next smallest key for iteration
6021
        // FIXME(gavin): if we want to continue scanning, the loop_done should not return non-zero
6022
181
        if (loop_done && loop_done() != 0) {
6023
4
            err = "loop_done error";
6024
4
            ret = -1;
6025
4
        }
6026
181
    }
6027
268
    return ret;
6028
268
}
6029
6030
19
int InstanceRecycler::abort_timeout_txn() {
6031
19
    const std::string task_name = "abort_timeout_txn";
6032
19
    int64_t num_scanned = 0;
6033
19
    int64_t num_timeout = 0;
6034
19
    int64_t num_abort = 0;
6035
19
    int64_t num_advance = 0;
6036
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6037
6038
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6039
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6040
19
    std::string begin_txn_running_key;
6041
19
    std::string end_txn_running_key;
6042
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6043
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6044
6045
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
6046
6047
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6048
19
    register_recycle_task(task_name, start_time);
6049
6050
19
    DORIS_CLOUD_DEFER {
6051
19
        unregister_recycle_task(task_name);
6052
19
        int64_t cost =
6053
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6054
19
        metrics_context.finish_report();
6055
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6056
19
                .tag("instance_id", instance_id_)
6057
19
                .tag("num_scanned", num_scanned)
6058
19
                .tag("num_timeout", num_timeout)
6059
19
                .tag("num_abort", num_abort)
6060
19
                .tag("num_advance", num_advance);
6061
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6050
3
    DORIS_CLOUD_DEFER {
6051
3
        unregister_recycle_task(task_name);
6052
3
        int64_t cost =
6053
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6054
3
        metrics_context.finish_report();
6055
3
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6056
3
                .tag("instance_id", instance_id_)
6057
3
                .tag("num_scanned", num_scanned)
6058
3
                .tag("num_timeout", num_timeout)
6059
3
                .tag("num_abort", num_abort)
6060
3
                .tag("num_advance", num_advance);
6061
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6050
16
    DORIS_CLOUD_DEFER {
6051
16
        unregister_recycle_task(task_name);
6052
16
        int64_t cost =
6053
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6054
16
        metrics_context.finish_report();
6055
16
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6056
16
                .tag("instance_id", instance_id_)
6057
16
                .tag("num_scanned", num_scanned)
6058
16
                .tag("num_timeout", num_timeout)
6059
16
                .tag("num_abort", num_abort)
6060
16
                .tag("num_advance", num_advance);
6061
16
    };
6062
6063
19
    int64_t current_time =
6064
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6065
6066
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
6067
19
                                  &current_time, &metrics_context,
6068
19
                                  this](std::string_view k, std::string_view v) -> int {
6069
9
        ++num_scanned;
6070
6071
9
        std::unique_ptr<Transaction> txn;
6072
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6073
9
        if (err != TxnErrorCode::TXN_OK) {
6074
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6075
0
            return -1;
6076
0
        }
6077
9
        std::string_view k1 = k;
6078
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6079
9
        k1.remove_prefix(1); // Remove key space
6080
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6081
9
        if (decode_key(&k1, &out) != 0) {
6082
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6083
0
            return -1;
6084
0
        }
6085
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6086
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6087
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6088
        // Update txn_info
6089
9
        std::string txn_inf_key, txn_inf_val;
6090
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6091
9
        err = txn->get(txn_inf_key, &txn_inf_val);
6092
9
        if (err != TxnErrorCode::TXN_OK) {
6093
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6094
0
            return -1;
6095
0
        }
6096
9
        TxnInfoPB txn_info;
6097
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
6098
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6099
0
            return -1;
6100
0
        }
6101
6102
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6103
3
            txn.reset();
6104
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6105
3
            std::shared_ptr<TxnLazyCommitTask> task =
6106
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6107
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6108
3
            if (ret.first != MetaServiceCode::OK) {
6109
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6110
0
                             << "msg=" << ret.second;
6111
0
                return -1;
6112
0
            }
6113
3
            ++num_advance;
6114
3
            return 0;
6115
6
        } else {
6116
6
            TxnRunningPB txn_running_pb;
6117
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6118
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6119
0
                return -1;
6120
0
            }
6121
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6122
4
                return 0;
6123
4
            }
6124
2
            ++num_timeout;
6125
6126
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6127
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6128
2
            txn_info.set_finish_time(current_time);
6129
2
            txn_info.set_reason("timeout");
6130
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6131
2
            txn_inf_val.clear();
6132
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6133
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6134
0
                return -1;
6135
0
            }
6136
2
            txn->put(txn_inf_key, txn_inf_val);
6137
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6138
            // Put recycle txn key
6139
2
            std::string recyc_txn_key, recyc_txn_val;
6140
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6141
2
            RecycleTxnPB recycle_txn_pb;
6142
2
            recycle_txn_pb.set_creation_time(current_time);
6143
2
            recycle_txn_pb.set_label(txn_info.label());
6144
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6145
0
                LOG_WARNING("failed to serialize txn recycle info")
6146
0
                        .tag("key", hex(k))
6147
0
                        .tag("db_id", db_id)
6148
0
                        .tag("txn_id", txn_id);
6149
0
                return -1;
6150
0
            }
6151
2
            txn->put(recyc_txn_key, recyc_txn_val);
6152
            // Remove txn running key
6153
2
            txn->remove(k);
6154
2
            err = txn->commit();
6155
2
            if (err != TxnErrorCode::TXN_OK) {
6156
0
                LOG_WARNING("failed to commit txn err={}", err)
6157
0
                        .tag("key", hex(k))
6158
0
                        .tag("db_id", db_id)
6159
0
                        .tag("txn_id", txn_id);
6160
0
                return -1;
6161
0
            }
6162
2
            metrics_context.total_recycled_num = ++num_abort;
6163
2
            metrics_context.report();
6164
2
        }
6165
6166
2
        return 0;
6167
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6068
3
                                  this](std::string_view k, std::string_view v) -> int {
6069
3
        ++num_scanned;
6070
6071
3
        std::unique_ptr<Transaction> txn;
6072
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6073
3
        if (err != TxnErrorCode::TXN_OK) {
6074
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6075
0
            return -1;
6076
0
        }
6077
3
        std::string_view k1 = k;
6078
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6079
3
        k1.remove_prefix(1); // Remove key space
6080
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6081
3
        if (decode_key(&k1, &out) != 0) {
6082
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6083
0
            return -1;
6084
0
        }
6085
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6086
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6087
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6088
        // Update txn_info
6089
3
        std::string txn_inf_key, txn_inf_val;
6090
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6091
3
        err = txn->get(txn_inf_key, &txn_inf_val);
6092
3
        if (err != TxnErrorCode::TXN_OK) {
6093
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6094
0
            return -1;
6095
0
        }
6096
3
        TxnInfoPB txn_info;
6097
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
6098
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6099
0
            return -1;
6100
0
        }
6101
6102
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6103
3
            txn.reset();
6104
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6105
3
            std::shared_ptr<TxnLazyCommitTask> task =
6106
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6107
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6108
3
            if (ret.first != MetaServiceCode::OK) {
6109
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6110
0
                             << "msg=" << ret.second;
6111
0
                return -1;
6112
0
            }
6113
3
            ++num_advance;
6114
3
            return 0;
6115
3
        } else {
6116
0
            TxnRunningPB txn_running_pb;
6117
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6118
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6119
0
                return -1;
6120
0
            }
6121
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6122
0
                return 0;
6123
0
            }
6124
0
            ++num_timeout;
6125
6126
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6127
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6128
0
            txn_info.set_finish_time(current_time);
6129
0
            txn_info.set_reason("timeout");
6130
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6131
0
            txn_inf_val.clear();
6132
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6133
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6134
0
                return -1;
6135
0
            }
6136
0
            txn->put(txn_inf_key, txn_inf_val);
6137
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6138
            // Put recycle txn key
6139
0
            std::string recyc_txn_key, recyc_txn_val;
6140
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6141
0
            RecycleTxnPB recycle_txn_pb;
6142
0
            recycle_txn_pb.set_creation_time(current_time);
6143
0
            recycle_txn_pb.set_label(txn_info.label());
6144
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6145
0
                LOG_WARNING("failed to serialize txn recycle info")
6146
0
                        .tag("key", hex(k))
6147
0
                        .tag("db_id", db_id)
6148
0
                        .tag("txn_id", txn_id);
6149
0
                return -1;
6150
0
            }
6151
0
            txn->put(recyc_txn_key, recyc_txn_val);
6152
            // Remove txn running key
6153
0
            txn->remove(k);
6154
0
            err = txn->commit();
6155
0
            if (err != TxnErrorCode::TXN_OK) {
6156
0
                LOG_WARNING("failed to commit txn err={}", err)
6157
0
                        .tag("key", hex(k))
6158
0
                        .tag("db_id", db_id)
6159
0
                        .tag("txn_id", txn_id);
6160
0
                return -1;
6161
0
            }
6162
0
            metrics_context.total_recycled_num = ++num_abort;
6163
0
            metrics_context.report();
6164
0
        }
6165
6166
0
        return 0;
6167
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6068
6
                                  this](std::string_view k, std::string_view v) -> int {
6069
6
        ++num_scanned;
6070
6071
6
        std::unique_ptr<Transaction> txn;
6072
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6073
6
        if (err != TxnErrorCode::TXN_OK) {
6074
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6075
0
            return -1;
6076
0
        }
6077
6
        std::string_view k1 = k;
6078
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6079
6
        k1.remove_prefix(1); // Remove key space
6080
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6081
6
        if (decode_key(&k1, &out) != 0) {
6082
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6083
0
            return -1;
6084
0
        }
6085
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6086
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6087
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6088
        // Update txn_info
6089
6
        std::string txn_inf_key, txn_inf_val;
6090
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6091
6
        err = txn->get(txn_inf_key, &txn_inf_val);
6092
6
        if (err != TxnErrorCode::TXN_OK) {
6093
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6094
0
            return -1;
6095
0
        }
6096
6
        TxnInfoPB txn_info;
6097
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
6098
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6099
0
            return -1;
6100
0
        }
6101
6102
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6103
0
            txn.reset();
6104
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6105
0
            std::shared_ptr<TxnLazyCommitTask> task =
6106
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6107
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6108
0
            if (ret.first != MetaServiceCode::OK) {
6109
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6110
0
                             << "msg=" << ret.second;
6111
0
                return -1;
6112
0
            }
6113
0
            ++num_advance;
6114
0
            return 0;
6115
6
        } else {
6116
6
            TxnRunningPB txn_running_pb;
6117
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6118
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6119
0
                return -1;
6120
0
            }
6121
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6122
4
                return 0;
6123
4
            }
6124
2
            ++num_timeout;
6125
6126
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6127
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6128
2
            txn_info.set_finish_time(current_time);
6129
2
            txn_info.set_reason("timeout");
6130
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6131
2
            txn_inf_val.clear();
6132
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6133
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6134
0
                return -1;
6135
0
            }
6136
2
            txn->put(txn_inf_key, txn_inf_val);
6137
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6138
            // Put recycle txn key
6139
2
            std::string recyc_txn_key, recyc_txn_val;
6140
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6141
2
            RecycleTxnPB recycle_txn_pb;
6142
2
            recycle_txn_pb.set_creation_time(current_time);
6143
2
            recycle_txn_pb.set_label(txn_info.label());
6144
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6145
0
                LOG_WARNING("failed to serialize txn recycle info")
6146
0
                        .tag("key", hex(k))
6147
0
                        .tag("db_id", db_id)
6148
0
                        .tag("txn_id", txn_id);
6149
0
                return -1;
6150
0
            }
6151
2
            txn->put(recyc_txn_key, recyc_txn_val);
6152
            // Remove txn running key
6153
2
            txn->remove(k);
6154
2
            err = txn->commit();
6155
2
            if (err != TxnErrorCode::TXN_OK) {
6156
0
                LOG_WARNING("failed to commit txn err={}", err)
6157
0
                        .tag("key", hex(k))
6158
0
                        .tag("db_id", db_id)
6159
0
                        .tag("txn_id", txn_id);
6160
0
                return -1;
6161
0
            }
6162
2
            metrics_context.total_recycled_num = ++num_abort;
6163
2
            metrics_context.report();
6164
2
        }
6165
6166
2
        return 0;
6167
6
    };
6168
6169
19
    if (config::enable_recycler_stats_metrics) {
6170
0
        scan_and_statistics_abort_timeout_txn();
6171
0
    }
6172
    // recycle_func and loop_done for scan and recycle
6173
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
6174
19
                            std::move(handle_txn_running_kv));
6175
19
}
6176
6177
19
int InstanceRecycler::recycle_expired_txn_label() {
6178
19
    const std::string task_name = "recycle_expired_txn_label";
6179
19
    int64_t num_scanned = 0;
6180
19
    int64_t num_expired = 0;
6181
19
    std::atomic_long num_recycled = 0;
6182
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6183
19
    int ret = 0;
6184
6185
19
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
6186
19
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6187
19
    std::string begin_recycle_txn_key;
6188
19
    std::string end_recycle_txn_key;
6189
19
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
6190
19
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
6191
19
    std::vector<std::string> recycle_txn_info_keys;
6192
6193
19
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
6194
6195
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6196
19
    register_recycle_task(task_name, start_time);
6197
19
    DORIS_CLOUD_DEFER {
6198
19
        unregister_recycle_task(task_name);
6199
19
        int64_t cost =
6200
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6201
19
        metrics_context.finish_report();
6202
19
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6203
19
                .tag("instance_id", instance_id_)
6204
19
                .tag("num_scanned", num_scanned)
6205
19
                .tag("num_expired", num_expired)
6206
19
                .tag("num_recycled", num_recycled);
6207
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6197
1
    DORIS_CLOUD_DEFER {
6198
1
        unregister_recycle_task(task_name);
6199
1
        int64_t cost =
6200
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6201
1
        metrics_context.finish_report();
6202
1
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6203
1
                .tag("instance_id", instance_id_)
6204
1
                .tag("num_scanned", num_scanned)
6205
1
                .tag("num_expired", num_expired)
6206
1
                .tag("num_recycled", num_recycled);
6207
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6197
18
    DORIS_CLOUD_DEFER {
6198
18
        unregister_recycle_task(task_name);
6199
18
        int64_t cost =
6200
18
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6201
18
        metrics_context.finish_report();
6202
18
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6203
18
                .tag("instance_id", instance_id_)
6204
18
                .tag("num_scanned", num_scanned)
6205
18
                .tag("num_expired", num_expired)
6206
18
                .tag("num_recycled", num_recycled);
6207
18
    };
6208
6209
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6210
6211
19
    SyncExecutor<int> concurrent_delete_executor(
6212
19
            _thread_pool_group.s3_producer_pool,
6213
19
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
6214
23.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
6214
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
6214
23.0k
            [](const int& ret) { return ret != 0; });
6215
6216
19
    int64_t current_time_ms =
6217
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6218
6219
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6220
30.0k
        ++num_scanned;
6221
30.0k
        RecycleTxnPB recycle_txn_pb;
6222
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6223
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6224
0
            return -1;
6225
0
        }
6226
30.0k
        if ((config::force_immediate_recycle) ||
6227
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6228
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6229
30.0k
             current_time_ms)) {
6230
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6231
23.0k
            num_expired++;
6232
23.0k
            recycle_txn_info_keys.emplace_back(k);
6233
23.0k
        }
6234
30.0k
        return 0;
6235
30.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6219
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6220
1
        ++num_scanned;
6221
1
        RecycleTxnPB recycle_txn_pb;
6222
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6223
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6224
0
            return -1;
6225
0
        }
6226
1
        if ((config::force_immediate_recycle) ||
6227
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6228
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6229
1
             current_time_ms)) {
6230
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6231
1
            num_expired++;
6232
1
            recycle_txn_info_keys.emplace_back(k);
6233
1
        }
6234
1
        return 0;
6235
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6219
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6220
30.0k
        ++num_scanned;
6221
30.0k
        RecycleTxnPB recycle_txn_pb;
6222
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6223
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6224
0
            return -1;
6225
0
        }
6226
30.0k
        if ((config::force_immediate_recycle) ||
6227
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6228
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6229
30.0k
             current_time_ms)) {
6230
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6231
23.0k
            num_expired++;
6232
23.0k
            recycle_txn_info_keys.emplace_back(k);
6233
23.0k
        }
6234
30.0k
        return 0;
6235
30.0k
    };
6236
6237
    // int 0 for success, 1 for conflict, -1 for error
6238
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6239
23.0k
        std::string_view k1 = k;
6240
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6241
23.0k
        k1.remove_prefix(1); // Remove key space
6242
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6243
23.0k
        int ret = decode_key(&k1, &out);
6244
23.0k
        if (ret != 0) {
6245
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6246
0
            return -1;
6247
0
        }
6248
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6249
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6250
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6251
23.0k
        std::unique_ptr<Transaction> txn;
6252
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6253
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6254
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6255
0
            return -1;
6256
0
        }
6257
        // Remove txn index kv
6258
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6259
23.0k
        txn->remove(index_key);
6260
        // Remove txn info kv
6261
23.0k
        std::string info_key, info_val;
6262
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6263
23.0k
        err = txn->get(info_key, &info_val);
6264
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6265
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6266
0
            return -1;
6267
0
        }
6268
23.0k
        TxnInfoPB txn_info;
6269
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6270
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6271
0
            return -1;
6272
0
        }
6273
23.0k
        txn->remove(info_key);
6274
        // Remove sub txn index kvs
6275
23.0k
        std::vector<std::string> sub_txn_index_keys;
6276
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6277
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6278
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6279
22.9k
        }
6280
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6281
22.9k
            txn->remove(sub_txn_index_key);
6282
22.9k
        }
6283
        // Update txn label
6284
23.0k
        std::string label_key, label_val;
6285
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6286
23.0k
        err = txn->get(label_key, &label_val);
6287
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6288
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6289
0
                         << " err=" << err;
6290
0
            return -1;
6291
0
        }
6292
23.0k
        TxnLabelPB txn_label;
6293
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6294
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6295
0
            return -1;
6296
0
        }
6297
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6298
23.0k
        if (it != txn_label.txn_ids().end()) {
6299
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6300
23.0k
        }
6301
23.0k
        if (txn_label.txn_ids().empty()) {
6302
23.0k
            txn->remove(label_key);
6303
23.0k
            TEST_SYNC_POINT_CALLBACK(
6304
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6305
23.0k
        } else {
6306
74
            if (!txn_label.SerializeToString(&label_val)) {
6307
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6308
0
                return -1;
6309
0
            }
6310
74
            TEST_SYNC_POINT_CALLBACK(
6311
74
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6312
74
            txn->atomic_set_ver_value(label_key, label_val);
6313
74
            TEST_SYNC_POINT_CALLBACK(
6314
74
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6315
74
        }
6316
        // Remove recycle txn kv
6317
23.0k
        txn->remove(k);
6318
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6319
23.0k
        err = txn->commit();
6320
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6321
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6322
62
                TEST_SYNC_POINT_CALLBACK(
6323
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6324
                // log the txn_id and label
6325
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6326
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6327
62
                             << " txn_label=" << txn_info.label();
6328
62
                return 1;
6329
62
            }
6330
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6331
0
            return -1;
6332
62
        }
6333
23.0k
        ++num_recycled;
6334
6335
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6336
23.0k
        return 0;
6337
23.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6238
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6239
1
        std::string_view k1 = k;
6240
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6241
1
        k1.remove_prefix(1); // Remove key space
6242
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6243
1
        int ret = decode_key(&k1, &out);
6244
1
        if (ret != 0) {
6245
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6246
0
            return -1;
6247
0
        }
6248
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6249
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6250
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6251
1
        std::unique_ptr<Transaction> txn;
6252
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6253
1
        if (err != TxnErrorCode::TXN_OK) {
6254
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6255
0
            return -1;
6256
0
        }
6257
        // Remove txn index kv
6258
1
        auto index_key = txn_index_key({instance_id_, txn_id});
6259
1
        txn->remove(index_key);
6260
        // Remove txn info kv
6261
1
        std::string info_key, info_val;
6262
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6263
1
        err = txn->get(info_key, &info_val);
6264
1
        if (err != TxnErrorCode::TXN_OK) {
6265
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6266
0
            return -1;
6267
0
        }
6268
1
        TxnInfoPB txn_info;
6269
1
        if (!txn_info.ParseFromString(info_val)) {
6270
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6271
0
            return -1;
6272
0
        }
6273
1
        txn->remove(info_key);
6274
        // Remove sub txn index kvs
6275
1
        std::vector<std::string> sub_txn_index_keys;
6276
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6277
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6278
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
6279
0
        }
6280
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6281
0
            txn->remove(sub_txn_index_key);
6282
0
        }
6283
        // Update txn label
6284
1
        std::string label_key, label_val;
6285
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6286
1
        err = txn->get(label_key, &label_val);
6287
1
        if (err != TxnErrorCode::TXN_OK) {
6288
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6289
0
                         << " err=" << err;
6290
0
            return -1;
6291
0
        }
6292
1
        TxnLabelPB txn_label;
6293
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6294
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6295
0
            return -1;
6296
0
        }
6297
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6298
1
        if (it != txn_label.txn_ids().end()) {
6299
1
            txn_label.mutable_txn_ids()->erase(it);
6300
1
        }
6301
1
        if (txn_label.txn_ids().empty()) {
6302
1
            txn->remove(label_key);
6303
1
            TEST_SYNC_POINT_CALLBACK(
6304
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6305
1
        } else {
6306
0
            if (!txn_label.SerializeToString(&label_val)) {
6307
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6308
0
                return -1;
6309
0
            }
6310
0
            TEST_SYNC_POINT_CALLBACK(
6311
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6312
0
            txn->atomic_set_ver_value(label_key, label_val);
6313
0
            TEST_SYNC_POINT_CALLBACK(
6314
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6315
0
        }
6316
        // Remove recycle txn kv
6317
1
        txn->remove(k);
6318
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6319
1
        err = txn->commit();
6320
1
        if (err != TxnErrorCode::TXN_OK) {
6321
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
6322
0
                TEST_SYNC_POINT_CALLBACK(
6323
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6324
                // log the txn_id and label
6325
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6326
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6327
0
                             << " txn_label=" << txn_info.label();
6328
0
                return 1;
6329
0
            }
6330
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6331
0
            return -1;
6332
0
        }
6333
1
        ++num_recycled;
6334
6335
1
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6336
1
        return 0;
6337
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6238
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6239
23.0k
        std::string_view k1 = k;
6240
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6241
23.0k
        k1.remove_prefix(1); // Remove key space
6242
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6243
23.0k
        int ret = decode_key(&k1, &out);
6244
23.0k
        if (ret != 0) {
6245
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6246
0
            return -1;
6247
0
        }
6248
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6249
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6250
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6251
23.0k
        std::unique_ptr<Transaction> txn;
6252
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6253
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6254
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6255
0
            return -1;
6256
0
        }
6257
        // Remove txn index kv
6258
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6259
23.0k
        txn->remove(index_key);
6260
        // Remove txn info kv
6261
23.0k
        std::string info_key, info_val;
6262
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6263
23.0k
        err = txn->get(info_key, &info_val);
6264
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6265
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6266
0
            return -1;
6267
0
        }
6268
23.0k
        TxnInfoPB txn_info;
6269
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6270
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6271
0
            return -1;
6272
0
        }
6273
23.0k
        txn->remove(info_key);
6274
        // Remove sub txn index kvs
6275
23.0k
        std::vector<std::string> sub_txn_index_keys;
6276
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6277
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6278
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6279
22.9k
        }
6280
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6281
22.9k
            txn->remove(sub_txn_index_key);
6282
22.9k
        }
6283
        // Update txn label
6284
23.0k
        std::string label_key, label_val;
6285
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6286
23.0k
        err = txn->get(label_key, &label_val);
6287
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6288
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6289
0
                         << " err=" << err;
6290
0
            return -1;
6291
0
        }
6292
23.0k
        TxnLabelPB txn_label;
6293
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6294
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6295
0
            return -1;
6296
0
        }
6297
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6298
23.0k
        if (it != txn_label.txn_ids().end()) {
6299
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6300
23.0k
        }
6301
23.0k
        if (txn_label.txn_ids().empty()) {
6302
23.0k
            txn->remove(label_key);
6303
23.0k
            TEST_SYNC_POINT_CALLBACK(
6304
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6305
23.0k
        } else {
6306
74
            if (!txn_label.SerializeToString(&label_val)) {
6307
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6308
0
                return -1;
6309
0
            }
6310
74
            TEST_SYNC_POINT_CALLBACK(
6311
74
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6312
74
            txn->atomic_set_ver_value(label_key, label_val);
6313
74
            TEST_SYNC_POINT_CALLBACK(
6314
74
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6315
74
        }
6316
        // Remove recycle txn kv
6317
23.0k
        txn->remove(k);
6318
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6319
23.0k
        err = txn->commit();
6320
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6321
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6322
62
                TEST_SYNC_POINT_CALLBACK(
6323
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6324
                // log the txn_id and label
6325
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6326
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6327
62
                             << " txn_label=" << txn_info.label();
6328
62
                return 1;
6329
62
            }
6330
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6331
0
            return -1;
6332
62
        }
6333
23.0k
        ++num_recycled;
6334
6335
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6336
23.0k
        return 0;
6337
23.0k
    };
6338
6339
19
    auto loop_done = [&]() -> int {
6340
10
        DORIS_CLOUD_DEFER {
6341
10
            recycle_txn_info_keys.clear();
6342
10
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6340
1
        DORIS_CLOUD_DEFER {
6341
1
            recycle_txn_info_keys.clear();
6342
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6340
9
        DORIS_CLOUD_DEFER {
6341
9
            recycle_txn_info_keys.clear();
6342
9
        };
6343
10
        TEST_SYNC_POINT_CALLBACK(
6344
10
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6345
10
                &recycle_txn_info_keys);
6346
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6347
23.0k
            concurrent_delete_executor.add([&]() {
6348
23.0k
                int ret = delete_recycle_txn_kv(k);
6349
23.0k
                if (ret == 1) {
6350
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6351
54
                    for (int i = 1; i <= max_retry; ++i) {
6352
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6353
54
                        ret = delete_recycle_txn_kv(k);
6354
                        // clang-format off
6355
54
                        TEST_SYNC_POINT_CALLBACK(
6356
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6357
                        // clang-format off
6358
54
                        if (ret != 1) {
6359
18
                            break;
6360
18
                        }
6361
                        // random sleep 0-100 ms to retry
6362
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6363
36
                    }
6364
18
                }
6365
23.0k
                if (ret != 0) {
6366
9
                    LOG_WARNING("failed to delete recycle txn kv")
6367
9
                            .tag("instance id", instance_id_)
6368
9
                            .tag("key", hex(k));
6369
9
                    return -1;
6370
9
                }
6371
23.0k
                return 0;
6372
23.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6347
1
            concurrent_delete_executor.add([&]() {
6348
1
                int ret = delete_recycle_txn_kv(k);
6349
1
                if (ret == 1) {
6350
0
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6351
0
                    for (int i = 1; i <= max_retry; ++i) {
6352
0
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6353
0
                        ret = delete_recycle_txn_kv(k);
6354
                        // clang-format off
6355
0
                        TEST_SYNC_POINT_CALLBACK(
6356
0
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6357
                        // clang-format off
6358
0
                        if (ret != 1) {
6359
0
                            break;
6360
0
                        }
6361
                        // random sleep 0-100 ms to retry
6362
0
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6363
0
                    }
6364
0
                }
6365
1
                if (ret != 0) {
6366
0
                    LOG_WARNING("failed to delete recycle txn kv")
6367
0
                            .tag("instance id", instance_id_)
6368
0
                            .tag("key", hex(k));
6369
0
                    return -1;
6370
0
                }
6371
1
                return 0;
6372
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6347
23.0k
            concurrent_delete_executor.add([&]() {
6348
23.0k
                int ret = delete_recycle_txn_kv(k);
6349
23.0k
                if (ret == 1) {
6350
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6351
54
                    for (int i = 1; i <= max_retry; ++i) {
6352
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6353
54
                        ret = delete_recycle_txn_kv(k);
6354
                        // clang-format off
6355
54
                        TEST_SYNC_POINT_CALLBACK(
6356
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6357
                        // clang-format off
6358
54
                        if (ret != 1) {
6359
18
                            break;
6360
18
                        }
6361
                        // random sleep 0-100 ms to retry
6362
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6363
36
                    }
6364
18
                }
6365
23.0k
                if (ret != 0) {
6366
9
                    LOG_WARNING("failed to delete recycle txn kv")
6367
9
                            .tag("instance id", instance_id_)
6368
9
                            .tag("key", hex(k));
6369
9
                    return -1;
6370
9
                }
6371
23.0k
                return 0;
6372
23.0k
            });
6373
23.0k
        }
6374
10
        bool finished = true;
6375
10
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6376
23.0k
        for (int r : rets) {
6377
23.0k
            if (r != 0) {
6378
9
                ret = -1;
6379
9
            }
6380
23.0k
        }
6381
6382
10
        ret = finished ? ret : -1;
6383
6384
        // Update metrics after all concurrent tasks completed
6385
10
        metrics_context.total_recycled_num = num_recycled.load();
6386
10
        metrics_context.report();
6387
6388
10
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6389
6390
10
        if (ret != 0) {
6391
3
            LOG_WARNING("recycle txn kv ret!=0")
6392
3
                    .tag("finished", finished)
6393
3
                    .tag("ret", ret)
6394
3
                    .tag("instance_id", instance_id_);
6395
3
            return ret;
6396
3
        }
6397
7
        return ret;
6398
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6339
1
    auto loop_done = [&]() -> int {
6340
1
        DORIS_CLOUD_DEFER {
6341
1
            recycle_txn_info_keys.clear();
6342
1
        };
6343
1
        TEST_SYNC_POINT_CALLBACK(
6344
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6345
1
                &recycle_txn_info_keys);
6346
1
        for (const auto& k : recycle_txn_info_keys) {
6347
1
            concurrent_delete_executor.add([&]() {
6348
1
                int ret = delete_recycle_txn_kv(k);
6349
1
                if (ret == 1) {
6350
1
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6351
1
                    for (int i = 1; i <= max_retry; ++i) {
6352
1
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6353
1
                        ret = delete_recycle_txn_kv(k);
6354
                        // clang-format off
6355
1
                        TEST_SYNC_POINT_CALLBACK(
6356
1
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6357
                        // clang-format off
6358
1
                        if (ret != 1) {
6359
1
                            break;
6360
1
                        }
6361
                        // random sleep 0-100 ms to retry
6362
1
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6363
1
                    }
6364
1
                }
6365
1
                if (ret != 0) {
6366
1
                    LOG_WARNING("failed to delete recycle txn kv")
6367
1
                            .tag("instance id", instance_id_)
6368
1
                            .tag("key", hex(k));
6369
1
                    return -1;
6370
1
                }
6371
1
                return 0;
6372
1
            });
6373
1
        }
6374
1
        bool finished = true;
6375
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6376
1
        for (int r : rets) {
6377
1
            if (r != 0) {
6378
0
                ret = -1;
6379
0
            }
6380
1
        }
6381
6382
1
        ret = finished ? ret : -1;
6383
6384
        // Update metrics after all concurrent tasks completed
6385
1
        metrics_context.total_recycled_num = num_recycled.load();
6386
1
        metrics_context.report();
6387
6388
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6389
6390
1
        if (ret != 0) {
6391
0
            LOG_WARNING("recycle txn kv ret!=0")
6392
0
                    .tag("finished", finished)
6393
0
                    .tag("ret", ret)
6394
0
                    .tag("instance_id", instance_id_);
6395
0
            return ret;
6396
0
        }
6397
1
        return ret;
6398
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6339
9
    auto loop_done = [&]() -> int {
6340
9
        DORIS_CLOUD_DEFER {
6341
9
            recycle_txn_info_keys.clear();
6342
9
        };
6343
9
        TEST_SYNC_POINT_CALLBACK(
6344
9
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6345
9
                &recycle_txn_info_keys);
6346
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6347
23.0k
            concurrent_delete_executor.add([&]() {
6348
23.0k
                int ret = delete_recycle_txn_kv(k);
6349
23.0k
                if (ret == 1) {
6350
23.0k
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6351
23.0k
                    for (int i = 1; i <= max_retry; ++i) {
6352
23.0k
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6353
23.0k
                        ret = delete_recycle_txn_kv(k);
6354
                        // clang-format off
6355
23.0k
                        TEST_SYNC_POINT_CALLBACK(
6356
23.0k
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6357
                        // clang-format off
6358
23.0k
                        if (ret != 1) {
6359
23.0k
                            break;
6360
23.0k
                        }
6361
                        // random sleep 0-100 ms to retry
6362
23.0k
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6363
23.0k
                    }
6364
23.0k
                }
6365
23.0k
                if (ret != 0) {
6366
23.0k
                    LOG_WARNING("failed to delete recycle txn kv")
6367
23.0k
                            .tag("instance id", instance_id_)
6368
23.0k
                            .tag("key", hex(k));
6369
23.0k
                    return -1;
6370
23.0k
                }
6371
23.0k
                return 0;
6372
23.0k
            });
6373
23.0k
        }
6374
9
        bool finished = true;
6375
9
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6376
23.0k
        for (int r : rets) {
6377
23.0k
            if (r != 0) {
6378
9
                ret = -1;
6379
9
            }
6380
23.0k
        }
6381
6382
9
        ret = finished ? ret : -1;
6383
6384
        // Update metrics after all concurrent tasks completed
6385
9
        metrics_context.total_recycled_num = num_recycled.load();
6386
9
        metrics_context.report();
6387
6388
9
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6389
6390
9
        if (ret != 0) {
6391
3
            LOG_WARNING("recycle txn kv ret!=0")
6392
3
                    .tag("finished", finished)
6393
3
                    .tag("ret", ret)
6394
3
                    .tag("instance_id", instance_id_);
6395
3
            return ret;
6396
3
        }
6397
6
        return ret;
6398
9
    };
6399
6400
19
    if (config::enable_recycler_stats_metrics) {
6401
0
        scan_and_statistics_expired_txn_label();
6402
0
    }
6403
    // recycle_func and loop_done for scan and recycle
6404
19
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
6405
19
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
6406
19
}
6407
6408
struct CopyJobIdTuple {
6409
    std::string instance_id;
6410
    std::string stage_id;
6411
    long table_id;
6412
    std::string copy_id;
6413
    std::string stage_path;
6414
};
6415
struct BatchObjStoreAccessor {
6416
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
6417
                          TxnKv* txn_kv)
6418
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
6419
3
    ~BatchObjStoreAccessor() {
6420
3
        if (!paths_.empty()) {
6421
3
            consume();
6422
3
        }
6423
3
    }
6424
6425
    /**
6426
    * To implicitely do batch work and submit the batch delete task to s3
6427
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
6428
    *
6429
    * @param copy_job The protubuf struct consists of the copy job files.
6430
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
6431
    *            it would last until we finish the delete task, here we need pass one string value
6432
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
6433
    */
6434
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
6435
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
6436
5
        auto& file_keys = copy_file_keys_[key];
6437
5
        file_keys.log_trace =
6438
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
6439
5
                            instance_id, stage_id, table_id, copy_id, path);
6440
5
        std::string_view log_trace = file_keys.log_trace;
6441
2.03k
        for (const auto& file : copy_job.object_files()) {
6442
2.03k
            auto relative_path = file.relative_path();
6443
2.03k
            paths_.push_back(relative_path);
6444
2.03k
            file_keys.keys.push_back(copy_file_key(
6445
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
6446
2.03k
            LOG_INFO(log_trace)
6447
2.03k
                    .tag("relative_path", relative_path)
6448
2.03k
                    .tag("batch_count", batch_count_);
6449
2.03k
        }
6450
5
        LOG_INFO(log_trace)
6451
5
                .tag("objects_num", copy_job.object_files().size())
6452
5
                .tag("batch_count", batch_count_);
6453
        // 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
6454
        // recommend using delete objects when objects num is less than 10)
6455
5
        if (paths_.size() < 1000) {
6456
3
            return;
6457
3
        }
6458
2
        consume();
6459
2
    }
6460
6461
private:
6462
5
    void consume() {
6463
5
        DORIS_CLOUD_DEFER {
6464
5
            paths_.clear();
6465
5
            copy_file_keys_.clear();
6466
5
            batch_count_++;
6467
6468
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
6469
5
                        batch_count_);
6470
5
        };
6471
6472
5
        StopWatch sw;
6473
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
6474
5
        if (0 != accessor_->delete_files(paths_)) {
6475
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
6476
2
                        paths_.size(), batch_count_, sw.elapsed_us());
6477
2
            return;
6478
2
        }
6479
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
6480
3
                    paths_.size(), batch_count_, sw.elapsed_us());
6481
        // delete fdb's keys
6482
3
        for (auto& file_keys : copy_file_keys_) {
6483
3
            auto& [log_trace, keys] = file_keys.second;
6484
3
            std::unique_ptr<Transaction> txn;
6485
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
6486
0
                LOG(WARNING) << "failed to create txn";
6487
0
                continue;
6488
0
            }
6489
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6490
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6491
            // limited, should not cause the txn commit failed.
6492
1.02k
            for (const auto& key : keys) {
6493
1.02k
                txn->remove(key);
6494
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
6495
1.02k
            }
6496
3
            txn->remove(file_keys.first);
6497
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
6498
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
6499
0
                continue;
6500
0
            }
6501
3
        }
6502
3
    }
6503
    std::shared_ptr<StorageVaultAccessor> accessor_;
6504
    // the path of the s3 files to be deleted
6505
    std::vector<std::string> paths_;
6506
    struct CopyFiles {
6507
        std::string log_trace;
6508
        std::vector<std::string> keys;
6509
    };
6510
    // pair<std::string, std::vector<std::string>>
6511
    // first: instance_id_ stage_id table_id query_id
6512
    // second: keys to be deleted
6513
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
6514
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
6515
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
6516
    // which can together uniquely identifies different tasks for tracing log
6517
    uint64_t& batch_count_;
6518
    TxnKv* txn_kv_;
6519
};
6520
6521
13
int InstanceRecycler::recycle_copy_jobs() {
6522
13
    int64_t num_scanned = 0;
6523
13
    int64_t num_finished = 0;
6524
13
    int64_t num_expired = 0;
6525
13
    int64_t num_recycled = 0;
6526
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
6527
13
    uint64_t batch_count = 0;
6528
13
    const std::string task_name = "recycle_copy_jobs";
6529
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6530
6531
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
6532
6533
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6534
13
    register_recycle_task(task_name, start_time);
6535
6536
13
    DORIS_CLOUD_DEFER {
6537
13
        unregister_recycle_task(task_name);
6538
13
        int64_t cost =
6539
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6540
13
        metrics_context.finish_report();
6541
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
6542
13
                .tag("instance_id", instance_id_)
6543
13
                .tag("num_scanned", num_scanned)
6544
13
                .tag("num_finished", num_finished)
6545
13
                .tag("num_expired", num_expired)
6546
13
                .tag("num_recycled", num_recycled);
6547
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
6536
13
    DORIS_CLOUD_DEFER {
6537
13
        unregister_recycle_task(task_name);
6538
13
        int64_t cost =
6539
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6540
13
        metrics_context.finish_report();
6541
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
6542
13
                .tag("instance_id", instance_id_)
6543
13
                .tag("num_scanned", num_scanned)
6544
13
                .tag("num_finished", num_finished)
6545
13
                .tag("num_expired", num_expired)
6546
13
                .tag("num_recycled", num_recycled);
6547
13
    };
6548
6549
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
6550
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
6551
13
    std::string key0;
6552
13
    std::string key1;
6553
13
    copy_job_key(key_info0, &key0);
6554
13
    copy_job_key(key_info1, &key1);
6555
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
6556
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
6557
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
6558
16
                         this](std::string_view k, std::string_view v) -> int {
6559
16
        ++num_scanned;
6560
16
        CopyJobPB copy_job;
6561
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
6562
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
6563
0
            return -1;
6564
0
        }
6565
6566
        // decode copy job key
6567
16
        auto k1 = k;
6568
16
        k1.remove_prefix(1);
6569
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6570
16
        decode_key(&k1, &out);
6571
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
6572
        // -> CopyJobPB
6573
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
6574
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
6575
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
6576
6577
16
        bool check_storage = true;
6578
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
6579
12
            ++num_finished;
6580
6581
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
6582
7
                auto it = stage_accessor_map.find(stage_id);
6583
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
6584
7
                std::string_view path;
6585
7
                if (it != stage_accessor_map.end()) {
6586
2
                    accessor = it->second;
6587
5
                } else {
6588
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
6589
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
6590
5
                                                      &inner_accessor);
6591
5
                    if (ret < 0) { // error
6592
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
6593
0
                        return -1;
6594
5
                    } else if (ret == 0) {
6595
3
                        path = inner_accessor->uri();
6596
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
6597
3
                                inner_accessor, batch_count, txn_kv_.get());
6598
3
                        stage_accessor_map.emplace(stage_id, accessor);
6599
3
                    } else { // stage not found, skip check storage
6600
2
                        check_storage = false;
6601
2
                    }
6602
5
                }
6603
7
                if (check_storage) {
6604
                    // TODO delete objects with key and etag is not supported
6605
5
                    accessor->add(std::move(copy_job), std::string(k),
6606
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
6607
5
                    return 0;
6608
5
                }
6609
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
6610
5
                int64_t current_time =
6611
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6612
5
                if (copy_job.finish_time_ms() > 0) {
6613
2
                    if (!config::force_immediate_recycle &&
6614
2
                        current_time < copy_job.finish_time_ms() +
6615
2
                                               config::copy_job_max_retention_second * 1000) {
6616
1
                        return 0;
6617
1
                    }
6618
3
                } else {
6619
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
6620
3
                    if (!config::force_immediate_recycle &&
6621
3
                        current_time < copy_job.start_time_ms() +
6622
3
                                               config::copy_job_max_retention_second * 1000) {
6623
1
                        return 0;
6624
1
                    }
6625
3
                }
6626
5
            }
6627
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
6628
4
            int64_t current_time =
6629
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6630
            // if copy job is timeout: delete all copy file kvs and copy job kv
6631
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
6632
2
                return 0;
6633
2
            }
6634
2
            ++num_expired;
6635
2
        }
6636
6637
        // delete all copy files
6638
7
        std::vector<std::string> copy_file_keys;
6639
70
        for (auto& file : copy_job.object_files()) {
6640
70
            copy_file_keys.push_back(copy_file_key(
6641
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
6642
70
        }
6643
7
        std::unique_ptr<Transaction> txn;
6644
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
6645
0
            LOG(WARNING) << "failed to create txn";
6646
0
            return -1;
6647
0
        }
6648
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6649
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6650
        // limited, should not cause the txn commit failed.
6651
70
        for (const auto& key : copy_file_keys) {
6652
70
            txn->remove(key);
6653
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
6654
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
6655
70
                      << ", query_id=" << copy_id;
6656
70
        }
6657
7
        txn->remove(k);
6658
7
        TxnErrorCode err = txn->commit();
6659
7
        if (err != TxnErrorCode::TXN_OK) {
6660
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
6661
0
            return -1;
6662
0
        }
6663
6664
7
        metrics_context.total_recycled_num = ++num_recycled;
6665
7
        metrics_context.report();
6666
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6667
7
        return 0;
6668
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
6558
16
                         this](std::string_view k, std::string_view v) -> int {
6559
16
        ++num_scanned;
6560
16
        CopyJobPB copy_job;
6561
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
6562
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
6563
0
            return -1;
6564
0
        }
6565
6566
        // decode copy job key
6567
16
        auto k1 = k;
6568
16
        k1.remove_prefix(1);
6569
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6570
16
        decode_key(&k1, &out);
6571
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
6572
        // -> CopyJobPB
6573
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
6574
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
6575
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
6576
6577
16
        bool check_storage = true;
6578
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
6579
12
            ++num_finished;
6580
6581
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
6582
7
                auto it = stage_accessor_map.find(stage_id);
6583
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
6584
7
                std::string_view path;
6585
7
                if (it != stage_accessor_map.end()) {
6586
2
                    accessor = it->second;
6587
5
                } else {
6588
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
6589
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
6590
5
                                                      &inner_accessor);
6591
5
                    if (ret < 0) { // error
6592
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
6593
0
                        return -1;
6594
5
                    } else if (ret == 0) {
6595
3
                        path = inner_accessor->uri();
6596
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
6597
3
                                inner_accessor, batch_count, txn_kv_.get());
6598
3
                        stage_accessor_map.emplace(stage_id, accessor);
6599
3
                    } else { // stage not found, skip check storage
6600
2
                        check_storage = false;
6601
2
                    }
6602
5
                }
6603
7
                if (check_storage) {
6604
                    // TODO delete objects with key and etag is not supported
6605
5
                    accessor->add(std::move(copy_job), std::string(k),
6606
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
6607
5
                    return 0;
6608
5
                }
6609
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
6610
5
                int64_t current_time =
6611
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6612
5
                if (copy_job.finish_time_ms() > 0) {
6613
2
                    if (!config::force_immediate_recycle &&
6614
2
                        current_time < copy_job.finish_time_ms() +
6615
2
                                               config::copy_job_max_retention_second * 1000) {
6616
1
                        return 0;
6617
1
                    }
6618
3
                } else {
6619
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
6620
3
                    if (!config::force_immediate_recycle &&
6621
3
                        current_time < copy_job.start_time_ms() +
6622
3
                                               config::copy_job_max_retention_second * 1000) {
6623
1
                        return 0;
6624
1
                    }
6625
3
                }
6626
5
            }
6627
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
6628
4
            int64_t current_time =
6629
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6630
            // if copy job is timeout: delete all copy file kvs and copy job kv
6631
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
6632
2
                return 0;
6633
2
            }
6634
2
            ++num_expired;
6635
2
        }
6636
6637
        // delete all copy files
6638
7
        std::vector<std::string> copy_file_keys;
6639
70
        for (auto& file : copy_job.object_files()) {
6640
70
            copy_file_keys.push_back(copy_file_key(
6641
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
6642
70
        }
6643
7
        std::unique_ptr<Transaction> txn;
6644
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
6645
0
            LOG(WARNING) << "failed to create txn";
6646
0
            return -1;
6647
0
        }
6648
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6649
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6650
        // limited, should not cause the txn commit failed.
6651
70
        for (const auto& key : copy_file_keys) {
6652
70
            txn->remove(key);
6653
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
6654
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
6655
70
                      << ", query_id=" << copy_id;
6656
70
        }
6657
7
        txn->remove(k);
6658
7
        TxnErrorCode err = txn->commit();
6659
7
        if (err != TxnErrorCode::TXN_OK) {
6660
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
6661
0
            return -1;
6662
0
        }
6663
6664
7
        metrics_context.total_recycled_num = ++num_recycled;
6665
7
        metrics_context.report();
6666
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6667
7
        return 0;
6668
7
    };
6669
6670
13
    if (config::enable_recycler_stats_metrics) {
6671
0
        scan_and_statistics_copy_jobs();
6672
0
    }
6673
    // recycle_func and loop_done for scan and recycle
6674
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
6675
13
}
6676
6677
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
6678
                                             const StagePB::StageType& stage_type,
6679
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
6680
5
#ifdef UNIT_TEST
6681
    // In unit test, external use the same accessor as the internal stage
6682
5
    auto it = accessor_map_.find(stage_id);
6683
5
    if (it != accessor_map_.end()) {
6684
3
        *accessor = it->second;
6685
3
    } else {
6686
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
6687
2
        return 1;
6688
2
    }
6689
#else
6690
    // init s3 accessor and add to accessor map
6691
    auto stage_it =
6692
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
6693
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
6694
6695
    if (stage_it == instance_info_.stages().end()) {
6696
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
6697
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
6698
        return 1;
6699
    }
6700
6701
    const auto& object_store_info = stage_it->obj_info();
6702
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
6703
6704
    S3Conf s3_conf;
6705
    if (stage_type == StagePB::EXTERNAL) {
6706
        if (stage_access_type == StagePB::AKSK) {
6707
            auto conf = S3Conf::from_obj_store_info(object_store_info);
6708
            if (!conf) {
6709
                return -1;
6710
            }
6711
6712
            s3_conf = std::move(*conf);
6713
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
6714
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
6715
            if (!conf) {
6716
                return -1;
6717
            }
6718
6719
            s3_conf = std::move(*conf);
6720
            if (instance_info_.ram_user().has_encryption_info()) {
6721
                AkSkPair plain_ak_sk_pair;
6722
                int ret = decrypt_ak_sk_helper(
6723
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
6724
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
6725
                if (ret != 0) {
6726
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
6727
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
6728
                    return -1;
6729
                }
6730
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
6731
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
6732
            } else {
6733
                s3_conf.ak = instance_info_.ram_user().ak();
6734
                s3_conf.sk = instance_info_.ram_user().sk();
6735
            }
6736
        } else {
6737
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
6738
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
6739
            return -1;
6740
        }
6741
    } else if (stage_type == StagePB::INTERNAL) {
6742
        int idx = stoi(object_store_info.id());
6743
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6744
            LOG(WARNING) << "invalid idx: " << idx;
6745
            return -1;
6746
        }
6747
6748
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
6749
        auto conf = S3Conf::from_obj_store_info(old_obj);
6750
        if (!conf) {
6751
            return -1;
6752
        }
6753
6754
        s3_conf = std::move(*conf);
6755
        s3_conf.prefix = object_store_info.prefix();
6756
    } else {
6757
        LOG(WARNING) << "unknown stage type " << stage_type;
6758
        return -1;
6759
    }
6760
6761
    std::shared_ptr<S3Accessor> s3_accessor;
6762
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
6763
    if (ret != 0) {
6764
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
6765
        return -1;
6766
    }
6767
6768
    *accessor = std::move(s3_accessor);
6769
#endif
6770
3
    return 0;
6771
5
}
6772
6773
11
int InstanceRecycler::recycle_stage() {
6774
11
    int64_t num_scanned = 0;
6775
11
    int64_t num_recycled = 0;
6776
11
    const std::string task_name = "recycle_stage";
6777
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6778
6779
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
6780
6781
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6782
11
    register_recycle_task(task_name, start_time);
6783
6784
11
    DORIS_CLOUD_DEFER {
6785
11
        unregister_recycle_task(task_name);
6786
11
        int64_t cost =
6787
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6788
11
        metrics_context.finish_report();
6789
11
        LOG_WARNING("recycle stage, cost={}s", cost)
6790
11
                .tag("instance_id", instance_id_)
6791
11
                .tag("num_scanned", num_scanned)
6792
11
                .tag("num_recycled", num_recycled);
6793
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
6784
11
    DORIS_CLOUD_DEFER {
6785
11
        unregister_recycle_task(task_name);
6786
11
        int64_t cost =
6787
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6788
11
        metrics_context.finish_report();
6789
11
        LOG_WARNING("recycle stage, cost={}s", cost)
6790
11
                .tag("instance_id", instance_id_)
6791
11
                .tag("num_scanned", num_scanned)
6792
11
                .tag("num_recycled", num_recycled);
6793
11
    };
6794
6795
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
6796
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
6797
11
    std::string key0 = recycle_stage_key(key_info0);
6798
11
    std::string key1 = recycle_stage_key(key_info1);
6799
6800
11
    std::vector<std::string_view> stage_keys;
6801
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
6802
11
                         this](std::string_view k, std::string_view v) -> int {
6803
1
        ++num_scanned;
6804
1
        RecycleStagePB recycle_stage;
6805
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
6806
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
6807
0
            return -1;
6808
0
        }
6809
6810
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
6811
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6812
0
            LOG(WARNING) << "invalid idx: " << idx;
6813
0
            return -1;
6814
0
        }
6815
6816
1
        std::shared_ptr<StorageVaultAccessor> accessor;
6817
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
6818
1
                [&] {
6819
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
6820
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
6821
1
                    if (!s3_conf) {
6822
1
                        return -1;
6823
1
                    }
6824
6825
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
6826
1
                    std::shared_ptr<S3Accessor> s3_accessor;
6827
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
6828
1
                    if (ret != 0) {
6829
1
                        return -1;
6830
1
                    }
6831
6832
1
                    accessor = std::move(s3_accessor);
6833
1
                    return 0;
6834
1
                }(),
6835
1
                "recycle_stage:get_accessor", &accessor);
6836
6837
1
        if (ret != 0) {
6838
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
6839
0
            return ret;
6840
0
        }
6841
6842
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
6843
1
                .tag("instance_id", instance_id_)
6844
1
                .tag("stage_id", recycle_stage.stage().stage_id())
6845
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
6846
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
6847
1
                .tag("obj_info_id", idx)
6848
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
6849
1
        ret = accessor->delete_all();
6850
1
        if (ret != 0) {
6851
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
6852
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
6853
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
6854
0
                         << ", ret=" << ret;
6855
0
            return -1;
6856
0
        }
6857
1
        metrics_context.total_recycled_num = ++num_recycled;
6858
1
        metrics_context.report();
6859
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
6860
1
        stage_keys.push_back(k);
6861
1
        return 0;
6862
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6802
1
                         this](std::string_view k, std::string_view v) -> int {
6803
1
        ++num_scanned;
6804
1
        RecycleStagePB recycle_stage;
6805
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
6806
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
6807
0
            return -1;
6808
0
        }
6809
6810
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
6811
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6812
0
            LOG(WARNING) << "invalid idx: " << idx;
6813
0
            return -1;
6814
0
        }
6815
6816
1
        std::shared_ptr<StorageVaultAccessor> accessor;
6817
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
6818
1
                [&] {
6819
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
6820
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
6821
1
                    if (!s3_conf) {
6822
1
                        return -1;
6823
1
                    }
6824
6825
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
6826
1
                    std::shared_ptr<S3Accessor> s3_accessor;
6827
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
6828
1
                    if (ret != 0) {
6829
1
                        return -1;
6830
1
                    }
6831
6832
1
                    accessor = std::move(s3_accessor);
6833
1
                    return 0;
6834
1
                }(),
6835
1
                "recycle_stage:get_accessor", &accessor);
6836
6837
1
        if (ret != 0) {
6838
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
6839
0
            return ret;
6840
0
        }
6841
6842
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
6843
1
                .tag("instance_id", instance_id_)
6844
1
                .tag("stage_id", recycle_stage.stage().stage_id())
6845
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
6846
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
6847
1
                .tag("obj_info_id", idx)
6848
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
6849
1
        ret = accessor->delete_all();
6850
1
        if (ret != 0) {
6851
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
6852
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
6853
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
6854
0
                         << ", ret=" << ret;
6855
0
            return -1;
6856
0
        }
6857
1
        metrics_context.total_recycled_num = ++num_recycled;
6858
1
        metrics_context.report();
6859
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
6860
1
        stage_keys.push_back(k);
6861
1
        return 0;
6862
1
    };
6863
6864
11
    auto loop_done = [&stage_keys, this]() -> int {
6865
1
        if (stage_keys.empty()) return 0;
6866
1
        DORIS_CLOUD_DEFER {
6867
1
            stage_keys.clear();
6868
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6866
1
        DORIS_CLOUD_DEFER {
6867
1
            stage_keys.clear();
6868
1
        };
6869
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
6870
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
6871
0
            return -1;
6872
0
        }
6873
1
        return 0;
6874
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
6864
1
    auto loop_done = [&stage_keys, this]() -> int {
6865
1
        if (stage_keys.empty()) return 0;
6866
1
        DORIS_CLOUD_DEFER {
6867
1
            stage_keys.clear();
6868
1
        };
6869
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
6870
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
6871
0
            return -1;
6872
0
        }
6873
1
        return 0;
6874
1
    };
6875
11
    if (config::enable_recycler_stats_metrics) {
6876
0
        scan_and_statistics_stage();
6877
0
    }
6878
    // recycle_func and loop_done for scan and recycle
6879
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
6880
11
}
6881
6882
10
int InstanceRecycler::recycle_expired_stage_objects() {
6883
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
6884
6885
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6886
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
6887
6888
10
    DORIS_CLOUD_DEFER {
6889
10
        int64_t cost =
6890
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6891
10
        metrics_context.finish_report();
6892
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
6893
10
                .tag("instance_id", instance_id_);
6894
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
6888
10
    DORIS_CLOUD_DEFER {
6889
10
        int64_t cost =
6890
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6891
10
        metrics_context.finish_report();
6892
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
6893
10
                .tag("instance_id", instance_id_);
6894
10
    };
6895
6896
10
    int ret = 0;
6897
6898
10
    if (config::enable_recycler_stats_metrics) {
6899
0
        scan_and_statistics_expired_stage_objects();
6900
0
    }
6901
6902
10
    for (const auto& stage : instance_info_.stages()) {
6903
0
        std::stringstream ss;
6904
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
6905
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
6906
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
6907
0
           << ", prefix=" << stage.obj_info().prefix();
6908
6909
0
        if (stopped()) {
6910
0
            break;
6911
0
        }
6912
0
        if (stage.type() == StagePB::EXTERNAL) {
6913
0
            continue;
6914
0
        }
6915
0
        int idx = stoi(stage.obj_info().id());
6916
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6917
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
6918
0
            continue;
6919
0
        }
6920
6921
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
6922
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
6923
0
        if (!s3_conf) {
6924
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
6925
0
            continue;
6926
0
        }
6927
6928
0
        s3_conf->prefix = stage.obj_info().prefix();
6929
0
        std::shared_ptr<S3Accessor> accessor;
6930
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
6931
0
        if (ret1 != 0) {
6932
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
6933
0
            ret = -1;
6934
0
            continue;
6935
0
        }
6936
6937
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
6938
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
6939
0
            ret = -1;
6940
0
            continue;
6941
0
        }
6942
6943
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
6944
0
        int64_t expiration_time =
6945
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
6946
0
                config::internal_stage_objects_expire_time_second;
6947
0
        if (config::force_immediate_recycle) {
6948
0
            expiration_time = INT64_MAX;
6949
0
        }
6950
0
        ret1 = accessor->delete_all(expiration_time);
6951
0
        if (ret1 != 0) {
6952
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
6953
0
                         << ss.str();
6954
0
            ret = -1;
6955
0
            continue;
6956
0
        }
6957
0
        metrics_context.total_recycled_num++;
6958
0
        metrics_context.report();
6959
0
    }
6960
10
    return ret;
6961
10
}
6962
6963
193
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
6964
193
    std::lock_guard lock(recycle_tasks_mutex);
6965
193
    running_recycle_tasks[task_name] = start_time;
6966
193
}
6967
6968
193
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
6969
193
    std::lock_guard lock(recycle_tasks_mutex);
6970
193
    DCHECK(running_recycle_tasks[task_name] > 0);
6971
193
    running_recycle_tasks.erase(task_name);
6972
193
}
6973
6974
21
bool InstanceRecycler::check_recycle_tasks() {
6975
21
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
6976
21
    {
6977
21
        std::lock_guard lock(recycle_tasks_mutex);
6978
21
        tmp_running_recycle_tasks = running_recycle_tasks;
6979
21
    }
6980
6981
21
    bool found = false;
6982
21
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6983
21
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
6984
20
        int64_t cost = now - start_time;
6985
20
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
6986
20
            LOG_INFO("recycle task cost too much time cost={}s", cost)
6987
20
                    .tag("instance_id", instance_id_)
6988
20
                    .tag("task", task_name);
6989
20
            found = true;
6990
20
        }
6991
20
    }
6992
6993
21
    return found;
6994
21
}
6995
6996
// Scan and statistics indexes that need to be recycled
6997
0
int InstanceRecycler::scan_and_statistics_indexes() {
6998
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
6999
7000
0
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
7001
0
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
7002
0
    std::string index_key0;
7003
0
    std::string index_key1;
7004
0
    recycle_index_key(index_key_info0, &index_key0);
7005
0
    recycle_index_key(index_key_info1, &index_key1);
7006
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7007
7008
0
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7009
0
        RecycleIndexPB index_pb;
7010
0
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7011
0
            return 0;
7012
0
        }
7013
0
        int64_t current_time = ::time(nullptr);
7014
0
        if (current_time <
7015
0
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7016
0
            return 0;
7017
0
        }
7018
        // decode index_id
7019
0
        auto k1 = k;
7020
0
        k1.remove_prefix(1);
7021
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7022
0
        decode_key(&k1, &out);
7023
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7024
0
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7025
0
        std::unique_ptr<Transaction> txn;
7026
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7027
0
        if (err != TxnErrorCode::TXN_OK) {
7028
0
            return 0;
7029
0
        }
7030
0
        std::string val;
7031
0
        err = txn->get(k, &val);
7032
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7033
0
            return 0;
7034
0
        }
7035
0
        if (err != TxnErrorCode::TXN_OK) {
7036
0
            return 0;
7037
0
        }
7038
0
        index_pb.Clear();
7039
0
        if (!index_pb.ParseFromString(val)) {
7040
0
            return 0;
7041
0
        }
7042
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7043
0
            return 0;
7044
0
        }
7045
0
        metrics_context.total_need_recycle_num++;
7046
0
        return 0;
7047
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
7048
7049
0
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
7050
0
    metrics_context.report(true);
7051
0
    segment_metrics_context_.report(true);
7052
0
    tablet_metrics_context_.report(true);
7053
0
    return ret;
7054
0
}
7055
7056
// Scan and statistics partitions that need to be recycled
7057
0
int InstanceRecycler::scan_and_statistics_partitions() {
7058
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
7059
7060
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
7061
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
7062
0
    std::string part_key0;
7063
0
    std::string part_key1;
7064
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7065
7066
0
    recycle_partition_key(part_key_info0, &part_key0);
7067
0
    recycle_partition_key(part_key_info1, &part_key1);
7068
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
7069
0
        RecyclePartitionPB part_pb;
7070
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
7071
0
            return 0;
7072
0
        }
7073
0
        int64_t current_time = ::time(nullptr);
7074
0
        if (current_time <
7075
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
7076
0
            return 0;
7077
0
        }
7078
        // decode partition_id
7079
0
        auto k1 = k;
7080
0
        k1.remove_prefix(1);
7081
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7082
0
        decode_key(&k1, &out);
7083
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
7084
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
7085
        // Change state to RECYCLING
7086
0
        std::unique_ptr<Transaction> txn;
7087
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7088
0
        if (err != TxnErrorCode::TXN_OK) {
7089
0
            return 0;
7090
0
        }
7091
0
        std::string val;
7092
0
        err = txn->get(k, &val);
7093
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7094
0
            return 0;
7095
0
        }
7096
0
        if (err != TxnErrorCode::TXN_OK) {
7097
0
            return 0;
7098
0
        }
7099
0
        part_pb.Clear();
7100
0
        if (!part_pb.ParseFromString(val)) {
7101
0
            return 0;
7102
0
        }
7103
        // Partitions with PREPARED state MUST have no data
7104
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
7105
0
        int ret = 0;
7106
0
        for (int64_t index_id : part_pb.index_id()) {
7107
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
7108
0
                                            partition_id, is_empty_tablet) != 0) {
7109
0
                ret = 0;
7110
0
            }
7111
0
        }
7112
0
        metrics_context.total_need_recycle_num++;
7113
0
        return ret;
7114
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_
7115
7116
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
7117
0
    metrics_context.report(true);
7118
0
    segment_metrics_context_.report(true);
7119
0
    tablet_metrics_context_.report(true);
7120
0
    return ret;
7121
0
}
7122
7123
// Scan and statistics rowsets that need to be recycled
7124
0
int InstanceRecycler::scan_and_statistics_rowsets() {
7125
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
7126
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
7127
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
7128
0
    std::string recyc_rs_key0;
7129
0
    std::string recyc_rs_key1;
7130
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
7131
0
                recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
7132
0
       int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7133
7134
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
7135
0
        RecycleRowsetPB rowset;
7136
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7137
0
            return 0;
7138
0
        }
7139
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
7140
0
        int64_t current_time = ::time(nullptr);
7141
0
        if (current_time <
7142
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
7143
0
            return 0;
7144
0
        }
7145
7146
0
        if (!rowset.has_type()) {
7147
0
            if (!rowset.has_resource_id()) [[unlikely]] {
7148
0
                return 0;
7149
0
            }
7150
0
            if (rowset.resource_id().empty()) [[unlikely]] {
7151
0
                return 0;
7152
0
            }
7153
0
            metrics_context.total_need_recycle_num++;
7154
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7155
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
7156
0
            segment_metrics_context_.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7157
0
            return 0;
7158
0
        }
7159
7160
0
        if(!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled()) {
7161
0
            return 0;
7162
0
        }
7163
7164
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
7165
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
7166
0
                return 0;
7167
0
            }
7168
0
        }
7169
0
        metrics_context.total_need_recycle_num++;
7170
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
7171
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
7172
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
7173
0
        return 0;
7174
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_
7175
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
7176
0
    metrics_context.report(true);
7177
0
    segment_metrics_context_.report(true);
7178
0
    return ret;
7179
0
}
7180
7181
// Scan and statistics tmp_rowsets that need to be recycled
7182
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
7183
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
7184
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
7185
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
7186
0
    std::string tmp_rs_key0;
7187
0
    std::string tmp_rs_key1;
7188
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
7189
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
7190
7191
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7192
7193
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
7194
0
        doris::RowsetMetaCloudPB rowset;
7195
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7196
0
            return 0;
7197
0
        }
7198
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
7199
0
        int64_t current_time = ::time(nullptr);
7200
0
        if (current_time < expiration) {
7201
0
            return 0;
7202
0
        }
7203
7204
0
        DCHECK_GT(rowset.txn_id(), 0)
7205
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
7206
7207
0
        if(!rowset.has_is_recycled() || !rowset.is_recycled()) {
7208
0
            return 0;
7209
0
        }
7210
7211
0
        if (!rowset.has_resource_id()) {
7212
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
7213
0
                return 0;
7214
0
            }
7215
0
            return 0;
7216
0
        }
7217
7218
0
        metrics_context.total_need_recycle_num++;
7219
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
7220
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
7221
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
7222
0
        return 0;
7223
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_
7224
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
7225
0
    metrics_context.report(true);
7226
0
    segment_metrics_context_.report(true);
7227
0
    return ret;
7228
0
}
7229
7230
// Scan and statistics abort_timeout_txn that need to be recycled
7231
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
7232
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
7233
7234
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
7235
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7236
0
    std::string begin_txn_running_key;
7237
0
    std::string end_txn_running_key;
7238
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
7239
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
7240
7241
0
    int64_t current_time =
7242
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7243
7244
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
7245
0
                                               std::string_view k, std::string_view v) -> int {
7246
0
        std::unique_ptr<Transaction> txn;
7247
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7248
0
        if (err != TxnErrorCode::TXN_OK) {
7249
0
            return 0;
7250
0
        }
7251
0
        std::string_view k1 = k;
7252
0
        k1.remove_prefix(1);
7253
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7254
0
        if (decode_key(&k1, &out) != 0) {
7255
0
            return 0;
7256
0
        }
7257
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7258
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7259
        // Update txn_info
7260
0
        std::string txn_inf_key, txn_inf_val;
7261
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
7262
0
        err = txn->get(txn_inf_key, &txn_inf_val);
7263
0
        if (err != TxnErrorCode::TXN_OK) {
7264
0
            return 0;
7265
0
        }
7266
0
        TxnInfoPB txn_info;
7267
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
7268
0
            return 0;
7269
0
        }
7270
7271
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
7272
0
            TxnRunningPB txn_running_pb;
7273
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7274
0
                return 0;
7275
0
            }
7276
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7277
0
                return 0;
7278
0
            }
7279
0
            metrics_context.total_need_recycle_num++;
7280
0
        }
7281
0
        return 0;
7282
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_
7283
7284
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key, std::move(handle_abort_timeout_txn_kv));
7285
0
    metrics_context.report(true);
7286
0
    return ret;
7287
0
}
7288
7289
// Scan and statistics expired_txn_label that need to be recycled
7290
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
7291
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
7292
7293
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7294
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7295
0
    std::string begin_recycle_txn_key;
7296
0
    std::string end_recycle_txn_key;
7297
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7298
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7299
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7300
0
    int64_t current_time_ms =
7301
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7302
7303
    // for calculate the total num or bytes of recyled objects
7304
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
7305
0
        RecycleTxnPB recycle_txn_pb;
7306
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7307
0
            return 0;
7308
0
        }
7309
0
        if ((config::force_immediate_recycle) ||
7310
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7311
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7312
0
             current_time_ms)) {
7313
0
            metrics_context.total_need_recycle_num++;
7314
0
        }
7315
0
        return 0;
7316
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_
7317
7318
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key, std::move(handle_expired_txn_label_kv));
7319
0
    metrics_context.report(true);
7320
0
    return ret;
7321
0
}
7322
7323
// Scan and statistics copy_jobs that need to be recycled
7324
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
7325
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
7326
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7327
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7328
0
    std::string key0;
7329
0
    std::string key1;
7330
0
    copy_job_key(key_info0, &key0);
7331
0
    copy_job_key(key_info1, &key1);
7332
7333
    // for calculate the total num or bytes of recyled objects
7334
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
7335
0
        CopyJobPB copy_job;
7336
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7337
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7338
0
            return 0;
7339
0
        }
7340
7341
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7342
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
7343
0
                int64_t current_time =
7344
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7345
0
                if (copy_job.finish_time_ms() > 0) {
7346
0
                    if (!config::force_immediate_recycle &&
7347
0
                        current_time < copy_job.finish_time_ms() +
7348
0
                                               config::copy_job_max_retention_second * 1000) {
7349
0
                        return 0;
7350
0
                    }
7351
0
                } else {
7352
0
                    if (!config::force_immediate_recycle &&
7353
0
                        current_time < copy_job.start_time_ms() +
7354
0
                                               config::copy_job_max_retention_second * 1000) {
7355
0
                        return 0;
7356
0
                    }
7357
0
                }
7358
0
            }
7359
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7360
0
            int64_t current_time =
7361
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7362
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7363
0
                return 0;
7364
0
            }
7365
0
        }
7366
0
        metrics_context.total_need_recycle_num++;
7367
0
        return 0;
7368
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_
7369
7370
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7371
0
    metrics_context.report(true);
7372
0
    return ret;
7373
0
}
7374
7375
// Scan and statistics stage that need to be recycled
7376
0
int InstanceRecycler::scan_and_statistics_stage() {
7377
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
7378
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7379
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7380
0
    std::string key0 = recycle_stage_key(key_info0);
7381
0
    std::string key1 = recycle_stage_key(key_info1);
7382
7383
    // for calculate the total num or bytes of recyled objects
7384
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
7385
0
                                                        std::string_view v) -> int {
7386
0
        RecycleStagePB recycle_stage;
7387
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7388
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7389
0
            return 0;
7390
0
        }
7391
7392
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
7393
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7394
0
            LOG(WARNING) << "invalid idx: " << idx;
7395
0
            return 0;
7396
0
        }
7397
7398
0
        std::shared_ptr<StorageVaultAccessor> accessor;
7399
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7400
0
                [&] {
7401
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7402
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7403
0
                    if (!s3_conf) {
7404
0
                        return 0;
7405
0
                    }
7406
7407
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7408
0
                    std::shared_ptr<S3Accessor> s3_accessor;
7409
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7410
0
                    if (ret != 0) {
7411
0
                        return 0;
7412
0
                    }
7413
7414
0
                    accessor = std::move(s3_accessor);
7415
0
                    return 0;
7416
0
                }(),
7417
0
                "recycle_stage:get_accessor", &accessor);
7418
7419
0
        if (ret != 0) {
7420
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7421
0
            return 0;
7422
0
        }
7423
7424
0
        metrics_context.total_need_recycle_num++;
7425
0
        return 0;
7426
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_
7427
7428
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7429
0
    metrics_context.report(true);
7430
0
    return ret;
7431
0
}
7432
7433
// Scan and statistics expired_stage_objects that need to be recycled
7434
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
7435
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7436
7437
    // for calculate the total num or bytes of recyled objects
7438
0
    auto scan_and_statistics = [&metrics_context, this]() {
7439
0
        for (const auto& stage : instance_info_.stages()) {
7440
0
            if (stopped()) {
7441
0
                break;
7442
0
            }
7443
0
            if (stage.type() == StagePB::EXTERNAL) {
7444
0
                continue;
7445
0
            }
7446
0
            int idx = stoi(stage.obj_info().id());
7447
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
7448
0
                continue;
7449
0
            }
7450
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
7451
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7452
0
            if (!s3_conf) {
7453
0
                continue;
7454
0
            }
7455
0
            s3_conf->prefix = stage.obj_info().prefix();
7456
0
            std::shared_ptr<S3Accessor> accessor;
7457
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
7458
0
            if (ret1 != 0) {
7459
0
                continue;
7460
0
            }
7461
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7462
0
                continue;
7463
0
            }
7464
0
            metrics_context.total_need_recycle_num++;
7465
0
        }
7466
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
7467
7468
0
    scan_and_statistics();
7469
0
    metrics_context.report(true);
7470
0
    return 0;
7471
0
}
7472
7473
// Scan and statistics versions that need to be recycled
7474
0
int InstanceRecycler::scan_and_statistics_versions() {
7475
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
7476
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
7477
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
7478
7479
0
    int64_t last_scanned_table_id = 0;
7480
0
    bool is_recycled = false; // Is last scanned kv recycled
7481
    // for calculate the total num or bytes of recyled objects
7482
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
7483
0
                                       std::string_view k, std::string_view) {
7484
0
        auto k1 = k;
7485
0
        k1.remove_prefix(1);
7486
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
7487
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7488
0
        decode_key(&k1, &out);
7489
0
        DCHECK_EQ(out.size(), 6) << k;
7490
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
7491
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
7492
0
            metrics_context.total_need_recycle_num +=
7493
0
                    is_recycled; // Version kv of this table has been recycled
7494
0
            return 0;
7495
0
        }
7496
0
        last_scanned_table_id = table_id;
7497
0
        is_recycled = false;
7498
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
7499
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
7500
0
        std::unique_ptr<Transaction> txn;
7501
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7502
0
        if (err != TxnErrorCode::TXN_OK) {
7503
0
            return 0;
7504
0
        }
7505
0
        std::unique_ptr<RangeGetIterator> iter;
7506
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
7507
0
        if (err != TxnErrorCode::TXN_OK) {
7508
0
            return 0;
7509
0
        }
7510
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
7511
0
            return 0;
7512
0
        }
7513
0
        metrics_context.total_need_recycle_num++;
7514
0
        is_recycled = true;
7515
0
        return 0;
7516
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_
7517
7518
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
7519
0
    metrics_context.report(true);
7520
0
    return ret;
7521
0
}
7522
7523
// Scan and statistics restore jobs that need to be recycled
7524
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
7525
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
7526
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
7527
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
7528
0
    std::string restore_job_key0;
7529
0
    std::string restore_job_key1;
7530
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
7531
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
7532
7533
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7534
7535
    // for calculate the total num or bytes of recyled objects
7536
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
7537
0
        RestoreJobCloudPB restore_job_pb;
7538
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
7539
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
7540
0
            return 0;
7541
0
        }
7542
0
        int64_t expiration =
7543
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
7544
0
        int64_t current_time = ::time(nullptr);
7545
0
        if (current_time < expiration) { // not expired
7546
0
            return 0;
7547
0
        }
7548
0
        metrics_context.total_need_recycle_num++;
7549
0
        if(restore_job_pb.need_recycle_data()) {
7550
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
7551
0
        }
7552
0
        return 0;
7553
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_
7554
7555
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
7556
0
    metrics_context.report(true);
7557
0
    return ret;
7558
0
}
7559
7560
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
7561
3
    if (!should_recycle_versioned_keys()) {
7562
0
        return;
7563
0
    }
7564
7565
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
7566
7567
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
7568
3
    if (recycle_checker.init() != 0) {
7569
0
        return;
7570
0
    }
7571
7572
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
7573
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
7574
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
7575
7576
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
7577
8
    for (; iter->valid(); iter->next()) {
7578
5
        OperationLogPB operation_log;
7579
5
        if (!iter->parse_value(&operation_log)) {
7580
0
            continue;
7581
0
        }
7582
7583
5
        std::string_view key = iter->key();
7584
5
        Versionstamp log_versionstamp;
7585
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
7586
0
            continue;
7587
0
        }
7588
7589
5
        OperationLogReferenceInfo ref_info;
7590
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
7591
5
                                         &ref_info)) {
7592
4
            metrics_context.total_need_recycle_num++;
7593
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
7594
4
        }
7595
5
    }
7596
7597
3
    metrics_context.report(true);
7598
3
}
7599
7600
int InstanceRecycler::classify_rowset_task_by_ref_count(
7601
60
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
7602
60
    constexpr int MAX_RETRY = 10;
7603
60
    const auto& rowset_meta = task.rowset_meta;
7604
60
    int64_t tablet_id = rowset_meta.tablet_id();
7605
60
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
7606
60
    std::string_view reference_instance_id = instance_id_;
7607
60
    if (rowset_meta.has_reference_instance_id()) {
7608
5
        reference_instance_id = rowset_meta.reference_instance_id();
7609
5
    }
7610
7611
61
    for (int i = 0; i < MAX_RETRY; ++i) {
7612
61
        std::unique_ptr<Transaction> txn;
7613
61
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7614
61
        if (err != TxnErrorCode::TXN_OK) {
7615
0
            LOG_WARNING("failed to create txn when classifying rowset task")
7616
0
                    .tag("instance_id", instance_id_)
7617
0
                    .tag("tablet_id", tablet_id)
7618
0
                    .tag("rowset_id", rowset_id)
7619
0
                    .tag("err", err);
7620
0
            return -1;
7621
0
        }
7622
7623
61
        std::string rowset_ref_count_key =
7624
61
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
7625
61
        task.rowset_ref_count_key = rowset_ref_count_key;
7626
7627
61
        int64_t ref_count = 0;
7628
61
        {
7629
61
            std::string value;
7630
61
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
7631
61
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7632
0
                ref_count = 1;
7633
61
            } else if (err != TxnErrorCode::TXN_OK) {
7634
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
7635
0
                        .tag("instance_id", instance_id_)
7636
0
                        .tag("tablet_id", tablet_id)
7637
0
                        .tag("rowset_id", rowset_id)
7638
0
                        .tag("err", err);
7639
0
                return -1;
7640
61
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
7641
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
7642
0
                        .tag("instance_id", instance_id_)
7643
0
                        .tag("tablet_id", tablet_id)
7644
0
                        .tag("rowset_id", rowset_id)
7645
0
                        .tag("value", hex(value));
7646
0
                return -1;
7647
0
            }
7648
61
        }
7649
7650
61
        if (ref_count > 1) {
7651
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
7652
12
            txn->atomic_add(rowset_ref_count_key, -1);
7653
12
            LOG_INFO("decrease rowset data ref count in classification phase")
7654
12
                    .tag("instance_id", instance_id_)
7655
12
                    .tag("tablet_id", tablet_id)
7656
12
                    .tag("rowset_id", rowset_id)
7657
12
                    .tag("ref_count", ref_count - 1)
7658
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
7659
7660
12
            if (!task.recycle_rowset_key.empty()) {
7661
0
                txn->remove(task.recycle_rowset_key);
7662
0
                LOG_INFO("remove recycle rowset key in classification phase")
7663
0
                        .tag("key", hex(task.recycle_rowset_key));
7664
0
            }
7665
12
            if (!task.non_versioned_rowset_key.empty()) {
7666
12
                txn->remove(task.non_versioned_rowset_key);
7667
12
                LOG_INFO("remove non versioned rowset key in classification phase")
7668
12
                        .tag("key", hex(task.non_versioned_rowset_key));
7669
12
            }
7670
7671
12
            err = txn->commit();
7672
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
7673
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
7674
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
7675
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
7676
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
7677
1
                continue;
7678
11
            } else if (err != TxnErrorCode::TXN_OK) {
7679
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
7680
0
                        .tag("instance_id", instance_id_)
7681
0
                        .tag("tablet_id", tablet_id)
7682
0
                        .tag("rowset_id", rowset_id)
7683
0
                        .tag("err", err);
7684
0
                return -1;
7685
0
            }
7686
11
            return 1; // handled, not added to batch delete
7687
49
        } else {
7688
            // ref_count == 1: Add to batch delete plan without modifying any KV.
7689
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
7690
49
            LOG_INFO("add rowset to batch delete plan")
7691
49
                    .tag("instance_id", instance_id_)
7692
49
                    .tag("tablet_id", tablet_id)
7693
49
                    .tag("rowset_id", rowset_id)
7694
49
                    .tag("resource_id", rowset_meta.resource_id())
7695
49
                    .tag("ref_count", ref_count);
7696
7697
49
            batch_delete_tasks.push_back(std::move(task));
7698
49
            return 0; // added to batch delete
7699
49
        }
7700
61
    }
7701
7702
0
    LOG_WARNING("failed to classify rowset task after retry")
7703
0
            .tag("instance_id", instance_id_)
7704
0
            .tag("tablet_id", tablet_id)
7705
0
            .tag("rowset_id", rowset_id)
7706
0
            .tag("retry", MAX_RETRY);
7707
0
    return -1;
7708
60
}
7709
7710
10
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
7711
10
    int ret = 0;
7712
49
    for (const auto& task : tasks) {
7713
49
        int64_t tablet_id = task.rowset_meta.tablet_id();
7714
49
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
7715
7716
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
7717
        // so we don't need to call it again here.
7718
7719
        // Remove all metadata keys in one transaction
7720
49
        std::unique_ptr<Transaction> txn;
7721
49
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7722
49
        if (err != TxnErrorCode::TXN_OK) {
7723
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
7724
0
                    .tag("instance_id", instance_id_)
7725
0
                    .tag("tablet_id", tablet_id)
7726
0
                    .tag("rowset_id", rowset_id)
7727
0
                    .tag("err", err);
7728
0
            ret = -1;
7729
0
            continue;
7730
0
        }
7731
7732
49
        std::string_view reference_instance_id = instance_id_;
7733
49
        if (task.rowset_meta.has_reference_instance_id()) {
7734
0
            reference_instance_id = task.rowset_meta.reference_instance_id();
7735
0
        }
7736
7737
49
        txn->remove(task.rowset_ref_count_key);
7738
49
        LOG_INFO("delete rowset data ref count key in cleanup phase")
7739
49
                .tag("instance_id", instance_id_)
7740
49
                .tag("tablet_id", tablet_id)
7741
49
                .tag("rowset_id", rowset_id)
7742
49
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
7743
7744
49
        std::string dbm_start_key =
7745
49
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
7746
49
        std::string dbm_end_key = meta_delete_bitmap_key(
7747
49
                {reference_instance_id, tablet_id, rowset_id,
7748
49
                 std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
7749
49
        txn->remove(dbm_start_key, dbm_end_key);
7750
49
        LOG_INFO("remove delete bitmap kv in cleanup phase")
7751
49
                .tag("instance_id", instance_id_)
7752
49
                .tag("tablet_id", tablet_id)
7753
49
                .tag("rowset_id", rowset_id)
7754
49
                .tag("begin", hex(dbm_start_key))
7755
49
                .tag("end", hex(dbm_end_key));
7756
7757
49
        std::string versioned_dbm_start_key =
7758
49
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
7759
49
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
7760
49
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
7761
49
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
7762
49
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
7763
49
                .tag("instance_id", instance_id_)
7764
49
                .tag("tablet_id", tablet_id)
7765
49
                .tag("rowset_id", rowset_id)
7766
49
                .tag("begin", hex(versioned_dbm_start_key))
7767
49
                .tag("end", hex(versioned_dbm_end_key));
7768
7769
        // Remove versioned meta rowset key
7770
49
        if (!task.versioned_rowset_key.empty()) {
7771
49
            versioned::document_remove<RowsetMetaCloudPB>(
7772
49
                txn.get(), task.versioned_rowset_key, task.versionstamp);
7773
49
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
7774
49
                    .tag("instance_id", instance_id_)
7775
49
                    .tag("tablet_id", tablet_id)
7776
49
                    .tag("rowset_id", rowset_id)
7777
49
                    .tag("key_prefix", hex(task.versioned_rowset_key));
7778
49
        }
7779
7780
49
        if (!task.non_versioned_rowset_key.empty()) {
7781
49
            txn->remove(task.non_versioned_rowset_key);
7782
49
            LOG_INFO("remove non versioned rowset key in cleanup phase")
7783
49
                    .tag("instance_id", instance_id_)
7784
49
                    .tag("tablet_id", tablet_id)
7785
49
                    .tag("rowset_id", rowset_id)
7786
49
                    .tag("key", hex(task.non_versioned_rowset_key));
7787
49
        }
7788
7789
        // Remove recycle_rowset_key last to ensure retry safety:
7790
        // if cleanup fails, this key remains and triggers next round retry.
7791
49
        if (!task.recycle_rowset_key.empty()) {
7792
0
            txn->remove(task.recycle_rowset_key);
7793
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
7794
0
                    .tag("instance_id", instance_id_)
7795
0
                    .tag("tablet_id", tablet_id)
7796
0
                    .tag("rowset_id", rowset_id)
7797
0
                    .tag("key", hex(task.recycle_rowset_key));
7798
0
        }
7799
7800
49
        err = txn->commit();
7801
49
        if (err != TxnErrorCode::TXN_OK) {
7802
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
7803
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
7804
0
                    .tag("instance_id", instance_id_)
7805
0
                    .tag("tablet_id", tablet_id)
7806
0
                    .tag("rowset_id", rowset_id)
7807
0
                    .tag("err", err);
7808
0
            ret = -1;
7809
0
            continue;
7810
0
        }
7811
7812
49
        LOG_INFO("cleanup rowset metadata success")
7813
49
                .tag("instance_id", instance_id_)
7814
49
                .tag("tablet_id", tablet_id)
7815
49
                .tag("rowset_id", rowset_id);
7816
49
    }
7817
10
    return ret;
7818
10
}
7819
7820
} // namespace doris::cloud