Coverage Report

Created: 2025-07-29 14:50

/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 <deque>
34
#include <initializer_list>
35
#include <numeric>
36
#include <string>
37
#include <string_view>
38
#include <utility>
39
40
#include "common/defer.h"
41
#include "common/stopwatch.h"
42
#include "meta-service/meta_service.h"
43
#include "meta-service/meta_service_helper.h"
44
#include "meta-service/meta_service_schema.h"
45
#include "meta-store/blob_message.h"
46
#include "meta-store/txn_kv.h"
47
#include "meta-store/txn_kv_error.h"
48
#include "meta-store/versioned_value.h"
49
#include "recycler/checker.h"
50
#include "recycler/hdfs_accessor.h"
51
#include "recycler/s3_accessor.h"
52
#include "recycler/storage_vault_accessor.h"
53
#ifdef UNIT_TEST
54
#include "../test/mock_accessor.h"
55
#endif
56
#include "common/bvars.h"
57
#include "common/config.h"
58
#include "common/encryption_util.h"
59
#include "common/logging.h"
60
#include "common/simple_thread_pool.h"
61
#include "common/util.h"
62
#include "cpp/sync_point.h"
63
#include "meta-store/keys.h"
64
#include "recycler/recycler_service.h"
65
#include "recycler/sync_executor.h"
66
#include "recycler/util.h"
67
68
namespace doris::cloud {
69
70
using namespace std::chrono;
71
72
RecyclerMetricsContext tablet_metrics_context_("global_recycler", "recycle_tablet");
73
RecyclerMetricsContext segment_metrics_context_("global_recycler", "recycle_segment");
74
75
// return 0 for success get a key, 1 for key not found, negative for error
76
0
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
77
0
    std::unique_ptr<Transaction> txn;
78
0
    TxnErrorCode err = txn_kv->create_txn(&txn);
79
0
    if (err != TxnErrorCode::TXN_OK) {
80
0
        return -1;
81
0
    }
82
0
    switch (txn->get(key, &val, true)) {
83
0
    case TxnErrorCode::TXN_OK:
84
0
        return 0;
85
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
86
0
        return 1;
87
0
    default:
88
0
        return -1;
89
0
    };
90
0
}
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
91
92
// 0 for success, negative for error
93
static int txn_get(TxnKv* txn_kv, std::string_view begin, std::string_view end,
94
220
                   std::unique_ptr<RangeGetIterator>& it) {
95
220
    std::unique_ptr<Transaction> txn;
96
220
    TxnErrorCode err = txn_kv->create_txn(&txn);
97
220
    if (err != TxnErrorCode::TXN_OK) {
98
0
        return -1;
99
0
    }
100
220
    switch (txn->get(begin, end, &it, true)) {
101
220
    case TxnErrorCode::TXN_OK:
102
220
        return 0;
103
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
104
0
        return 1;
105
0
    default:
106
0
        return -1;
107
220
    };
108
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
94
201
                   std::unique_ptr<RangeGetIterator>& it) {
95
201
    std::unique_ptr<Transaction> txn;
96
201
    TxnErrorCode err = txn_kv->create_txn(&txn);
97
201
    if (err != TxnErrorCode::TXN_OK) {
98
0
        return -1;
99
0
    }
100
201
    switch (txn->get(begin, end, &it, true)) {
101
201
    case TxnErrorCode::TXN_OK:
102
201
        return 0;
103
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
104
0
        return 1;
105
0
    default:
106
0
        return -1;
107
201
    };
108
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
94
19
                   std::unique_ptr<RangeGetIterator>& it) {
95
19
    std::unique_ptr<Transaction> txn;
96
19
    TxnErrorCode err = txn_kv->create_txn(&txn);
97
19
    if (err != TxnErrorCode::TXN_OK) {
98
0
        return -1;
99
0
    }
100
19
    switch (txn->get(begin, end, &it, true)) {
101
19
    case TxnErrorCode::TXN_OK:
102
19
        return 0;
103
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
104
0
        return 1;
105
0
    default:
106
0
        return -1;
107
19
    };
108
0
}
109
110
// return 0 for success otherwise error
111
10
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
112
10
    std::unique_ptr<Transaction> txn;
113
10
    TxnErrorCode err = txn_kv->create_txn(&txn);
114
10
    if (err != TxnErrorCode::TXN_OK) {
115
0
        return -1;
116
0
    }
117
3.04k
    for (auto k : keys) {
118
3.04k
        txn->remove(k);
119
3.04k
    }
120
10
    switch (txn->commit()) {
121
10
    case TxnErrorCode::TXN_OK:
122
10
        return 0;
123
0
    case TxnErrorCode::TXN_CONFLICT:
124
0
        return -1;
125
0
    default:
126
0
        return -1;
127
10
    }
128
10
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
111
6
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
112
6
    std::unique_ptr<Transaction> txn;
113
6
    TxnErrorCode err = txn_kv->create_txn(&txn);
114
6
    if (err != TxnErrorCode::TXN_OK) {
115
0
        return -1;
116
0
    }
117
3.02k
    for (auto k : keys) {
118
3.02k
        txn->remove(k);
119
3.02k
    }
120
6
    switch (txn->commit()) {
121
6
    case TxnErrorCode::TXN_OK:
122
6
        return 0;
123
0
    case TxnErrorCode::TXN_CONFLICT:
124
0
        return -1;
125
0
    default:
126
0
        return -1;
127
6
    }
128
6
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
111
4
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
112
4
    std::unique_ptr<Transaction> txn;
113
4
    TxnErrorCode err = txn_kv->create_txn(&txn);
114
4
    if (err != TxnErrorCode::TXN_OK) {
115
0
        return -1;
116
0
    }
117
21
    for (auto k : keys) {
118
21
        txn->remove(k);
119
21
    }
120
4
    switch (txn->commit()) {
121
4
    case TxnErrorCode::TXN_OK:
122
4
        return 0;
123
0
    case TxnErrorCode::TXN_CONFLICT:
124
0
        return -1;
125
0
    default:
126
0
        return -1;
127
4
    }
128
4
}
129
130
// return 0 for success otherwise error
131
30
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
132
30
    std::unique_ptr<Transaction> txn;
133
30
    TxnErrorCode err = txn_kv->create_txn(&txn);
134
30
    if (err != TxnErrorCode::TXN_OK) {
135
0
        return -1;
136
0
    }
137
4.00k
    for (auto& k : keys) {
138
4.00k
        txn->remove(k);
139
4.00k
    }
140
30
    switch (txn->commit()) {
141
30
    case TxnErrorCode::TXN_OK:
142
30
        return 0;
143
0
    case TxnErrorCode::TXN_CONFLICT:
144
0
        return -1;
145
0
    default:
146
0
        return -1;
147
30
    }
148
30
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
131
30
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
132
30
    std::unique_ptr<Transaction> txn;
133
30
    TxnErrorCode err = txn_kv->create_txn(&txn);
134
30
    if (err != TxnErrorCode::TXN_OK) {
135
0
        return -1;
136
0
    }
137
4.00k
    for (auto& k : keys) {
138
4.00k
        txn->remove(k);
139
4.00k
    }
140
30
    switch (txn->commit()) {
141
30
    case TxnErrorCode::TXN_OK:
142
30
        return 0;
143
0
    case TxnErrorCode::TXN_CONFLICT:
144
0
        return -1;
145
0
    default:
146
0
        return -1;
147
30
    }
148
30
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
149
150
// return 0 for success otherwise error
151
[[maybe_unused]] static int txn_remove(TxnKv* txn_kv, std::string_view begin,
152
0
                                       std::string_view end) {
153
0
    std::unique_ptr<Transaction> txn;
154
0
    TxnErrorCode err = txn_kv->create_txn(&txn);
155
0
    if (err != TxnErrorCode::TXN_OK) {
156
0
        return -1;
157
0
    }
158
0
    txn->remove(begin, end);
159
0
    switch (txn->commit()) {
160
0
    case TxnErrorCode::TXN_OK:
161
0
        return 0;
162
0
    case TxnErrorCode::TXN_CONFLICT:
163
0
        return -1;
164
0
    default:
165
0
        return -1;
166
0
    }
167
0
}
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
168
169
void scan_restore_job_rowset(
170
        Transaction* txn, const std::string& instance_id, int64_t tablet_id, MetaServiceCode& code,
171
        std::string& msg,
172
        std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>* restore_job_rs_metas);
173
174
static inline void check_recycle_task(const std::string& instance_id, const std::string& task_name,
175
                                      int64_t num_scanned, int64_t num_recycled,
176
49
                                      int64_t start_time) {
177
49
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
178
0
        int64_t cost =
179
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
180
0
        if (cost > config::recycle_task_threshold_seconds) {
181
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
182
0
                    .tag("instance_id", instance_id)
183
0
                    .tag("task", task_name)
184
0
                    .tag("num_scanned", num_scanned)
185
0
                    .tag("num_recycled", num_recycled);
186
0
        }
187
0
    }
188
49
    return;
189
49
}
recycler_test.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
176
47
                                      int64_t start_time) {
177
47
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
178
0
        int64_t cost =
179
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
180
0
        if (cost > config::recycle_task_threshold_seconds) {
181
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
182
0
                    .tag("instance_id", instance_id)
183
0
                    .tag("task", task_name)
184
0
                    .tag("num_scanned", num_scanned)
185
0
                    .tag("num_recycled", num_recycled);
186
0
        }
187
0
    }
188
47
    return;
189
47
}
recycler.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
176
2
                                      int64_t start_time) {
177
2
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
178
0
        int64_t cost =
179
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
180
0
        if (cost > config::recycle_task_threshold_seconds) {
181
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
182
0
                    .tag("instance_id", instance_id)
183
0
                    .tag("task", task_name)
184
0
                    .tag("num_scanned", num_scanned)
185
0
                    .tag("num_recycled", num_recycled);
186
0
        }
187
0
    }
188
2
    return;
189
2
}
190
191
4
Recycler::Recycler(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
192
4
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
193
194
4
    auto s3_producer_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
195
4
                                                               "s3_producer_pool");
196
4
    s3_producer_pool->start();
197
4
    auto recycle_tablet_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
198
4
                                                                  "recycle_tablet_pool");
199
4
    recycle_tablet_pool->start();
200
4
    auto group_recycle_function_pool = std::make_shared<SimpleThreadPool>(
201
4
            config::recycle_pool_parallelism, "group_recycle_function_pool");
202
4
    group_recycle_function_pool->start();
203
4
    _thread_pool_group =
204
4
            RecyclerThreadPoolGroup(std::move(s3_producer_pool), std::move(recycle_tablet_pool),
205
4
                                    std::move(group_recycle_function_pool));
206
207
4
    txn_lazy_committer_ = std::make_shared<TxnLazyCommitter>(txn_kv_);
208
4
}
209
210
4
Recycler::~Recycler() {
211
4
    if (!stopped()) {
212
0
        stop();
213
0
    }
214
4
}
215
216
4
void Recycler::instance_scanner_callback() {
217
    // sleep 60 seconds before scheduling for the launch procedure to complete:
218
    // some bad hdfs connection may cause some log to stdout stderr
219
    // which may pollute .out file and affect the script to check success
220
4
    std::this_thread::sleep_for(
221
4
            std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
222
7
    while (!stopped()) {
223
3
        std::vector<InstanceInfoPB> instances;
224
3
        get_all_instances(txn_kv_.get(), instances);
225
        // TODO(plat1ko): delete job recycle kv of non-existent instances
226
3
        LOG(INFO) << "Recycler get instances: " << [&instances] {
227
3
            std::stringstream ss;
228
30
            for (auto& i : instances) ss << ' ' << i.instance_id();
229
3
            return ss.str();
230
3
        }();
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
Line
Count
Source
226
3
        LOG(INFO) << "Recycler get instances: " << [&instances] {
227
3
            std::stringstream ss;
228
30
            for (auto& i : instances) ss << ' ' << i.instance_id();
229
3
            return ss.str();
230
3
        }();
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
231
3
        if (!instances.empty()) {
232
            // enqueue instances
233
3
            std::lock_guard lock(mtx_);
234
30
            for (auto& instance : instances) {
235
30
                if (instance_filter_.filter_out(instance.instance_id())) continue;
236
30
                auto [_, success] = pending_instance_set_.insert(instance.instance_id());
237
                // skip instance already in pending queue
238
30
                if (success) {
239
30
                    pending_instance_queue_.push_back(std::move(instance));
240
30
                }
241
30
            }
242
3
            pending_instance_cond_.notify_all();
243
3
        }
244
3
        {
245
3
            std::unique_lock lock(mtx_);
246
3
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
247
6
                               [&]() { return stopped(); });
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
247
6
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
248
3
        }
249
3
    }
250
4
}
251
252
8
void Recycler::recycle_callback() {
253
37
    while (!stopped()) {
254
36
        InstanceInfoPB instance;
255
36
        {
256
36
            std::unique_lock lock(mtx_);
257
36
            pending_instance_cond_.wait(
258
49
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
258
49
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
259
36
            if (stopped()) {
260
7
                return;
261
7
            }
262
29
            instance = std::move(pending_instance_queue_.front());
263
29
            pending_instance_queue_.pop_front();
264
29
            pending_instance_set_.erase(instance.instance_id());
265
29
        }
266
0
        auto& instance_id = instance.instance_id();
267
29
        {
268
29
            std::lock_guard lock(mtx_);
269
            // skip instance in recycling
270
29
            if (recycling_instance_map_.count(instance_id)) continue;
271
29
        }
272
29
        auto instance_recycler = std::make_shared<InstanceRecycler>(
273
29
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
274
275
29
        if (int r = instance_recycler->init(); r != 0) {
276
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
277
0
                         << " ret=" << r;
278
0
            continue;
279
0
        }
280
29
        std::string recycle_job_key;
281
29
        job_recycle_key({instance_id}, &recycle_job_key);
282
29
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
283
29
                                               ip_port_, config::recycle_interval_seconds * 1000);
284
29
        if (ret != 0) { // Prepare failed
285
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
286
20
                         << " ret=" << ret;
287
20
            continue;
288
20
        } else {
289
9
            std::lock_guard lock(mtx_);
290
9
            recycling_instance_map_.emplace(instance_id, instance_recycler);
291
9
        }
292
9
        if (stopped()) return;
293
9
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
294
9
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
295
9
        g_bvar_recycler_instance_recycle_task_concurrency << 1;
296
9
        g_bvar_recycler_instance_running_counter << 1;
297
9
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
298
9
        tablet_metrics_context_.reset();
299
9
        segment_metrics_context_.reset();
300
9
        ret = instance_recycler->do_recycle();
301
9
        tablet_metrics_context_.finish_report();
302
9
        segment_metrics_context_.finish_report();
303
9
        g_bvar_recycler_instance_recycle_task_concurrency << -1;
304
9
        g_bvar_recycler_instance_running_counter << -1;
305
        // If instance recycler has been aborted, don't finish this job
306
10
        if (!instance_recycler->stopped()) {
307
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
308
10
                                        ret == 0, ctime_ms);
309
10
        }
310
9
        {
311
9
            std::lock_guard lock(mtx_);
312
9
            recycling_instance_map_.erase(instance_id);
313
9
        }
314
315
9
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
316
9
        auto elpased_ms = now - ctime_ms;
317
9
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
318
9
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
319
9
        g_bvar_recycler_instance_next_ts.put({instance_id},
320
9
                                             now + config::recycle_interval_seconds * 1000);
321
9
        LOG(INFO) << "recycle instance done, "
322
9
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
323
9
                  << " now: " << now;
324
325
9
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
326
327
9
        LOG_WARNING("finish recycle instance")
328
9
                .tag("instance_id", instance_id)
329
9
                .tag("cost_ms", elpased_ms);
330
9
    }
331
8
}
332
333
4
void Recycler::lease_recycle_jobs() {
334
54
    while (!stopped()) {
335
50
        std::vector<std::string> instances;
336
50
        instances.reserve(recycling_instance_map_.size());
337
50
        {
338
50
            std::lock_guard lock(mtx_);
339
50
            for (auto& [id, _] : recycling_instance_map_) {
340
30
                instances.push_back(id);
341
30
            }
342
50
        }
343
50
        for (auto& i : instances) {
344
30
            std::string recycle_job_key;
345
30
            job_recycle_key({i}, &recycle_job_key);
346
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
347
30
            if (ret == 1) {
348
0
                std::lock_guard lock(mtx_);
349
0
                if (auto it = recycling_instance_map_.find(i);
350
0
                    it != recycling_instance_map_.end()) {
351
0
                    it->second->stop();
352
0
                }
353
0
            }
354
30
        }
355
50
        {
356
50
            std::unique_lock lock(mtx_);
357
50
            notifier_.wait_for(lock,
358
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
359
100
                               [&]() { return stopped(); });
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
359
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
360
50
        }
361
50
    }
362
4
}
363
364
4
void Recycler::check_recycle_tasks() {
365
7
    while (!stopped()) {
366
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
367
3
        {
368
3
            std::lock_guard lock(mtx_);
369
3
            recycling_instance_map = recycling_instance_map_;
370
3
        }
371
3
        for (auto& entry : recycling_instance_map) {
372
0
            entry.second->check_recycle_tasks();
373
0
        }
374
375
3
        std::unique_lock lock(mtx_);
376
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
377
6
                           [&]() { return stopped(); });
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
377
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
378
3
    }
379
4
}
380
381
4
int Recycler::start(brpc::Server* server) {
382
4
    instance_filter_.reset(config::recycle_whitelist, config::recycle_blacklist);
383
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
384
4
    S3Environment::getInstance();
385
386
4
    if (config::enable_checker) {
387
0
        checker_ = std::make_unique<Checker>(txn_kv_);
388
0
        int ret = checker_->start();
389
0
        std::string msg;
390
0
        if (ret != 0) {
391
0
            msg = "failed to start checker";
392
0
            LOG(ERROR) << msg;
393
0
            std::cerr << msg << std::endl;
394
0
            return ret;
395
0
        }
396
0
        msg = "checker started";
397
0
        LOG(INFO) << msg;
398
0
        std::cout << msg << std::endl;
399
0
    }
400
401
4
    if (server) {
402
        // Add service
403
1
        auto recycler_service =
404
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
405
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
406
1
    }
407
408
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
408
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
409
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
410
8
        workers_.emplace_back([this] { recycle_callback(); });
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
410
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
411
8
    }
412
413
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
414
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
415
4
    return 0;
416
4
}
417
418
4
void Recycler::stop() {
419
4
    stopped_ = true;
420
4
    notifier_.notify_all();
421
4
    pending_instance_cond_.notify_all();
422
4
    {
423
4
        std::lock_guard lock(mtx_);
424
4
        for (auto& [_, recycler] : recycling_instance_map_) {
425
0
            recycler->stop();
426
0
        }
427
4
    }
428
20
    for (auto& w : workers_) {
429
20
        if (w.joinable()) w.join();
430
20
    }
431
4
    if (checker_) {
432
0
        checker_->stop();
433
0
    }
434
4
}
435
436
class InstanceRecycler::InvertedIndexIdCache {
437
public:
438
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
439
77
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
440
441
    // Return 0 if success, 1 if schema kv not found, negative for error
442
3.55k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
443
3.55k
        {
444
3.55k
            std::lock_guard lock(mtx_);
445
3.55k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
446
644
                return 0;
447
644
            }
448
2.90k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
449
2.90k
                it != inverted_index_id_map_.end()) {
450
2.37k
                res = it->second;
451
2.37k
                return 0;
452
2.37k
            }
453
2.90k
        }
454
        // Get schema from kv
455
        // TODO(plat1ko): Single flight
456
532
        std::unique_ptr<Transaction> txn;
457
532
        TxnErrorCode err = txn_kv_->create_txn(&txn);
458
532
        if (err != TxnErrorCode::TXN_OK) {
459
0
            LOG(WARNING) << "failed to create txn, err=" << err;
460
0
            return -1;
461
0
        }
462
532
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
463
532
        ValueBuf val_buf;
464
532
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
465
532
        if (err != TxnErrorCode::TXN_OK) {
466
500
            LOG(WARNING) << "failed to get schema, err=" << err;
467
500
            return static_cast<int>(err);
468
500
        }
469
32
        doris::TabletSchemaCloudPB schema;
470
32
        if (!parse_schema_value(val_buf, &schema)) {
471
0
            LOG(WARNING) << "malformed schema value, key=" << hex(schema_key);
472
0
            return -1;
473
0
        }
474
32
        if (schema.index_size() > 0) {
475
26
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
476
26
            if (schema.has_inverted_index_storage_format()) {
477
23
                index_format = schema.inverted_index_storage_format();
478
23
            }
479
26
            res.first = index_format;
480
26
            res.second.reserve(schema.index_size());
481
62
            for (auto& i : schema.index()) {
482
62
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
483
62
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
484
62
                }
485
62
            }
486
26
        }
487
32
        insert(index_id, schema_version, res);
488
32
        return 0;
489
32
    }
490
491
    // Empty `ids` means this schema has no inverted index
492
32
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
493
32
        if (index_info.second.empty()) {
494
6
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
495
6
            std::lock_guard lock(mtx_);
496
6
            schemas_without_inverted_index_.emplace(index_id, schema_version);
497
26
        } else {
498
26
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
499
26
            std::lock_guard lock(mtx_);
500
26
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
501
26
        }
502
32
    }
503
504
private:
505
    std::string instance_id_;
506
    std::shared_ptr<TxnKv> txn_kv_;
507
508
    std::mutex mtx_;
509
    using Key = std::pair<int64_t, int32_t>; // <index_id, schema_version>
510
    struct HashOfKey {
511
6.49k
        size_t operator()(const Key& key) const {
512
6.49k
            size_t seed = 0;
513
6.49k
            seed = std::hash<int64_t> {}(key.first);
514
6.49k
            seed = std::hash<int32_t> {}(key.second);
515
6.49k
            return seed;
516
6.49k
        }
517
    };
518
    // <index_id, schema_version> -> inverted_index_ids
519
    std::unordered_map<Key, InvertedIndexInfo, HashOfKey> inverted_index_id_map_;
520
    // Store <index_id, schema_version> of schema which doesn't have inverted index
521
    std::unordered_set<Key, HashOfKey> schemas_without_inverted_index_;
522
};
523
524
InstanceRecycler::InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
525
                                   RecyclerThreadPoolGroup thread_pool_group,
526
                                   std::shared_ptr<TxnLazyCommitter> txn_lazy_committer)
527
        : txn_kv_(std::move(txn_kv)),
528
          instance_id_(instance.instance_id()),
529
          instance_info_(instance),
530
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
531
          _thread_pool_group(std::move(thread_pool_group)),
532
77
          txn_lazy_committer_(std::move(txn_lazy_committer)) {};
533
534
77
InstanceRecycler::~InstanceRecycler() = default;
535
536
77
int InstanceRecycler::init_obj_store_accessors() {
537
77
    for (const auto& obj_info : instance_info_.obj_info()) {
538
56
#ifdef UNIT_TEST
539
56
        auto accessor = std::make_shared<MockAccessor>();
540
#else
541
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
542
        if (!s3_conf) {
543
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
544
            return -1;
545
        }
546
547
        std::shared_ptr<S3Accessor> accessor;
548
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
549
        if (ret != 0) {
550
            LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
551
                         << " resource_id=" << obj_info.id();
552
            return ret;
553
        }
554
#endif
555
56
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
556
56
    }
557
558
77
    return 0;
559
77
}
560
561
77
int InstanceRecycler::init_storage_vault_accessors() {
562
77
    if (instance_info_.resource_ids().empty()) {
563
70
        return 0;
564
70
    }
565
566
7
    FullRangeGetOptions opts(txn_kv_);
567
7
    opts.prefetch = true;
568
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
569
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
570
571
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
572
18
        auto [k, v] = *kv;
573
18
        StorageVaultPB vault;
574
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
575
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
576
0
            return -1;
577
0
        }
578
18
        std::string recycler_storage_vault_white_list = accumulate(
579
18
                config::recycler_storage_vault_white_list.begin(),
580
18
                config::recycler_storage_vault_white_list.end(), std::string(),
581
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
Line
Count
Source
581
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
582
18
        LOG_INFO("config::recycler_storage_vault_white_list")
583
18
                .tag("", recycler_storage_vault_white_list);
584
18
        if (!config::recycler_storage_vault_white_list.empty()) {
585
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
586
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
587
8
                it == config::recycler_storage_vault_white_list.end()) {
588
2
                LOG_WARNING(
589
2
                        "failed to init accessor for vault because this vault is not in "
590
2
                        "config::recycler_storage_vault_white_list. ")
591
2
                        .tag(" vault name:", vault.name())
592
2
                        .tag(" config::recycler_storage_vault_white_list:",
593
2
                             recycler_storage_vault_white_list);
594
2
                continue;
595
2
            }
596
8
        }
597
16
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
598
16
                                 &accessor_map_, &vault);
599
16
        if (vault.has_hdfs_info()) {
600
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
601
9
            int ret = accessor->init();
602
9
            if (ret != 0) {
603
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
604
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
605
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
606
4
                continue;
607
4
            }
608
5
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
609
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
610
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
611
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
612
7
        } else if (vault.has_obj_info()) {
613
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
614
7
            if (!s3_conf) {
615
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
616
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
617
1
                continue;
618
1
            }
619
620
6
            std::shared_ptr<S3Accessor> accessor;
621
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
622
6
            if (ret != 0) {
623
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
624
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
625
0
                             << " ret=" << ret
626
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
627
0
                continue;
628
0
            }
629
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
630
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
631
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
632
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
633
6
        }
634
16
    }
635
636
7
    if (!it->is_valid()) {
637
0
        LOG_WARNING("failed to get storage vault kv");
638
0
        return -1;
639
0
    }
640
641
7
    if (accessor_map_.empty()) {
642
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
643
1
        return -2;
644
1
    }
645
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
646
6
             instance_id_);
647
648
6
    return 0;
649
7
}
650
651
77
int InstanceRecycler::init() {
652
77
    int ret = init_obj_store_accessors();
653
77
    if (ret != 0) {
654
0
        return ret;
655
0
    }
656
657
77
    return init_storage_vault_accessors();
658
77
}
659
660
template <typename... Func>
661
100
auto task_wrapper(Func... funcs) -> std::function<int()> {
662
100
    return [funcs...]() {
663
100
        return [](std::initializer_list<int> ret_vals) {
664
100
            int i = 0;
665
120
            for (int ret : ret_vals) {
666
120
                if (ret != 0) {
667
0
                    i = ret;
668
0
                }
669
120
            }
670
100
            return i;
671
100
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_1ZNS2_10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
20
            for (int ret : ret_vals) {
666
20
                if (ret != 0) {
667
0
                    i = ret;
668
0
                }
669
20
            }
670
10
            return i;
671
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
0
                    i = ret;
668
0
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
0
                    i = ret;
668
0
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_5ZNS2_10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
20
            for (int ret : ret_vals) {
666
20
                if (ret != 0) {
667
0
                    i = ret;
668
0
                }
669
20
            }
670
10
            return i;
671
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
0
                    i = ret;
668
0
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
0
                    i = ret;
668
0
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
0
                    i = ret;
668
0
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
0
                    i = ret;
668
0
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
0
                    i = ret;
668
0
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
0
                    i = ret;
668
0
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_1ZNS2_10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_5ZNS2_10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
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$_9EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
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_
672
100
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_1ZNS2_10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
662
10
    return [funcs...]() {
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
10
                    i = ret;
668
10
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
672
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
662
10
    return [funcs...]() {
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
10
                    i = ret;
668
10
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
672
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
662
10
    return [funcs...]() {
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
10
                    i = ret;
668
10
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
672
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_5ZNS2_10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
662
10
    return [funcs...]() {
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
10
                    i = ret;
668
10
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
672
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
662
10
    return [funcs...]() {
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
10
                    i = ret;
668
10
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
672
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
662
10
    return [funcs...]() {
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
10
                    i = ret;
668
10
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
672
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
662
10
    return [funcs...]() {
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
10
                    i = ret;
668
10
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
672
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
662
10
    return [funcs...]() {
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
10
                    i = ret;
668
10
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
672
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
662
10
    return [funcs...]() {
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
10
                    i = ret;
668
10
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
672
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
662
10
    return [funcs...]() {
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
10
                    i = ret;
668
10
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
672
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_1ZNS2_10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_5ZNS2_10do_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$_9EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_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
673
100
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_1ZNS2_10do_recycleEvE3$_2EEESt8functionIFivEEDpT_
Line
Count
Source
661
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
662
10
    return [funcs...]() {
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
10
                    i = ret;
668
10
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
672
10
    };
673
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
661
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
662
10
    return [funcs...]() {
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
10
                    i = ret;
668
10
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
672
10
    };
673
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4EEESt8functionIFivEEDpT_
Line
Count
Source
661
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
662
10
    return [funcs...]() {
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
10
                    i = ret;
668
10
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
672
10
    };
673
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_5ZNS2_10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
661
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
662
10
    return [funcs...]() {
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
10
                    i = ret;
668
10
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
672
10
    };
673
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
661
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
662
10
    return [funcs...]() {
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
10
                    i = ret;
668
10
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
672
10
    };
673
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
661
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
662
10
    return [funcs...]() {
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
10
                    i = ret;
668
10
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
672
10
    };
673
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9EEESt8functionIFivEEDpT_
Line
Count
Source
661
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
662
10
    return [funcs...]() {
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
10
                    i = ret;
668
10
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
672
10
    };
673
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
661
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
662
10
    return [funcs...]() {
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
10
                    i = ret;
668
10
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
672
10
    };
673
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
661
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
662
10
    return [funcs...]() {
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
10
                    i = ret;
668
10
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
672
10
    };
673
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
661
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
662
10
    return [funcs...]() {
663
10
        return [](std::initializer_list<int> ret_vals) {
664
10
            int i = 0;
665
10
            for (int ret : ret_vals) {
666
10
                if (ret != 0) {
667
10
                    i = ret;
668
10
                }
669
10
            }
670
10
            return i;
671
10
        }({funcs()...});
672
10
    };
673
10
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_1ZNS2_10do_recycleEvE3$_2EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_5ZNS2_10do_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$_9EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
674
675
10
int InstanceRecycler::do_recycle() {
676
10
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
677
10
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
678
0
        return recycle_deleted_instance();
679
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
680
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
681
10
                                        fmt::format("instance id {}", instance_id_),
682
100
                                        [](int r) { return r != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEi
Line
Count
Source
682
100
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEi
683
10
        sync_executor
684
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
685
                                   // becase they may both recycle the same set of tablets
686
                        // recycle dropped table or idexes(mv, rollup)
687
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEv
Line
Count
Source
687
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEv
688
                        // recycle dropped partitions
689
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
689
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
690
10
                .add(task_wrapper(
691
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_3clEv
Line
Count
Source
691
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_3clEv
692
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
692
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
693
10
                .add(task_wrapper(
694
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
694
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
695
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
695
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
696
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_7clEv
Line
Count
Source
696
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_7clEv
697
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
697
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
698
10
                .add(task_wrapper(
699
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
699
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
700
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
700
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
701
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_11clEv
Line
Count
Source
701
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_11clEv
702
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_12clEv
Line
Count
Source
702
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_12clEv
703
10
        bool finished = true;
704
10
        std::vector<int> rets = sync_executor.when_all(&finished);
705
100
        for (int ret : rets) {
706
100
            if (ret != 0) {
707
0
                return ret;
708
0
            }
709
100
        }
710
10
        return finished ? 0 : -1;
711
10
    } else {
712
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
713
0
                     << " instance_id=" << instance_id_;
714
0
        return -1;
715
0
    }
716
10
}
717
718
/**
719
 * 1. delete all remote data
720
 * 2. delete all kv
721
 * 3. remove instance kv
722
 */
723
1
int InstanceRecycler::recycle_deleted_instance() {
724
1
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
725
726
1
    int ret = 0;
727
1
    auto start_time = steady_clock::now();
728
729
1
    DORIS_CLOUD_DEFER {
730
1
        auto cost = duration<float>(steady_clock::now() - start_time).count();
731
1
        LOG(WARNING) << (ret == 0 ? "successfully" : "failed to")
732
1
                     << " recycle deleted instance, cost=" << cost
733
1
                     << "s, instance_id=" << instance_id_;
734
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
729
1
    DORIS_CLOUD_DEFER {
730
1
        auto cost = duration<float>(steady_clock::now() - start_time).count();
731
1
        LOG(WARNING) << (ret == 0 ? "successfully" : "failed to")
732
1
                     << " recycle deleted instance, cost=" << cost
733
1
                     << "s, instance_id=" << instance_id_;
734
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
735
736
    // delete all remote data
737
2
    for (auto& [_, accessor] : accessor_map_) {
738
2
        if (stopped()) {
739
0
            return ret;
740
0
        }
741
742
2
        LOG(INFO) << "begin to delete all objects in " << accessor->uri();
743
2
        int del_ret = accessor->delete_all();
744
2
        if (del_ret == 0) {
745
2
            LOG(INFO) << "successfully delete all objects in " << accessor->uri();
746
2
        } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
747
            // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
748
            // so the recycling has been successful.
749
0
            ret = -1;
750
0
        }
751
2
    }
752
753
1
    if (ret != 0) {
754
0
        LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
755
0
        return ret;
756
0
    }
757
758
    // delete all kv
759
1
    std::unique_ptr<Transaction> txn;
760
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
761
1
    if (err != TxnErrorCode::TXN_OK) {
762
0
        LOG(WARNING) << "failed to create txn";
763
0
        ret = -1;
764
0
        return -1;
765
0
    }
766
1
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
767
    // delete kv before deleting objects to prevent the checker from misjudging data loss
768
1
    std::string start_txn_key = txn_key_prefix(instance_id_);
769
1
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
770
1
    txn->remove(start_txn_key, end_txn_key);
771
1
    std::string start_version_key = version_key_prefix(instance_id_);
772
1
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
773
1
    txn->remove(start_version_key, end_version_key);
774
1
    std::string start_meta_key = meta_key_prefix(instance_id_);
775
1
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
776
1
    txn->remove(start_meta_key, end_meta_key);
777
1
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
778
1
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
779
1
    txn->remove(start_recycle_key, end_recycle_key);
780
1
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
781
1
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
782
1
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
783
1
    std::string start_copy_key = copy_key_prefix(instance_id_);
784
1
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
785
1
    txn->remove(start_copy_key, end_copy_key);
786
    // should not remove job key range, because we need to reserve job recycle kv
787
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
788
1
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
789
1
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
790
1
    txn->remove(start_job_tablet_key, end_job_tablet_key);
791
1
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
792
1
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
793
1
    std::string start_vault_key = storage_vault_key(key_info0);
794
1
    std::string end_vault_key = storage_vault_key(key_info1);
795
1
    txn->remove(start_vault_key, end_vault_key);
796
1
    err = txn->commit();
797
1
    if (err != TxnErrorCode::TXN_OK) {
798
0
        LOG(WARNING) << "failed to delete all kv, instance_id=" << instance_id_ << ", err=" << err;
799
0
        ret = -1;
800
0
    }
801
802
1
    if (ret == 0) {
803
        // remove instance kv
804
        // ATTN: MUST ensure that cloud platform won't regenerate the same instance id
805
1
        err = txn_kv_->create_txn(&txn);
806
1
        if (err != TxnErrorCode::TXN_OK) {
807
0
            LOG(WARNING) << "failed to create txn";
808
0
            ret = -1;
809
0
            return ret;
810
0
        }
811
1
        std::string key;
812
1
        instance_key({instance_id_}, &key);
813
1
        txn->remove(key);
814
1
        err = txn->commit();
815
1
        if (err != TxnErrorCode::TXN_OK) {
816
0
            LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
817
0
                         << " err=" << err;
818
0
            ret = -1;
819
0
        }
820
1
    }
821
1
    return ret;
822
1
}
823
824
bool is_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string& instance_id,
825
3.05k
                     int64_t txn_id) {
826
3.05k
    std::unique_ptr<Transaction> txn;
827
3.05k
    TxnErrorCode err = txn_kv->create_txn(&txn);
828
3.05k
    if (err != TxnErrorCode::TXN_OK) {
829
0
        LOG(WARNING) << "failed to create txn, txn_id=" << txn_id << " instance_id=" << instance_id;
830
0
        return false;
831
0
    }
832
833
3.05k
    std::string index_val;
834
3.05k
    const std::string index_key = txn_index_key({instance_id, txn_id});
835
3.05k
    err = txn->get(index_key, &index_val);
836
3.05k
    if (err != TxnErrorCode::TXN_OK) {
837
3.03k
        if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
838
3.03k
            TEST_SYNC_POINT_CALLBACK("is_txn_finished::txn_has_been_recycled");
839
            // txn has been recycled;
840
3.03k
            LOG(INFO) << "txn index key has been recycled, txn_id=" << txn_id
841
3.03k
                      << " instance_id=" << instance_id;
842
3.03k
            return true;
843
3.03k
        }
844
0
        LOG(WARNING) << "failed to get txn index key, txn_id=" << txn_id
845
0
                     << " instance_id=" << instance_id << " key=" << hex(index_key)
846
0
                     << " err=" << err;
847
0
        return false;
848
3.03k
    }
849
850
20
    TxnIndexPB index_pb;
851
20
    if (!index_pb.ParseFromString(index_val)) {
852
0
        LOG(WARNING) << "failed to parse txn_index_pb, txn_id=" << txn_id
853
0
                     << " instance_id=" << instance_id;
854
0
        return false;
855
0
    }
856
857
20
    DCHECK(index_pb.has_tablet_index() == true);
858
20
    if (!index_pb.tablet_index().has_db_id()) {
859
        // In the previous version, the db_id was not set in the index_pb.
860
        // If updating to the version which enable txn lazy commit, the db_id will be set.
861
0
        LOG(INFO) << "txn index has no db_id, txn_id=" << txn_id << " instance_id=" << instance_id
862
0
                  << " index=" << index_pb.ShortDebugString();
863
0
        return true;
864
0
    }
865
866
20
    int64_t db_id = index_pb.tablet_index().db_id();
867
20
    DCHECK_GT(db_id, 0) << "db_id=" << db_id << " txn_id=" << txn_id
868
0
                        << " instance_id=" << instance_id;
869
870
20
    std::string info_val;
871
20
    const std::string info_key = txn_info_key({instance_id, db_id, txn_id});
872
20
    err = txn->get(info_key, &info_val);
873
20
    if (err != TxnErrorCode::TXN_OK) {
874
0
        if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
875
            // txn info has been recycled;
876
0
            LOG(INFO) << "txn info key has been recycled, db_id=" << db_id << " txn_id=" << txn_id
877
0
                      << " instance_id=" << instance_id;
878
0
            return true;
879
0
        }
880
881
0
        DCHECK(err != TxnErrorCode::TXN_KEY_NOT_FOUND);
882
0
        LOG(WARNING) << "failed to get txn info key, txn_id=" << txn_id
883
0
                     << " instance_id=" << instance_id << " key=" << hex(info_key)
884
0
                     << " err=" << err;
885
0
        return false;
886
0
    }
887
888
20
    TxnInfoPB txn_info;
889
20
    if (!txn_info.ParseFromString(info_val)) {
890
0
        LOG(WARNING) << "failed to parse txn_info, txn_id=" << txn_id
891
0
                     << " instance_id=" << instance_id;
892
0
        return false;
893
0
    }
894
895
20
    DCHECK(txn_info.txn_id() == txn_id) << "txn_id=" << txn_id << " instance_id=" << instance_id
896
0
                                        << " txn_info=" << txn_info.ShortDebugString();
897
898
20
    if (TxnStatusPB::TXN_STATUS_ABORTED == txn_info.status() ||
899
20
        TxnStatusPB::TXN_STATUS_VISIBLE == txn_info.status()) {
900
10
        TEST_SYNC_POINT_CALLBACK("is_txn_finished::txn_has_been_aborted", &txn_info);
901
10
        return true;
902
10
    }
903
904
10
    TEST_SYNC_POINT_CALLBACK("is_txn_finished::txn_not_finished", &txn_info);
905
10
    return false;
906
20
}
907
908
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
909
4.00k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
910
4.00k
    if (config::force_immediate_recycle) {
911
0
        return 0L;
912
0
    }
913
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
914
4.00k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
915
4.00k
    int64_t retention_seconds = config::retention_seconds;
916
4.00k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
917
3.10k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
918
3.10k
    }
919
4.00k
    int64_t final_expiration = expiration + retention_seconds;
920
4.00k
    if (*earlest_ts > final_expiration) {
921
2
        *earlest_ts = final_expiration;
922
2
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
923
2
    }
924
4.00k
    return final_expiration;
925
4.00k
}
926
927
int64_t calculate_partition_expired_time(
928
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
929
8
        int64_t* earlest_ts /* partition earliest expiration ts */) {
930
8
    if (config::force_immediate_recycle) {
931
2
        return 0L;
932
2
    }
933
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
934
6
                                                            : partition_meta_pb.creation_time();
935
6
    int64_t retention_seconds = config::retention_seconds;
936
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
937
6
        retention_seconds =
938
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
939
6
    }
940
6
    int64_t final_expiration = expiration + retention_seconds;
941
6
    if (*earlest_ts > final_expiration) {
942
2
        *earlest_ts = final_expiration;
943
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
944
2
    }
945
6
    return final_expiration;
946
8
}
947
948
int64_t calculate_index_expired_time(const std::string& instance_id_,
949
                                     const RecycleIndexPB& index_meta_pb,
950
8
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
951
8
    if (config::force_immediate_recycle) {
952
2
        return 0L;
953
2
    }
954
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
955
6
                                                        : index_meta_pb.creation_time();
956
6
    int64_t retention_seconds = config::retention_seconds;
957
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
958
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
959
6
    }
960
6
    int64_t final_expiration = expiration + retention_seconds;
961
6
    if (*earlest_ts > final_expiration) {
962
2
        *earlest_ts = final_expiration;
963
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
964
2
    }
965
6
    return final_expiration;
966
8
}
967
968
int64_t calculate_tmp_rowset_expired_time(
969
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
970
3.05k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
971
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
972
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
973
    //  duration or timeout always < `retention_time` in practice.
974
3.05k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
975
3.05k
                                 ? tmp_rowset_meta_pb.txn_expiration()
976
3.05k
                                 : tmp_rowset_meta_pb.creation_time();
977
3.05k
    expiration = config::force_immediate_recycle ? 0 : expiration;
978
3.05k
    int64_t final_expiration = expiration + config::retention_seconds;
979
3.05k
    if (*earlest_ts > final_expiration) {
980
6
        *earlest_ts = final_expiration;
981
6
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
982
6
    }
983
3.05k
    return final_expiration;
984
3.05k
}
985
986
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
987
30.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
988
30.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
989
30.0k
    if (*earlest_ts > final_expiration / 1000) {
990
6
        *earlest_ts = final_expiration / 1000;
991
6
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
992
6
    }
993
30.0k
    return final_expiration;
994
30.0k
}
995
996
int64_t calculate_restore_job_expired_time(
997
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
998
20
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
999
20
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED) {
1000
20
        return 0L;
1001
20
    }
1002
0
    int64_t expiration = restore_job.expiration() > 0
1003
0
                                 ? restore_job.creation_time() + restore_job.expiration()
1004
0
                                 : restore_job.creation_time();
1005
0
    int64_t final_expiration = expiration + config::retention_seconds;
1006
0
    if (*earlest_ts > final_expiration) {
1007
0
        *earlest_ts = final_expiration;
1008
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1009
0
    }
1010
0
    return final_expiration;
1011
20
}
1012
1013
14
int InstanceRecycler::recycle_indexes() {
1014
14
    const std::string task_name = "recycle_indexes";
1015
14
    int64_t num_scanned = 0;
1016
14
    int64_t num_expired = 0;
1017
14
    int64_t num_recycled = 0;
1018
14
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
1019
1020
14
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
1021
14
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
1022
14
    std::string index_key0;
1023
14
    std::string index_key1;
1024
14
    recycle_index_key(index_key_info0, &index_key0);
1025
14
    recycle_index_key(index_key_info1, &index_key1);
1026
1027
14
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
1028
1029
14
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
1030
14
    register_recycle_task(task_name, start_time);
1031
1032
14
    DORIS_CLOUD_DEFER {
1033
14
        unregister_recycle_task(task_name);
1034
14
        int64_t cost =
1035
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
1036
14
        metrics_context.finish_report();
1037
14
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
1038
14
                .tag("instance_id", instance_id_)
1039
14
                .tag("num_scanned", num_scanned)
1040
14
                .tag("num_expired", num_expired)
1041
14
                .tag("num_recycled", num_recycled);
1042
14
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
1032
12
    DORIS_CLOUD_DEFER {
1033
12
        unregister_recycle_task(task_name);
1034
12
        int64_t cost =
1035
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
1036
12
        metrics_context.finish_report();
1037
12
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
1038
12
                .tag("instance_id", instance_id_)
1039
12
                .tag("num_scanned", num_scanned)
1040
12
                .tag("num_expired", num_expired)
1041
12
                .tag("num_recycled", num_recycled);
1042
12
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
1032
2
    DORIS_CLOUD_DEFER {
1033
2
        unregister_recycle_task(task_name);
1034
2
        int64_t cost =
1035
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
1036
2
        metrics_context.finish_report();
1037
2
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
1038
2
                .tag("instance_id", instance_id_)
1039
2
                .tag("num_scanned", num_scanned)
1040
2
                .tag("num_expired", num_expired)
1041
2
                .tag("num_recycled", num_recycled);
1042
2
    };
1043
1044
14
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
1045
1046
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
1047
14
    std::vector<std::string_view> index_keys;
1048
14
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
1049
8
        ++num_scanned;
1050
8
        RecycleIndexPB index_pb;
1051
8
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
1052
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
1053
0
            return -1;
1054
0
        }
1055
8
        int64_t current_time = ::time(nullptr);
1056
8
        if (current_time <
1057
8
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
1058
0
            return 0;
1059
0
        }
1060
8
        ++num_expired;
1061
        // decode index_id
1062
8
        auto k1 = k;
1063
8
        k1.remove_prefix(1);
1064
8
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1065
8
        decode_key(&k1, &out);
1066
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
1067
8
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
1068
8
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
1069
8
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
1070
8
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
1071
        // Change state to RECYCLING
1072
8
        std::unique_ptr<Transaction> txn;
1073
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1074
8
        if (err != TxnErrorCode::TXN_OK) {
1075
0
            LOG_WARNING("failed to create txn").tag("err", err);
1076
0
            return -1;
1077
0
        }
1078
8
        std::string val;
1079
8
        err = txn->get(k, &val);
1080
8
        if (err ==
1081
8
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
1082
0
            LOG_INFO("index {} has been recycled or committed", index_id);
1083
0
            return 0;
1084
0
        }
1085
8
        if (err != TxnErrorCode::TXN_OK) {
1086
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
1087
0
            return -1;
1088
0
        }
1089
8
        index_pb.Clear();
1090
8
        if (!index_pb.ParseFromString(val)) {
1091
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
1092
0
            return -1;
1093
0
        }
1094
8
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
1095
7
            index_pb.set_state(RecycleIndexPB::RECYCLING);
1096
7
            txn->put(k, index_pb.SerializeAsString());
1097
7
            err = txn->commit();
1098
7
            if (err != TxnErrorCode::TXN_OK) {
1099
0
                LOG_WARNING("failed to commit txn").tag("err", err);
1100
0
                return -1;
1101
0
            }
1102
7
        }
1103
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
1104
1
            LOG_WARNING("failed to recycle tablets under index")
1105
1
                    .tag("table_id", index_pb.table_id())
1106
1
                    .tag("instance_id", instance_id_)
1107
1
                    .tag("index_id", index_id);
1108
1
            return -1;
1109
1
        }
1110
7
        metrics_context.total_recycled_num = ++num_recycled;
1111
7
        metrics_context.report();
1112
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
1113
7
        index_keys.push_back(k);
1114
7
        return 0;
1115
8
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
1048
6
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
1049
6
        ++num_scanned;
1050
6
        RecycleIndexPB index_pb;
1051
6
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
1052
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
1053
0
            return -1;
1054
0
        }
1055
6
        int64_t current_time = ::time(nullptr);
1056
6
        if (current_time <
1057
6
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
1058
0
            return 0;
1059
0
        }
1060
6
        ++num_expired;
1061
        // decode index_id
1062
6
        auto k1 = k;
1063
6
        k1.remove_prefix(1);
1064
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1065
6
        decode_key(&k1, &out);
1066
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
1067
6
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
1068
6
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
1069
6
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
1070
6
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
1071
        // Change state to RECYCLING
1072
6
        std::unique_ptr<Transaction> txn;
1073
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1074
6
        if (err != TxnErrorCode::TXN_OK) {
1075
0
            LOG_WARNING("failed to create txn").tag("err", err);
1076
0
            return -1;
1077
0
        }
1078
6
        std::string val;
1079
6
        err = txn->get(k, &val);
1080
6
        if (err ==
1081
6
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
1082
0
            LOG_INFO("index {} has been recycled or committed", index_id);
1083
0
            return 0;
1084
0
        }
1085
6
        if (err != TxnErrorCode::TXN_OK) {
1086
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
1087
0
            return -1;
1088
0
        }
1089
6
        index_pb.Clear();
1090
6
        if (!index_pb.ParseFromString(val)) {
1091
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
1092
0
            return -1;
1093
0
        }
1094
6
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
1095
6
            index_pb.set_state(RecycleIndexPB::RECYCLING);
1096
6
            txn->put(k, index_pb.SerializeAsString());
1097
6
            err = txn->commit();
1098
6
            if (err != TxnErrorCode::TXN_OK) {
1099
0
                LOG_WARNING("failed to commit txn").tag("err", err);
1100
0
                return -1;
1101
0
            }
1102
6
        }
1103
6
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
1104
0
            LOG_WARNING("failed to recycle tablets under index")
1105
0
                    .tag("table_id", index_pb.table_id())
1106
0
                    .tag("instance_id", instance_id_)
1107
0
                    .tag("index_id", index_id);
1108
0
            return -1;
1109
0
        }
1110
6
        metrics_context.total_recycled_num = ++num_recycled;
1111
6
        metrics_context.report();
1112
6
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
1113
6
        index_keys.push_back(k);
1114
6
        return 0;
1115
6
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
1048
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
1049
2
        ++num_scanned;
1050
2
        RecycleIndexPB index_pb;
1051
2
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
1052
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
1053
0
            return -1;
1054
0
        }
1055
2
        int64_t current_time = ::time(nullptr);
1056
2
        if (current_time <
1057
2
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
1058
0
            return 0;
1059
0
        }
1060
2
        ++num_expired;
1061
        // decode index_id
1062
2
        auto k1 = k;
1063
2
        k1.remove_prefix(1);
1064
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1065
2
        decode_key(&k1, &out);
1066
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
1067
2
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
1068
2
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
1069
2
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
1070
2
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
1071
        // Change state to RECYCLING
1072
2
        std::unique_ptr<Transaction> txn;
1073
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1074
2
        if (err != TxnErrorCode::TXN_OK) {
1075
0
            LOG_WARNING("failed to create txn").tag("err", err);
1076
0
            return -1;
1077
0
        }
1078
2
        std::string val;
1079
2
        err = txn->get(k, &val);
1080
2
        if (err ==
1081
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
1082
0
            LOG_INFO("index {} has been recycled or committed", index_id);
1083
0
            return 0;
1084
0
        }
1085
2
        if (err != TxnErrorCode::TXN_OK) {
1086
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
1087
0
            return -1;
1088
0
        }
1089
2
        index_pb.Clear();
1090
2
        if (!index_pb.ParseFromString(val)) {
1091
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
1092
0
            return -1;
1093
0
        }
1094
2
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
1095
1
            index_pb.set_state(RecycleIndexPB::RECYCLING);
1096
1
            txn->put(k, index_pb.SerializeAsString());
1097
1
            err = txn->commit();
1098
1
            if (err != TxnErrorCode::TXN_OK) {
1099
0
                LOG_WARNING("failed to commit txn").tag("err", err);
1100
0
                return -1;
1101
0
            }
1102
1
        }
1103
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
1104
1
            LOG_WARNING("failed to recycle tablets under index")
1105
1
                    .tag("table_id", index_pb.table_id())
1106
1
                    .tag("instance_id", instance_id_)
1107
1
                    .tag("index_id", index_id);
1108
1
            return -1;
1109
1
        }
1110
1
        metrics_context.total_recycled_num = ++num_recycled;
1111
1
        metrics_context.report();
1112
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
1113
1
        index_keys.push_back(k);
1114
1
        return 0;
1115
2
    };
1116
1117
14
    auto loop_done = [&index_keys, this]() -> int {
1118
4
        if (index_keys.empty()) return 0;
1119
3
        DORIS_CLOUD_DEFER {
1120
3
            index_keys.clear();
1121
3
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
1119
2
        DORIS_CLOUD_DEFER {
1120
2
            index_keys.clear();
1121
2
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
1119
1
        DORIS_CLOUD_DEFER {
1120
1
            index_keys.clear();
1121
1
        };
1122
3
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
1123
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
1124
0
            return -1;
1125
0
        }
1126
3
        return 0;
1127
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
1117
2
    auto loop_done = [&index_keys, this]() -> int {
1118
2
        if (index_keys.empty()) return 0;
1119
2
        DORIS_CLOUD_DEFER {
1120
2
            index_keys.clear();
1121
2
        };
1122
2
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
1123
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
1124
0
            return -1;
1125
0
        }
1126
2
        return 0;
1127
2
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
1117
2
    auto loop_done = [&index_keys, this]() -> int {
1118
2
        if (index_keys.empty()) return 0;
1119
1
        DORIS_CLOUD_DEFER {
1120
1
            index_keys.clear();
1121
1
        };
1122
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
1123
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
1124
0
            return -1;
1125
0
        }
1126
1
        return 0;
1127
1
    };
1128
1129
14
    if (config::enable_recycler_stats_metrics) {
1130
0
        scan_and_statistics_indexes();
1131
0
    }
1132
    // recycle_func and loop_done for scan and recycle
1133
14
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
1134
14
}
1135
1136
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
1137
271
                             int64_t tablet_id) {
1138
271
    std::unique_ptr<Transaction> txn;
1139
271
    TxnErrorCode err = txn_kv->create_txn(&txn);
1140
271
    if (err != TxnErrorCode::TXN_OK) {
1141
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
1142
0
                     << " tablet_id=" << tablet_id << " err=" << err;
1143
0
        return false;
1144
0
    }
1145
1146
271
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
1147
271
    std::string tablet_idx_val;
1148
271
    err = txn->get(tablet_idx_key, &tablet_idx_val);
1149
271
    if (TxnErrorCode::TXN_OK != err) {
1150
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
1151
0
                     << " tablet_id=" << tablet_id << " err=" << err
1152
0
                     << " key=" << hex(tablet_idx_key);
1153
0
        return false;
1154
0
    }
1155
1156
271
    TabletIndexPB tablet_idx_pb;
1157
271
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
1158
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
1159
0
                     << " tablet_id=" << tablet_id;
1160
0
        return false;
1161
0
    }
1162
1163
271
    if (!tablet_idx_pb.has_db_id()) {
1164
        // In the previous version, the db_id was not set in the index_pb.
1165
        // If updating to the version which enable txn lazy commit, the db_id will be set.
1166
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
1167
0
                  << " instance_id=" << instance_id
1168
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
1169
0
        return true;
1170
0
    }
1171
1172
271
    std::string ver_val;
1173
271
    std::string ver_key =
1174
271
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
1175
271
                                   tablet_idx_pb.partition_id()});
1176
271
    err = txn->get(ver_key, &ver_val);
1177
1178
271
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
1179
201
        LOG(INFO) << ""
1180
201
                     "partition version not found, instance_id="
1181
201
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
1182
201
                  << " table_id=" << tablet_idx_pb.table_id()
1183
201
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
1184
201
                  << " key=" << hex(ver_key);
1185
201
        return true;
1186
201
    }
1187
1188
70
    if (TxnErrorCode::TXN_OK != err) {
1189
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
1190
0
                     << " db_id=" << tablet_idx_pb.db_id()
1191
0
                     << " table_id=" << tablet_idx_pb.table_id()
1192
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
1193
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
1194
0
        return false;
1195
0
    }
1196
1197
70
    VersionPB version_pb;
1198
70
    if (!version_pb.ParseFromString(ver_val)) {
1199
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
1200
0
                     << " db_id=" << tablet_idx_pb.db_id()
1201
0
                     << " table_id=" << tablet_idx_pb.table_id()
1202
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
1203
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
1204
0
        return false;
1205
0
    }
1206
1207
70
    if (version_pb.pending_txn_ids_size() > 0) {
1208
20
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
1209
20
        DCHECK(version_pb.pending_txn_ids_size() == 1);
1210
20
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
1211
20
                     << " db_id=" << tablet_idx_pb.db_id()
1212
20
                     << " table_id=" << tablet_idx_pb.table_id()
1213
20
                     << " partition_id=" << tablet_idx_pb.partition_id()
1214
20
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
1215
20
                     << " key=" << hex(ver_key);
1216
20
        return false;
1217
20
    }
1218
50
    return true;
1219
70
}
1220
1221
14
int InstanceRecycler::recycle_partitions() {
1222
14
    const std::string task_name = "recycle_partitions";
1223
14
    int64_t num_scanned = 0;
1224
14
    int64_t num_expired = 0;
1225
14
    int64_t num_recycled = 0;
1226
14
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
1227
1228
14
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
1229
14
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
1230
14
    std::string part_key0;
1231
14
    std::string part_key1;
1232
14
    recycle_partition_key(part_key_info0, &part_key0);
1233
14
    recycle_partition_key(part_key_info1, &part_key1);
1234
1235
14
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
1236
1237
14
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
1238
14
    register_recycle_task(task_name, start_time);
1239
1240
14
    DORIS_CLOUD_DEFER {
1241
14
        unregister_recycle_task(task_name);
1242
14
        int64_t cost =
1243
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
1244
14
        metrics_context.finish_report();
1245
14
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
1246
14
                .tag("instance_id", instance_id_)
1247
14
                .tag("num_scanned", num_scanned)
1248
14
                .tag("num_expired", num_expired)
1249
14
                .tag("num_recycled", num_recycled);
1250
14
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
1240
12
    DORIS_CLOUD_DEFER {
1241
12
        unregister_recycle_task(task_name);
1242
12
        int64_t cost =
1243
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
1244
12
        metrics_context.finish_report();
1245
12
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
1246
12
                .tag("instance_id", instance_id_)
1247
12
                .tag("num_scanned", num_scanned)
1248
12
                .tag("num_expired", num_expired)
1249
12
                .tag("num_recycled", num_recycled);
1250
12
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
1240
2
    DORIS_CLOUD_DEFER {
1241
2
        unregister_recycle_task(task_name);
1242
2
        int64_t cost =
1243
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
1244
2
        metrics_context.finish_report();
1245
2
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
1246
2
                .tag("instance_id", instance_id_)
1247
2
                .tag("num_scanned", num_scanned)
1248
2
                .tag("num_expired", num_expired)
1249
2
                .tag("num_recycled", num_recycled);
1250
2
    };
1251
1252
14
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
1253
1254
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
1255
14
    std::vector<std::string_view> partition_keys;
1256
14
    std::vector<std::string> partition_version_keys;
1257
14
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
1258
8
        ++num_scanned;
1259
8
        RecyclePartitionPB part_pb;
1260
8
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
1261
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
1262
0
            return -1;
1263
0
        }
1264
8
        int64_t current_time = ::time(nullptr);
1265
8
        if (current_time <
1266
8
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
1267
0
            return 0;
1268
0
        }
1269
8
        ++num_expired;
1270
        // decode partition_id
1271
8
        auto k1 = k;
1272
8
        k1.remove_prefix(1);
1273
8
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1274
8
        decode_key(&k1, &out);
1275
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
1276
8
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
1277
8
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
1278
8
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
1279
8
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
1280
        // Change state to RECYCLING
1281
8
        std::unique_ptr<Transaction> txn;
1282
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1283
8
        if (err != TxnErrorCode::TXN_OK) {
1284
0
            LOG_WARNING("failed to create txn").tag("err", err);
1285
0
            return -1;
1286
0
        }
1287
8
        std::string val;
1288
8
        err = txn->get(k, &val);
1289
8
        if (err ==
1290
8
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
1291
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
1292
0
            return 0;
1293
0
        }
1294
8
        if (err != TxnErrorCode::TXN_OK) {
1295
0
            LOG_WARNING("failed to get kv");
1296
0
            return -1;
1297
0
        }
1298
8
        part_pb.Clear();
1299
8
        if (!part_pb.ParseFromString(val)) {
1300
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
1301
0
            return -1;
1302
0
        }
1303
        // Partitions with PREPARED state MUST have no data
1304
8
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
1305
8
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
1306
7
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
1307
7
            txn->put(k, part_pb.SerializeAsString());
1308
7
            err = txn->commit();
1309
7
            if (err != TxnErrorCode::TXN_OK) {
1310
0
                LOG_WARNING("failed to commit txn: {}", err);
1311
0
                return -1;
1312
0
            }
1313
7
        }
1314
1315
8
        int ret = 0;
1316
32
        for (int64_t index_id : part_pb.index_id()) {
1317
32
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id,
1318
32
                                is_empty_tablet) != 0) {
1319
1
                LOG_WARNING("failed to recycle tablets under partition")
1320
1
                        .tag("table_id", part_pb.table_id())
1321
1
                        .tag("instance_id", instance_id_)
1322
1
                        .tag("index_id", index_id)
1323
1
                        .tag("partition_id", partition_id);
1324
1
                ret = -1;
1325
1
            }
1326
32
        }
1327
8
        if (ret == 0 && part_pb.has_db_id()) {
1328
            // Recycle the versioned keys
1329
7
            std::unique_ptr<Transaction> txn;
1330
7
            err = txn_kv_->create_txn(&txn);
1331
7
            if (err != TxnErrorCode::TXN_OK) {
1332
0
                LOG_WARNING("failed to create txn").tag("err", err);
1333
0
                return -1;
1334
0
            }
1335
7
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
1336
7
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
1337
7
            std::string inverted_index_key = versioned::partition_inverted_index_key(
1338
7
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
1339
7
            versioned_remove_all(txn.get(), meta_key);
1340
7
            txn->remove(index_key);
1341
7
            txn->remove(inverted_index_key);
1342
7
            err = txn->commit();
1343
7
            if (err != TxnErrorCode::TXN_OK) {
1344
0
                LOG_WARNING("failed to commit txn").tag("err", err);
1345
0
                return -1;
1346
0
            }
1347
7
        }
1348
1349
8
        if (ret == 0) {
1350
7
            ++num_recycled;
1351
7
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
1352
7
            partition_keys.push_back(k);
1353
7
            if (part_pb.db_id() > 0) {
1354
7
                partition_version_keys.push_back(partition_version_key(
1355
7
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
1356
7
            }
1357
7
            metrics_context.total_recycled_num = num_recycled;
1358
7
            metrics_context.report();
1359
7
        }
1360
8
        return ret;
1361
8
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
1257
6
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
1258
6
        ++num_scanned;
1259
6
        RecyclePartitionPB part_pb;
1260
6
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
1261
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
1262
0
            return -1;
1263
0
        }
1264
6
        int64_t current_time = ::time(nullptr);
1265
6
        if (current_time <
1266
6
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
1267
0
            return 0;
1268
0
        }
1269
6
        ++num_expired;
1270
        // decode partition_id
1271
6
        auto k1 = k;
1272
6
        k1.remove_prefix(1);
1273
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1274
6
        decode_key(&k1, &out);
1275
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
1276
6
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
1277
6
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
1278
6
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
1279
6
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
1280
        // Change state to RECYCLING
1281
6
        std::unique_ptr<Transaction> txn;
1282
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1283
6
        if (err != TxnErrorCode::TXN_OK) {
1284
0
            LOG_WARNING("failed to create txn").tag("err", err);
1285
0
            return -1;
1286
0
        }
1287
6
        std::string val;
1288
6
        err = txn->get(k, &val);
1289
6
        if (err ==
1290
6
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
1291
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
1292
0
            return 0;
1293
0
        }
1294
6
        if (err != TxnErrorCode::TXN_OK) {
1295
0
            LOG_WARNING("failed to get kv");
1296
0
            return -1;
1297
0
        }
1298
6
        part_pb.Clear();
1299
6
        if (!part_pb.ParseFromString(val)) {
1300
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
1301
0
            return -1;
1302
0
        }
1303
        // Partitions with PREPARED state MUST have no data
1304
6
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
1305
6
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
1306
6
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
1307
6
            txn->put(k, part_pb.SerializeAsString());
1308
6
            err = txn->commit();
1309
6
            if (err != TxnErrorCode::TXN_OK) {
1310
0
                LOG_WARNING("failed to commit txn: {}", err);
1311
0
                return -1;
1312
0
            }
1313
6
        }
1314
1315
6
        int ret = 0;
1316
30
        for (int64_t index_id : part_pb.index_id()) {
1317
30
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id,
1318
30
                                is_empty_tablet) != 0) {
1319
0
                LOG_WARNING("failed to recycle tablets under partition")
1320
0
                        .tag("table_id", part_pb.table_id())
1321
0
                        .tag("instance_id", instance_id_)
1322
0
                        .tag("index_id", index_id)
1323
0
                        .tag("partition_id", partition_id);
1324
0
                ret = -1;
1325
0
            }
1326
30
        }
1327
6
        if (ret == 0 && part_pb.has_db_id()) {
1328
            // Recycle the versioned keys
1329
6
            std::unique_ptr<Transaction> txn;
1330
6
            err = txn_kv_->create_txn(&txn);
1331
6
            if (err != TxnErrorCode::TXN_OK) {
1332
0
                LOG_WARNING("failed to create txn").tag("err", err);
1333
0
                return -1;
1334
0
            }
1335
6
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
1336
6
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
1337
6
            std::string inverted_index_key = versioned::partition_inverted_index_key(
1338
6
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
1339
6
            versioned_remove_all(txn.get(), meta_key);
1340
6
            txn->remove(index_key);
1341
6
            txn->remove(inverted_index_key);
1342
6
            err = txn->commit();
1343
6
            if (err != TxnErrorCode::TXN_OK) {
1344
0
                LOG_WARNING("failed to commit txn").tag("err", err);
1345
0
                return -1;
1346
0
            }
1347
6
        }
1348
1349
6
        if (ret == 0) {
1350
6
            ++num_recycled;
1351
6
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
1352
6
            partition_keys.push_back(k);
1353
6
            if (part_pb.db_id() > 0) {
1354
6
                partition_version_keys.push_back(partition_version_key(
1355
6
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
1356
6
            }
1357
6
            metrics_context.total_recycled_num = num_recycled;
1358
6
            metrics_context.report();
1359
6
        }
1360
6
        return ret;
1361
6
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
1257
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
1258
2
        ++num_scanned;
1259
2
        RecyclePartitionPB part_pb;
1260
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
1261
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
1262
0
            return -1;
1263
0
        }
1264
2
        int64_t current_time = ::time(nullptr);
1265
2
        if (current_time <
1266
2
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
1267
0
            return 0;
1268
0
        }
1269
2
        ++num_expired;
1270
        // decode partition_id
1271
2
        auto k1 = k;
1272
2
        k1.remove_prefix(1);
1273
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1274
2
        decode_key(&k1, &out);
1275
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
1276
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
1277
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
1278
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
1279
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
1280
        // Change state to RECYCLING
1281
2
        std::unique_ptr<Transaction> txn;
1282
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1283
2
        if (err != TxnErrorCode::TXN_OK) {
1284
0
            LOG_WARNING("failed to create txn").tag("err", err);
1285
0
            return -1;
1286
0
        }
1287
2
        std::string val;
1288
2
        err = txn->get(k, &val);
1289
2
        if (err ==
1290
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
1291
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
1292
0
            return 0;
1293
0
        }
1294
2
        if (err != TxnErrorCode::TXN_OK) {
1295
0
            LOG_WARNING("failed to get kv");
1296
0
            return -1;
1297
0
        }
1298
2
        part_pb.Clear();
1299
2
        if (!part_pb.ParseFromString(val)) {
1300
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
1301
0
            return -1;
1302
0
        }
1303
        // Partitions with PREPARED state MUST have no data
1304
2
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
1305
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
1306
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
1307
1
            txn->put(k, part_pb.SerializeAsString());
1308
1
            err = txn->commit();
1309
1
            if (err != TxnErrorCode::TXN_OK) {
1310
0
                LOG_WARNING("failed to commit txn: {}", err);
1311
0
                return -1;
1312
0
            }
1313
1
        }
1314
1315
2
        int ret = 0;
1316
2
        for (int64_t index_id : part_pb.index_id()) {
1317
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id,
1318
2
                                is_empty_tablet) != 0) {
1319
1
                LOG_WARNING("failed to recycle tablets under partition")
1320
1
                        .tag("table_id", part_pb.table_id())
1321
1
                        .tag("instance_id", instance_id_)
1322
1
                        .tag("index_id", index_id)
1323
1
                        .tag("partition_id", partition_id);
1324
1
                ret = -1;
1325
1
            }
1326
2
        }
1327
2
        if (ret == 0 && part_pb.has_db_id()) {
1328
            // Recycle the versioned keys
1329
1
            std::unique_ptr<Transaction> txn;
1330
1
            err = txn_kv_->create_txn(&txn);
1331
1
            if (err != TxnErrorCode::TXN_OK) {
1332
0
                LOG_WARNING("failed to create txn").tag("err", err);
1333
0
                return -1;
1334
0
            }
1335
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
1336
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
1337
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
1338
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
1339
1
            versioned_remove_all(txn.get(), meta_key);
1340
1
            txn->remove(index_key);
1341
1
            txn->remove(inverted_index_key);
1342
1
            err = txn->commit();
1343
1
            if (err != TxnErrorCode::TXN_OK) {
1344
0
                LOG_WARNING("failed to commit txn").tag("err", err);
1345
0
                return -1;
1346
0
            }
1347
1
        }
1348
1349
2
        if (ret == 0) {
1350
1
            ++num_recycled;
1351
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
1352
1
            partition_keys.push_back(k);
1353
1
            if (part_pb.db_id() > 0) {
1354
1
                partition_version_keys.push_back(partition_version_key(
1355
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
1356
1
            }
1357
1
            metrics_context.total_recycled_num = num_recycled;
1358
1
            metrics_context.report();
1359
1
        }
1360
2
        return ret;
1361
2
    };
1362
1363
14
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
1364
4
        if (partition_keys.empty()) return 0;
1365
3
        DORIS_CLOUD_DEFER {
1366
3
            partition_keys.clear();
1367
3
            partition_version_keys.clear();
1368
3
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
1365
2
        DORIS_CLOUD_DEFER {
1366
2
            partition_keys.clear();
1367
2
            partition_version_keys.clear();
1368
2
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
1365
1
        DORIS_CLOUD_DEFER {
1366
1
            partition_keys.clear();
1367
1
            partition_version_keys.clear();
1368
1
        };
1369
3
        std::unique_ptr<Transaction> txn;
1370
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1371
3
        if (err != TxnErrorCode::TXN_OK) {
1372
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
1373
0
            return -1;
1374
0
        }
1375
7
        for (auto& k : partition_keys) {
1376
7
            txn->remove(k);
1377
7
        }
1378
7
        for (auto& k : partition_version_keys) {
1379
7
            txn->remove(k);
1380
7
        }
1381
3
        err = txn->commit();
1382
3
        if (err != TxnErrorCode::TXN_OK) {
1383
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
1384
0
                         << " err=" << err;
1385
0
            return -1;
1386
0
        }
1387
3
        return 0;
1388
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
1363
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
1364
2
        if (partition_keys.empty()) return 0;
1365
2
        DORIS_CLOUD_DEFER {
1366
2
            partition_keys.clear();
1367
2
            partition_version_keys.clear();
1368
2
        };
1369
2
        std::unique_ptr<Transaction> txn;
1370
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1371
2
        if (err != TxnErrorCode::TXN_OK) {
1372
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
1373
0
            return -1;
1374
0
        }
1375
6
        for (auto& k : partition_keys) {
1376
6
            txn->remove(k);
1377
6
        }
1378
6
        for (auto& k : partition_version_keys) {
1379
6
            txn->remove(k);
1380
6
        }
1381
2
        err = txn->commit();
1382
2
        if (err != TxnErrorCode::TXN_OK) {
1383
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
1384
0
                         << " err=" << err;
1385
0
            return -1;
1386
0
        }
1387
2
        return 0;
1388
2
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
1363
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
1364
2
        if (partition_keys.empty()) return 0;
1365
1
        DORIS_CLOUD_DEFER {
1366
1
            partition_keys.clear();
1367
1
            partition_version_keys.clear();
1368
1
        };
1369
1
        std::unique_ptr<Transaction> txn;
1370
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1371
1
        if (err != TxnErrorCode::TXN_OK) {
1372
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
1373
0
            return -1;
1374
0
        }
1375
1
        for (auto& k : partition_keys) {
1376
1
            txn->remove(k);
1377
1
        }
1378
1
        for (auto& k : partition_version_keys) {
1379
1
            txn->remove(k);
1380
1
        }
1381
1
        err = txn->commit();
1382
1
        if (err != TxnErrorCode::TXN_OK) {
1383
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
1384
0
                         << " err=" << err;
1385
0
            return -1;
1386
0
        }
1387
1
        return 0;
1388
1
    };
1389
1390
14
    if (config::enable_recycler_stats_metrics) {
1391
0
        scan_and_statistics_partitions();
1392
0
    }
1393
    // recycle_func and loop_done for scan and recycle
1394
14
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
1395
14
}
1396
1397
12
int InstanceRecycler::recycle_versions() {
1398
12
    int64_t num_scanned = 0;
1399
12
    int64_t num_recycled = 0;
1400
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
1401
1402
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
1403
1404
12
    auto start_time = steady_clock::now();
1405
1406
12
    DORIS_CLOUD_DEFER {
1407
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
1408
12
        metrics_context.finish_report();
1409
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
1410
12
                .tag("instance_id", instance_id_)
1411
12
                .tag("num_scanned", num_scanned)
1412
12
                .tag("num_recycled", num_recycled);
1413
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
1406
12
    DORIS_CLOUD_DEFER {
1407
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
1408
12
        metrics_context.finish_report();
1409
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
1410
12
                .tag("instance_id", instance_id_)
1411
12
                .tag("num_scanned", num_scanned)
1412
12
                .tag("num_recycled", num_recycled);
1413
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
1414
1415
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
1416
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
1417
12
    int64_t last_scanned_table_id = 0;
1418
12
    bool is_recycled = false; // Is last scanned kv recycled
1419
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
1420
12
                         &metrics_context, this](std::string_view k, std::string_view) {
1421
2
        ++num_scanned;
1422
2
        auto k1 = k;
1423
2
        k1.remove_prefix(1);
1424
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
1425
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1426
2
        decode_key(&k1, &out);
1427
2
        DCHECK_EQ(out.size(), 6) << k;
1428
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
1429
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
1430
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
1431
0
            return 0;
1432
0
        }
1433
2
        last_scanned_table_id = table_id;
1434
2
        is_recycled = false;
1435
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
1436
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
1437
2
        std::unique_ptr<Transaction> txn;
1438
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1439
2
        if (err != TxnErrorCode::TXN_OK) {
1440
0
            return -1;
1441
0
        }
1442
2
        std::unique_ptr<RangeGetIterator> iter;
1443
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
1444
2
        if (err != TxnErrorCode::TXN_OK) {
1445
0
            return -1;
1446
0
        }
1447
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
1448
1
            return 0;
1449
1
        }
1450
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
1451
        // 1. Remove all partition version kvs of this table
1452
1
        auto partition_version_key_begin =
1453
1
                partition_version_key({instance_id_, db_id, table_id, 0});
1454
1
        auto partition_version_key_end =
1455
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
1456
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
1457
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
1458
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
1459
1
                     << " table_id=" << table_id;
1460
        // 2. Remove the table version kv of this table
1461
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
1462
1
        txn->remove(tbl_version_key);
1463
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
1464
        // 3. Remove mow delete bitmap update lock and tablet job lock
1465
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
1466
1
        txn->remove(lock_key);
1467
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
1468
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
1469
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
1470
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
1471
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
1472
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
1473
1
                     << " table_id=" << table_id;
1474
1
        err = txn->commit();
1475
1
        if (err != TxnErrorCode::TXN_OK) {
1476
0
            return -1;
1477
0
        }
1478
1
        metrics_context.total_recycled_num = ++num_recycled;
1479
1
        metrics_context.report();
1480
1
        is_recycled = true;
1481
1
        return 0;
1482
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
1420
2
                         &metrics_context, this](std::string_view k, std::string_view) {
1421
2
        ++num_scanned;
1422
2
        auto k1 = k;
1423
2
        k1.remove_prefix(1);
1424
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
1425
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1426
2
        decode_key(&k1, &out);
1427
2
        DCHECK_EQ(out.size(), 6) << k;
1428
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
1429
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
1430
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
1431
0
            return 0;
1432
0
        }
1433
2
        last_scanned_table_id = table_id;
1434
2
        is_recycled = false;
1435
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
1436
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
1437
2
        std::unique_ptr<Transaction> txn;
1438
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1439
2
        if (err != TxnErrorCode::TXN_OK) {
1440
0
            return -1;
1441
0
        }
1442
2
        std::unique_ptr<RangeGetIterator> iter;
1443
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
1444
2
        if (err != TxnErrorCode::TXN_OK) {
1445
0
            return -1;
1446
0
        }
1447
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
1448
1
            return 0;
1449
1
        }
1450
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
1451
        // 1. Remove all partition version kvs of this table
1452
1
        auto partition_version_key_begin =
1453
1
                partition_version_key({instance_id_, db_id, table_id, 0});
1454
1
        auto partition_version_key_end =
1455
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
1456
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
1457
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
1458
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
1459
1
                     << " table_id=" << table_id;
1460
        // 2. Remove the table version kv of this table
1461
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
1462
1
        txn->remove(tbl_version_key);
1463
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
1464
        // 3. Remove mow delete bitmap update lock and tablet job lock
1465
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
1466
1
        txn->remove(lock_key);
1467
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
1468
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
1469
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
1470
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
1471
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
1472
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
1473
1
                     << " table_id=" << table_id;
1474
1
        err = txn->commit();
1475
1
        if (err != TxnErrorCode::TXN_OK) {
1476
0
            return -1;
1477
0
        }
1478
1
        metrics_context.total_recycled_num = ++num_recycled;
1479
1
        metrics_context.report();
1480
1
        is_recycled = true;
1481
1
        return 0;
1482
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
1483
1484
12
    if (config::enable_recycler_stats_metrics) {
1485
0
        scan_and_statistics_versions();
1486
0
    }
1487
    // recycle_func and loop_done for scan and recycle
1488
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
1489
12
}
1490
1491
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
1492
                                      RecyclerMetricsContext& metrics_context, int64_t partition_id,
1493
41
                                      bool is_empty_tablet) {
1494
41
    int64_t num_scanned = 0;
1495
41
    std::atomic_long num_recycled = 0;
1496
1497
41
    std::string tablet_key_begin, tablet_key_end;
1498
41
    std::string stats_key_begin, stats_key_end;
1499
41
    std::string job_key_begin, job_key_end;
1500
1501
41
    std::string tablet_belongs;
1502
41
    if (partition_id > 0) {
1503
        // recycle tablets in a partition belonging to the index
1504
32
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
1505
32
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
1506
32
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
1507
32
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
1508
32
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
1509
32
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
1510
32
        tablet_belongs = "partition";
1511
32
    } else {
1512
        // recycle tablets in the index
1513
9
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
1514
9
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
1515
9
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
1516
9
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
1517
9
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
1518
9
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
1519
9
        tablet_belongs = "index";
1520
9
    }
1521
1522
41
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
1523
41
            .tag("table_id", table_id)
1524
41
            .tag("index_id", index_id)
1525
41
            .tag("partition_id", partition_id);
1526
1527
41
    auto start_time = steady_clock::now();
1528
1529
41
    DORIS_CLOUD_DEFER {
1530
41
        auto cost = duration<float>(steady_clock::now() - start_time).count();
1531
41
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
1532
41
                .tag("instance_id", instance_id_)
1533
41
                .tag("table_id", table_id)
1534
41
                .tag("index_id", index_id)
1535
41
                .tag("partition_id", partition_id)
1536
41
                .tag("num_scanned", num_scanned)
1537
41
                .tag("num_recycled", num_recycled);
1538
41
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElbENK3$_0clEv
Line
Count
Source
1529
37
    DORIS_CLOUD_DEFER {
1530
37
        auto cost = duration<float>(steady_clock::now() - start_time).count();
1531
37
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
1532
37
                .tag("instance_id", instance_id_)
1533
37
                .tag("table_id", table_id)
1534
37
                .tag("index_id", index_id)
1535
37
                .tag("partition_id", partition_id)
1536
37
                .tag("num_scanned", num_scanned)
1537
37
                .tag("num_recycled", num_recycled);
1538
37
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElbENK3$_0clEv
Line
Count
Source
1529
4
    DORIS_CLOUD_DEFER {
1530
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
1531
4
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
1532
4
                .tag("instance_id", instance_id_)
1533
4
                .tag("table_id", table_id)
1534
4
                .tag("index_id", index_id)
1535
4
                .tag("partition_id", partition_id)
1536
4
                .tag("num_scanned", num_scanned)
1537
4
                .tag("num_recycled", num_recycled);
1538
4
    };
1539
1540
    // The first string_view represents the tablet key which has been recycled
1541
    // The second bool represents whether the following fdb's tablet key deletion could be done using range move or not
1542
41
    using TabletKeyPair = std::pair<std::string_view, bool>;
1543
41
    SyncExecutor<TabletKeyPair> sync_executor(
1544
41
            _thread_pool_group.recycle_tablet_pool,
1545
41
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
1546
41
                        index_id, partition_id),
1547
251
            [](const TabletKeyPair& k) { return k.first.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElbENK3$_2clERKSt4pairISt17basic_string_viewIcSt11char_traitsIcEEbE
Line
Count
Source
1547
231
            [](const TabletKeyPair& k) { return k.first.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElbENK3$_2clERKSt4pairISt17basic_string_viewIcSt11char_traitsIcEEbE
Line
Count
Source
1547
20
            [](const TabletKeyPair& k) { return k.first.empty(); });
1548
1549
    // Elements in `tablet_keys` has the same lifetime as `it` in `scan_and_recycle`
1550
41
    std::vector<std::string> tablet_idx_keys;
1551
41
    std::vector<std::string> restore_job_keys;
1552
41
    std::vector<std::string> init_rs_keys;
1553
271
    auto recycle_func = [&, is_empty_tablet, this](std::string_view k, std::string_view v) -> int {
1554
271
        bool use_range_remove = true;
1555
271
        ++num_scanned;
1556
271
        doris::TabletMetaCloudPB tablet_meta_pb;
1557
271
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
1558
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
1559
0
            use_range_remove = false;
1560
0
            return -1;
1561
0
        }
1562
271
        int64_t tablet_id = tablet_meta_pb.tablet_id();
1563
1564
271
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
1565
20
            LOG(WARNING) << "lazy txn not finished tablet_meta_pb=" << tablet_meta_pb.tablet_id();
1566
20
            return -1;
1567
20
        }
1568
1569
251
        tablet_idx_keys.push_back(meta_tablet_idx_key({instance_id_, tablet_id}));
1570
251
        restore_job_keys.push_back(job_restore_tablet_key({instance_id_, tablet_id}));
1571
251
        if (!is_empty_tablet) {
1572
251
            sync_executor.add([this, &num_recycled, tid = tablet_id, range_move = use_range_remove,
1573
251
                               &metrics_context, k]() mutable -> TabletKeyPair {
1574
251
                if (recycle_tablet(tid, metrics_context) != 0) {
1575
0
                    LOG_WARNING("failed to recycle tablet")
1576
0
                            .tag("instance_id", instance_id_)
1577
0
                            .tag("tablet_id", tid);
1578
0
                    range_move = false;
1579
0
                    return {std::string_view(), range_move};
1580
0
                }
1581
251
                ++num_recycled;
1582
251
                LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
1583
251
                return {k, range_move};
1584
251
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElbENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENUlvE_clEv
Line
Count
Source
1573
231
                               &metrics_context, k]() mutable -> TabletKeyPair {
1574
231
                if (recycle_tablet(tid, metrics_context) != 0) {
1575
0
                    LOG_WARNING("failed to recycle tablet")
1576
0
                            .tag("instance_id", instance_id_)
1577
0
                            .tag("tablet_id", tid);
1578
0
                    range_move = false;
1579
0
                    return {std::string_view(), range_move};
1580
0
                }
1581
231
                ++num_recycled;
1582
231
                LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
1583
231
                return {k, range_move};
1584
231
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElbENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENUlvE_clEv
Line
Count
Source
1573
20
                               &metrics_context, k]() mutable -> TabletKeyPair {
1574
20
                if (recycle_tablet(tid, metrics_context) != 0) {
1575
0
                    LOG_WARNING("failed to recycle tablet")
1576
0
                            .tag("instance_id", instance_id_)
1577
0
                            .tag("tablet_id", tid);
1578
0
                    range_move = false;
1579
0
                    return {std::string_view(), range_move};
1580
0
                }
1581
20
                ++num_recycled;
1582
20
                LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
1583
20
                return {k, range_move};
1584
20
            });
1585
251
        } else {
1586
            // Empty tablet only has a [0-1] init rowset
1587
0
            init_rs_keys.push_back(meta_rowset_key({instance_id_, tablet_id, 1}));
1588
0
            DCHECK([&]() {
1589
0
                std::unique_ptr<Transaction> txn;
1590
0
                if (TxnErrorCode err = txn_kv_->create_txn(&txn); err != TxnErrorCode::TXN_OK) {
1591
0
                    LOG_ERROR("failed to create txn").tag("err", err);
1592
0
                    return false;
1593
0
                }
1594
0
                auto rs_key_begin = meta_rowset_key({instance_id_, tablet_id, 2});
1595
0
                auto rs_key_end = meta_rowset_key({instance_id_, tablet_id, INT64_MAX});
1596
0
                std::unique_ptr<RangeGetIterator> iter;
1597
0
                if (TxnErrorCode err = txn->get(rs_key_begin, rs_key_end, &iter, true, 1);
1598
0
                    err != TxnErrorCode::TXN_OK) {
1599
0
                    LOG_ERROR("failed to get kv").tag("err", err);
1600
0
                    return false;
1601
0
                }
1602
0
                if (iter->has_next()) {
1603
0
                    LOG_ERROR("tablet is not empty").tag("tablet_id", tablet_id);
1604
0
                    return false;
1605
0
                }
1606
0
                return true;
1607
0
            }());
1608
0
            sync_executor.add([k]() mutable -> TabletKeyPair {
1609
0
                LOG_INFO("k is {}, is empty {}", k, k.empty());
1610
0
                return {k, true};
1611
0
            });
Unexecuted instantiation: recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElbENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENUlvE1_clEv
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElbENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENUlvE1_clEv
1612
0
            ++num_recycled;
1613
0
        }
1614
251
        return 0;
1615
271
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElbENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
1553
231
    auto recycle_func = [&, is_empty_tablet, this](std::string_view k, std::string_view v) -> int {
1554
231
        bool use_range_remove = true;
1555
231
        ++num_scanned;
1556
231
        doris::TabletMetaCloudPB tablet_meta_pb;
1557
231
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
1558
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
1559
0
            use_range_remove = false;
1560
0
            return -1;
1561
0
        }
1562
231
        int64_t tablet_id = tablet_meta_pb.tablet_id();
1563
1564
231
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
1565
0
            LOG(WARNING) << "lazy txn not finished tablet_meta_pb=" << tablet_meta_pb.tablet_id();
1566
0
            return -1;
1567
0
        }
1568
1569
231
        tablet_idx_keys.push_back(meta_tablet_idx_key({instance_id_, tablet_id}));
1570
231
        restore_job_keys.push_back(job_restore_tablet_key({instance_id_, tablet_id}));
1571
231
        if (!is_empty_tablet) {
1572
231
            sync_executor.add([this, &num_recycled, tid = tablet_id, range_move = use_range_remove,
1573
231
                               &metrics_context, k]() mutable -> TabletKeyPair {
1574
231
                if (recycle_tablet(tid, metrics_context) != 0) {
1575
231
                    LOG_WARNING("failed to recycle tablet")
1576
231
                            .tag("instance_id", instance_id_)
1577
231
                            .tag("tablet_id", tid);
1578
231
                    range_move = false;
1579
231
                    return {std::string_view(), range_move};
1580
231
                }
1581
231
                ++num_recycled;
1582
231
                LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
1583
231
                return {k, range_move};
1584
231
            });
1585
231
        } else {
1586
            // Empty tablet only has a [0-1] init rowset
1587
0
            init_rs_keys.push_back(meta_rowset_key({instance_id_, tablet_id, 1}));
1588
0
            DCHECK([&]() {
1589
0
                std::unique_ptr<Transaction> txn;
1590
0
                if (TxnErrorCode err = txn_kv_->create_txn(&txn); err != TxnErrorCode::TXN_OK) {
1591
0
                    LOG_ERROR("failed to create txn").tag("err", err);
1592
0
                    return false;
1593
0
                }
1594
0
                auto rs_key_begin = meta_rowset_key({instance_id_, tablet_id, 2});
1595
0
                auto rs_key_end = meta_rowset_key({instance_id_, tablet_id, INT64_MAX});
1596
0
                std::unique_ptr<RangeGetIterator> iter;
1597
0
                if (TxnErrorCode err = txn->get(rs_key_begin, rs_key_end, &iter, true, 1);
1598
0
                    err != TxnErrorCode::TXN_OK) {
1599
0
                    LOG_ERROR("failed to get kv").tag("err", err);
1600
0
                    return false;
1601
0
                }
1602
0
                if (iter->has_next()) {
1603
0
                    LOG_ERROR("tablet is not empty").tag("tablet_id", tablet_id);
1604
0
                    return false;
1605
0
                }
1606
0
                return true;
1607
0
            }());
1608
0
            sync_executor.add([k]() mutable -> TabletKeyPair {
1609
0
                LOG_INFO("k is {}, is empty {}", k, k.empty());
1610
0
                return {k, true};
1611
0
            });
1612
0
            ++num_recycled;
1613
0
        }
1614
231
        return 0;
1615
231
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElbENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
1553
40
    auto recycle_func = [&, is_empty_tablet, this](std::string_view k, std::string_view v) -> int {
1554
40
        bool use_range_remove = true;
1555
40
        ++num_scanned;
1556
40
        doris::TabletMetaCloudPB tablet_meta_pb;
1557
40
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
1558
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
1559
0
            use_range_remove = false;
1560
0
            return -1;
1561
0
        }
1562
40
        int64_t tablet_id = tablet_meta_pb.tablet_id();
1563
1564
40
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
1565
20
            LOG(WARNING) << "lazy txn not finished tablet_meta_pb=" << tablet_meta_pb.tablet_id();
1566
20
            return -1;
1567
20
        }
1568
1569
20
        tablet_idx_keys.push_back(meta_tablet_idx_key({instance_id_, tablet_id}));
1570
20
        restore_job_keys.push_back(job_restore_tablet_key({instance_id_, tablet_id}));
1571
20
        if (!is_empty_tablet) {
1572
20
            sync_executor.add([this, &num_recycled, tid = tablet_id, range_move = use_range_remove,
1573
20
                               &metrics_context, k]() mutable -> TabletKeyPair {
1574
20
                if (recycle_tablet(tid, metrics_context) != 0) {
1575
20
                    LOG_WARNING("failed to recycle tablet")
1576
20
                            .tag("instance_id", instance_id_)
1577
20
                            .tag("tablet_id", tid);
1578
20
                    range_move = false;
1579
20
                    return {std::string_view(), range_move};
1580
20
                }
1581
20
                ++num_recycled;
1582
20
                LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
1583
20
                return {k, range_move};
1584
20
            });
1585
20
        } else {
1586
            // Empty tablet only has a [0-1] init rowset
1587
0
            init_rs_keys.push_back(meta_rowset_key({instance_id_, tablet_id, 1}));
1588
0
            DCHECK([&]() {
1589
0
                std::unique_ptr<Transaction> txn;
1590
0
                if (TxnErrorCode err = txn_kv_->create_txn(&txn); err != TxnErrorCode::TXN_OK) {
1591
0
                    LOG_ERROR("failed to create txn").tag("err", err);
1592
0
                    return false;
1593
0
                }
1594
0
                auto rs_key_begin = meta_rowset_key({instance_id_, tablet_id, 2});
1595
0
                auto rs_key_end = meta_rowset_key({instance_id_, tablet_id, INT64_MAX});
1596
0
                std::unique_ptr<RangeGetIterator> iter;
1597
0
                if (TxnErrorCode err = txn->get(rs_key_begin, rs_key_end, &iter, true, 1);
1598
0
                    err != TxnErrorCode::TXN_OK) {
1599
0
                    LOG_ERROR("failed to get kv").tag("err", err);
1600
0
                    return false;
1601
0
                }
1602
0
                if (iter->has_next()) {
1603
0
                    LOG_ERROR("tablet is not empty").tag("tablet_id", tablet_id);
1604
0
                    return false;
1605
0
                }
1606
0
                return true;
1607
0
            }());
1608
0
            sync_executor.add([k]() mutable -> TabletKeyPair {
1609
0
                LOG_INFO("k is {}, is empty {}", k, k.empty());
1610
0
                return {k, true};
1611
0
            });
1612
0
            ++num_recycled;
1613
0
        }
1614
20
        return 0;
1615
40
    };
1616
1617
    // TODO(AlexYue): Add one ut to cover use_range_remove = false
1618
41
    auto loop_done = [&, this]() -> int {
1619
41
        bool finished = true;
1620
41
        auto tablet_keys = sync_executor.when_all(&finished);
1621
41
        if (!finished) {
1622
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
1623
0
            return -1;
1624
0
        }
1625
41
        if (tablet_keys.empty() && tablet_idx_keys.empty()) return 0;
1626
        // sort the vector using key's order
1627
39
        std::sort(tablet_keys.begin(), tablet_keys.end(),
1628
980
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElbENK3$_1clEvENKUlRKT_RKT0_E_clISt4pairISt17basic_string_viewIcSt11char_traitsIcEEbESI_EEDaS7_SA_
Line
Count
Source
1628
944
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElbENK3$_1clEvENKUlRKT_RKT0_E_clISt4pairISt17basic_string_viewIcSt11char_traitsIcEEbESI_EEDaS7_SA_
Line
Count
Source
1628
36
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
1629
39
        bool use_range_remove = true;
1630
251
        for (auto& [_, remove] : tablet_keys) {
1631
251
            if (!remove) {
1632
0
                use_range_remove = remove;
1633
0
                break;
1634
0
            }
1635
251
        }
1636
39
        DORIS_CLOUD_DEFER {
1637
39
            tablet_idx_keys.clear();
1638
39
            restore_job_keys.clear();
1639
39
            init_rs_keys.clear();
1640
39
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElbENK3$_1clEvENKUlvE_clEv
Line
Count
Source
1636
37
        DORIS_CLOUD_DEFER {
1637
37
            tablet_idx_keys.clear();
1638
37
            restore_job_keys.clear();
1639
37
            init_rs_keys.clear();
1640
37
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElbENK3$_1clEvENKUlvE_clEv
Line
Count
Source
1636
2
        DORIS_CLOUD_DEFER {
1637
2
            tablet_idx_keys.clear();
1638
2
            restore_job_keys.clear();
1639
2
            init_rs_keys.clear();
1640
2
        };
1641
39
        std::unique_ptr<Transaction> txn;
1642
39
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
1643
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
1644
0
            return -1;
1645
0
        }
1646
39
        std::string tablet_key_end;
1647
39
        if (!tablet_keys.empty()) {
1648
39
            if (use_range_remove) {
1649
39
                tablet_key_end = std::string(tablet_keys.back().first) + '\x00';
1650
39
                txn->remove(tablet_keys.front().first, tablet_key_end);
1651
39
            } else {
1652
0
                for (auto& [k, _] : tablet_keys) {
1653
0
                    txn->remove(k);
1654
0
                }
1655
0
            }
1656
39
        }
1657
251
        for (auto& k : tablet_idx_keys) {
1658
251
            txn->remove(k);
1659
251
        }
1660
251
        for (auto& k : restore_job_keys) {
1661
251
            txn->remove(k);
1662
251
        }
1663
39
        for (auto& k : init_rs_keys) {
1664
0
            txn->remove(k);
1665
0
        }
1666
39
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
1667
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
1668
0
                         << ", err=" << err;
1669
0
            return -1;
1670
0
        }
1671
39
        return 0;
1672
39
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElbENK3$_1clEv
Line
Count
Source
1618
37
    auto loop_done = [&, this]() -> int {
1619
37
        bool finished = true;
1620
37
        auto tablet_keys = sync_executor.when_all(&finished);
1621
37
        if (!finished) {
1622
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
1623
0
            return -1;
1624
0
        }
1625
37
        if (tablet_keys.empty() && tablet_idx_keys.empty()) return 0;
1626
        // sort the vector using key's order
1627
37
        std::sort(tablet_keys.begin(), tablet_keys.end(),
1628
37
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
1629
37
        bool use_range_remove = true;
1630
231
        for (auto& [_, remove] : tablet_keys) {
1631
231
            if (!remove) {
1632
0
                use_range_remove = remove;
1633
0
                break;
1634
0
            }
1635
231
        }
1636
37
        DORIS_CLOUD_DEFER {
1637
37
            tablet_idx_keys.clear();
1638
37
            restore_job_keys.clear();
1639
37
            init_rs_keys.clear();
1640
37
        };
1641
37
        std::unique_ptr<Transaction> txn;
1642
37
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
1643
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
1644
0
            return -1;
1645
0
        }
1646
37
        std::string tablet_key_end;
1647
37
        if (!tablet_keys.empty()) {
1648
37
            if (use_range_remove) {
1649
37
                tablet_key_end = std::string(tablet_keys.back().first) + '\x00';
1650
37
                txn->remove(tablet_keys.front().first, tablet_key_end);
1651
37
            } else {
1652
0
                for (auto& [k, _] : tablet_keys) {
1653
0
                    txn->remove(k);
1654
0
                }
1655
0
            }
1656
37
        }
1657
231
        for (auto& k : tablet_idx_keys) {
1658
231
            txn->remove(k);
1659
231
        }
1660
231
        for (auto& k : restore_job_keys) {
1661
231
            txn->remove(k);
1662
231
        }
1663
37
        for (auto& k : init_rs_keys) {
1664
0
            txn->remove(k);
1665
0
        }
1666
37
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
1667
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
1668
0
                         << ", err=" << err;
1669
0
            return -1;
1670
0
        }
1671
37
        return 0;
1672
37
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElbENK3$_1clEv
Line
Count
Source
1618
4
    auto loop_done = [&, this]() -> int {
1619
4
        bool finished = true;
1620
4
        auto tablet_keys = sync_executor.when_all(&finished);
1621
4
        if (!finished) {
1622
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
1623
0
            return -1;
1624
0
        }
1625
4
        if (tablet_keys.empty() && tablet_idx_keys.empty()) return 0;
1626
        // sort the vector using key's order
1627
2
        std::sort(tablet_keys.begin(), tablet_keys.end(),
1628
2
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
1629
2
        bool use_range_remove = true;
1630
20
        for (auto& [_, remove] : tablet_keys) {
1631
20
            if (!remove) {
1632
0
                use_range_remove = remove;
1633
0
                break;
1634
0
            }
1635
20
        }
1636
2
        DORIS_CLOUD_DEFER {
1637
2
            tablet_idx_keys.clear();
1638
2
            restore_job_keys.clear();
1639
2
            init_rs_keys.clear();
1640
2
        };
1641
2
        std::unique_ptr<Transaction> txn;
1642
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
1643
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
1644
0
            return -1;
1645
0
        }
1646
2
        std::string tablet_key_end;
1647
2
        if (!tablet_keys.empty()) {
1648
2
            if (use_range_remove) {
1649
2
                tablet_key_end = std::string(tablet_keys.back().first) + '\x00';
1650
2
                txn->remove(tablet_keys.front().first, tablet_key_end);
1651
2
            } else {
1652
0
                for (auto& [k, _] : tablet_keys) {
1653
0
                    txn->remove(k);
1654
0
                }
1655
0
            }
1656
2
        }
1657
20
        for (auto& k : tablet_idx_keys) {
1658
20
            txn->remove(k);
1659
20
        }
1660
20
        for (auto& k : restore_job_keys) {
1661
20
            txn->remove(k);
1662
20
        }
1663
2
        for (auto& k : init_rs_keys) {
1664
0
            txn->remove(k);
1665
0
        }
1666
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
1667
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
1668
0
                         << ", err=" << err;
1669
0
            return -1;
1670
0
        }
1671
2
        return 0;
1672
2
    };
1673
1674
41
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
1675
41
                               std::move(loop_done));
1676
41
    if (ret != 0) {
1677
2
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
1678
2
        return ret;
1679
2
    }
1680
1681
    // directly remove tablet stats and tablet jobs of these dropped index or partition
1682
39
    std::unique_ptr<Transaction> txn;
1683
39
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
1684
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
1685
0
        return -1;
1686
0
    }
1687
39
    txn->remove(stats_key_begin, stats_key_end);
1688
39
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
1689
39
                 << " end=" << hex(stats_key_end);
1690
39
    txn->remove(job_key_begin, job_key_end);
1691
39
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
1692
39
    std::string schema_key_begin, schema_key_end;
1693
39
    std::string schema_dict_key;
1694
39
    if (partition_id <= 0) {
1695
        // Delete schema kv of this index
1696
8
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
1697
8
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
1698
8
        txn->remove(schema_key_begin, schema_key_end);
1699
8
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
1700
8
                     << " end=" << hex(schema_key_end);
1701
8
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
1702
8
        txn->remove(schema_dict_key);
1703
8
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
1704
8
    }
1705
1706
39
    TxnErrorCode err = txn->commit();
1707
39
    if (err != TxnErrorCode::TXN_OK) {
1708
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
1709
0
                     << " err=" << err;
1710
0
        return -1;
1711
0
    }
1712
1713
39
    return ret;
1714
39
}
1715
1716
4.00k
int InstanceRecycler::delete_rowset_data(const doris::RowsetMetaCloudPB& rs_meta_pb) {
1717
4.00k
    int64_t num_segments = rs_meta_pb.num_segments();
1718
4.00k
    if (num_segments <= 0) return 0;
1719
4.00k
    if (!rs_meta_pb.has_tablet_schema()) {
1720
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
1721
0
                                  rs_meta_pb.rowset_id_v2());
1722
0
    }
1723
4.00k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
1724
4.00k
    if (it == accessor_map_.end()) {
1725
0
        LOG_WARNING("instance has no such resource id")
1726
0
                .tag("instance_id", instance_id_)
1727
0
                .tag("resource_id", rs_meta_pb.resource_id());
1728
0
        return -1;
1729
0
    }
1730
4.00k
    auto& accessor = it->second;
1731
4.00k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
1732
4.00k
    int64_t tablet_id = rs_meta_pb.tablet_id();
1733
    // process inverted indexes
1734
4.00k
    std::vector<std::pair<int64_t, std::string>> index_ids;
1735
4.00k
    index_ids.reserve(rs_meta_pb.tablet_schema().index_size());
1736
8.00k
    for (auto& i : rs_meta_pb.tablet_schema().index()) {
1737
8.00k
        if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
1738
8.00k
            index_ids.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
1739
8.00k
        }
1740
8.00k
    }
1741
4.00k
    std::vector<std::string> file_paths;
1742
4.00k
    auto tablet_schema = rs_meta_pb.tablet_schema();
1743
4.00k
    auto index_storage_format = InvertedIndexStorageFormatPB::V1;
1744
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
1745
20.0k
        file_paths.push_back(segment_path(tablet_id, rowset_id, i));
1746
20.0k
        if (tablet_schema.has_inverted_index_storage_format()) {
1747
10.0k
            index_storage_format = tablet_schema.inverted_index_storage_format();
1748
10.0k
        }
1749
20.0k
        if (index_storage_format == InvertedIndexStorageFormatPB::V1) {
1750
40.0k
            for (const auto& index_id : index_ids) {
1751
40.0k
                file_paths.push_back(inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
1752
40.0k
                                                            index_id.second));
1753
40.0k
            }
1754
20.0k
        } else if (!index_ids.empty()) {
1755
0
            file_paths.push_back(inverted_index_path_v2(tablet_id, rowset_id, i));
1756
0
        }
1757
20.0k
    }
1758
    // TODO(AlexYue): seems could do do batch
1759
4.00k
    return accessor->delete_files(file_paths);
1760
4.00k
}
1761
1762
int InstanceRecycler::delete_rowset_data(
1763
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
1764
32
        RecyclerMetricsContext& metrics_context) {
1765
32
    int ret = 0;
1766
    // resource_id -> file_paths
1767
32
    std::map<std::string, std::vector<std::string>> resource_file_paths;
1768
    // (resource_id, tablet_id, rowset_id)
1769
32
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
1770
32
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
1771
1772
6.14k
    for (const auto& [_, rs] : rowsets) {
1773
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
1774
        // due to aborted schema change.
1775
6.14k
        if (is_formal_rowset) {
1776
3.12k
            std::lock_guard lock(recycled_tablets_mtx_);
1777
3.12k
            if (recycled_tablets_.count(rs.tablet_id())) {
1778
0
                continue; // Rowset data has already been deleted
1779
0
            }
1780
3.12k
        }
1781
1782
6.14k
        auto it = accessor_map_.find(rs.resource_id());
1783
        // possible if the accessor is not initilized correctly
1784
6.14k
        if (it == accessor_map_.end()) [[unlikely]] {
1785
1
            LOG_WARNING("instance has no such resource id")
1786
1
                    .tag("instance_id", instance_id_)
1787
1
                    .tag("resource_id", rs.resource_id());
1788
1
            ret = -1;
1789
1
            continue;
1790
1
        }
1791
1792
6.14k
        auto& file_paths = resource_file_paths[rs.resource_id()];
1793
6.14k
        const auto& rowset_id = rs.rowset_id_v2();
1794
6.14k
        int64_t tablet_id = rs.tablet_id();
1795
6.14k
        int64_t num_segments = rs.num_segments();
1796
6.14k
        if (num_segments <= 0) {
1797
0
            metrics_context.total_recycled_num++;
1798
0
            metrics_context.total_recycled_data_size += rs.total_disk_size();
1799
0
            continue;
1800
0
        }
1801
1802
        // Process inverted indexes
1803
6.14k
        std::vector<std::pair<int64_t, std::string>> index_ids;
1804
        // default format as v1.
1805
6.14k
        InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
1806
6.14k
        int inverted_index_get_ret = 0;
1807
6.14k
        if (rs.has_tablet_schema()) {
1808
5.54k
            for (const auto& index : rs.tablet_schema().index()) {
1809
5.54k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
1810
5.54k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
1811
5.54k
                }
1812
5.54k
            }
1813
2.59k
            if (rs.tablet_schema().has_inverted_index_storage_format()) {
1814
2.56k
                index_format = rs.tablet_schema().inverted_index_storage_format();
1815
2.56k
            }
1816
3.55k
        } else {
1817
3.55k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
1818
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
1819
0
                                "instance_id="
1820
0
                             << instance_id_ << " tablet_id=" << tablet_id
1821
0
                             << " rowset_id=" << rowset_id;
1822
0
                ret = -1;
1823
0
                continue;
1824
0
            }
1825
3.55k
            InvertedIndexInfo index_info;
1826
3.55k
            inverted_index_get_ret =
1827
3.55k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
1828
3.55k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
1829
3.55k
                                     &inverted_index_get_ret);
1830
3.55k
            if (inverted_index_get_ret == 0) {
1831
3.05k
                index_format = index_info.first;
1832
3.05k
                index_ids = index_info.second;
1833
3.05k
            } else if (inverted_index_get_ret == 1) {
1834
                // 1. Schema kv not found means tablet has been recycled
1835
                // Maybe some tablet recycle failed by some bugs
1836
                // We need to delete again to double check
1837
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
1838
                // because we are uncertain about the inverted index information.
1839
                // If there are inverted indexes, some data might not be deleted,
1840
                // but this is acceptable as we have made our best effort to delete the data.
1841
503
                LOG_INFO(
1842
503
                        "delete rowset data schema kv not found, need to delete again to double "
1843
503
                        "check")
1844
503
                        .tag("instance_id", instance_id_)
1845
503
                        .tag("tablet_id", tablet_id)
1846
503
                        .tag("rowset", rs.ShortDebugString());
1847
                // Currently index_ids is guaranteed to be empty,
1848
                // but we clear it again here as a safeguard against future code changes
1849
                // that might cause index_ids to no longer be empty
1850
503
                index_format = InvertedIndexStorageFormatPB::V2;
1851
503
                index_ids.clear();
1852
503
            } else {
1853
0
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
1854
0
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
1855
0
                ret = -1;
1856
0
                continue;
1857
0
            }
1858
3.55k
        }
1859
6.14k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
1860
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
1861
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
1862
5
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
1863
5
            continue;
1864
5
        }
1865
36.8k
        for (int64_t i = 0; i < num_segments; ++i) {
1866
30.6k
            file_paths.push_back(segment_path(tablet_id, rowset_id, i));
1867
30.6k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
1868
59.2k
                for (const auto& index_id : index_ids) {
1869
59.2k
                    file_paths.push_back(inverted_index_path_v1(tablet_id, rowset_id, i,
1870
59.2k
                                                                index_id.first, index_id.second));
1871
59.2k
                }
1872
28.1k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
1873
                // try to recycle inverted index v2 when get_ret == 1
1874
                // we treat schema not found as if it has a v2 format inverted index
1875
                // to reduce chance of data leakage
1876
2.50k
                if (inverted_index_get_ret == 1) {
1877
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
1878
2.50k
                            .tag("instance_id", instance_id_)
1879
2.50k
                            .tag("inverted index v2 path",
1880
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, i));
1881
2.50k
                }
1882
2.50k
                file_paths.push_back(inverted_index_path_v2(tablet_id, rowset_id, i));
1883
2.50k
            }
1884
30.6k
        }
1885
6.13k
    }
1886
1887
32
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
1888
32
                                                 "delete_rowset_data",
1889
34
                                                 [](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
1889
34
                                                 [](const int& ret) { return ret != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clERKi
1890
32
    for (auto& [resource_id, file_paths] : resource_file_paths) {
1891
29
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
1892
29
            DCHECK(accessor_map_.count(*rid))
1893
0
                    << "uninitilized accessor, instance_id=" << instance_id_
1894
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
1895
29
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
1896
29
                                     &accessor_map_);
1897
29
            if (!accessor_map_.contains(*rid)) {
1898
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
1899
0
                        .tag("resource_id", resource_id)
1900
0
                        .tag("instance_id", instance_id_);
1901
0
                return -1;
1902
0
            }
1903
29
            auto& accessor = accessor_map_[*rid];
1904
29
            int ret = accessor->delete_files(*paths);
1905
29
            if (!ret) {
1906
                // deduplication of different files with the same rowset id
1907
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
1908
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
1909
29
                std::set<std::string> deleted_rowset_id;
1910
1911
29
                std::for_each(
1912
29
                        paths->begin(), paths->end(),
1913
92.3k
                        [&metrics_context, &rowsets, &deleted_rowset_id](const std::string& path) {
1914
92.3k
                            std::vector<std::string> str;
1915
92.3k
                            butil::SplitString(path, '/', &str);
1916
92.3k
                            std::string rowset_id;
1917
92.3k
                            if (auto pos = str.back().find('_'); pos != std::string::npos) {
1918
92.3k
                                rowset_id = str.back().substr(0, pos);
1919
92.3k
                            } else {
1920
0
                                LOG(WARNING) << "failed to parse rowset_id, path=" << path;
1921
0
                                return;
1922
0
                            }
1923
92.3k
                            auto rs_meta = rowsets.find(rowset_id);
1924
92.3k
                            if (rs_meta != rowsets.end() &&
1925
92.3k
                                !deleted_rowset_id.contains(rowset_id)) {
1926
6.13k
                                deleted_rowset_id.emplace(rowset_id);
1927
6.13k
                                metrics_context.total_recycled_data_size +=
1928
6.13k
                                        rs_meta->second.total_disk_size();
1929
6.13k
                                segment_metrics_context_.total_recycled_num +=
1930
6.13k
                                        rs_meta->second.num_segments();
1931
6.13k
                                segment_metrics_context_.total_recycled_data_size +=
1932
6.13k
                                        rs_meta->second.total_disk_size();
1933
6.13k
                                metrics_context.total_recycled_num++;
1934
6.13k
                            }
1935
92.3k
                        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
1913
92.3k
                        [&metrics_context, &rowsets, &deleted_rowset_id](const std::string& path) {
1914
92.3k
                            std::vector<std::string> str;
1915
92.3k
                            butil::SplitString(path, '/', &str);
1916
92.3k
                            std::string rowset_id;
1917
92.3k
                            if (auto pos = str.back().find('_'); pos != std::string::npos) {
1918
92.3k
                                rowset_id = str.back().substr(0, pos);
1919
92.3k
                            } else {
1920
0
                                LOG(WARNING) << "failed to parse rowset_id, path=" << path;
1921
0
                                return;
1922
0
                            }
1923
92.3k
                            auto rs_meta = rowsets.find(rowset_id);
1924
92.3k
                            if (rs_meta != rowsets.end() &&
1925
92.3k
                                !deleted_rowset_id.contains(rowset_id)) {
1926
6.13k
                                deleted_rowset_id.emplace(rowset_id);
1927
6.13k
                                metrics_context.total_recycled_data_size +=
1928
6.13k
                                        rs_meta->second.total_disk_size();
1929
6.13k
                                segment_metrics_context_.total_recycled_num +=
1930
6.13k
                                        rs_meta->second.num_segments();
1931
6.13k
                                segment_metrics_context_.total_recycled_data_size +=
1932
6.13k
                                        rs_meta->second.total_disk_size();
1933
6.13k
                                metrics_context.total_recycled_num++;
1934
6.13k
                            }
1935
92.3k
                        });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
1936
29
                segment_metrics_context_.report();
1937
29
                metrics_context.report();
1938
29
            }
1939
29
            return ret;
1940
29
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
1891
29
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
1892
29
            DCHECK(accessor_map_.count(*rid))
1893
0
                    << "uninitilized accessor, instance_id=" << instance_id_
1894
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
1895
29
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
1896
29
                                     &accessor_map_);
1897
29
            if (!accessor_map_.contains(*rid)) {
1898
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
1899
0
                        .tag("resource_id", resource_id)
1900
0
                        .tag("instance_id", instance_id_);
1901
0
                return -1;
1902
0
            }
1903
29
            auto& accessor = accessor_map_[*rid];
1904
29
            int ret = accessor->delete_files(*paths);
1905
29
            if (!ret) {
1906
                // deduplication of different files with the same rowset id
1907
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
1908
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
1909
29
                std::set<std::string> deleted_rowset_id;
1910
1911
29
                std::for_each(
1912
29
                        paths->begin(), paths->end(),
1913
29
                        [&metrics_context, &rowsets, &deleted_rowset_id](const std::string& path) {
1914
29
                            std::vector<std::string> str;
1915
29
                            butil::SplitString(path, '/', &str);
1916
29
                            std::string rowset_id;
1917
29
                            if (auto pos = str.back().find('_'); pos != std::string::npos) {
1918
29
                                rowset_id = str.back().substr(0, pos);
1919
29
                            } else {
1920
29
                                LOG(WARNING) << "failed to parse rowset_id, path=" << path;
1921
29
                                return;
1922
29
                            }
1923
29
                            auto rs_meta = rowsets.find(rowset_id);
1924
29
                            if (rs_meta != rowsets.end() &&
1925
29
                                !deleted_rowset_id.contains(rowset_id)) {
1926
29
                                deleted_rowset_id.emplace(rowset_id);
1927
29
                                metrics_context.total_recycled_data_size +=
1928
29
                                        rs_meta->second.total_disk_size();
1929
29
                                segment_metrics_context_.total_recycled_num +=
1930
29
                                        rs_meta->second.num_segments();
1931
29
                                segment_metrics_context_.total_recycled_data_size +=
1932
29
                                        rs_meta->second.total_disk_size();
1933
29
                                metrics_context.total_recycled_num++;
1934
29
                            }
1935
29
                        });
1936
29
                segment_metrics_context_.report();
1937
29
                metrics_context.report();
1938
29
            }
1939
29
            return ret;
1940
29
        });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
1941
29
    }
1942
32
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
1943
5
        LOG_INFO(
1944
5
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
1945
5
                "resource_id={}, tablet_id={}, instance_id={}",
1946
5
                rowset_id, resource_id, tablet_id, instance_id_);
1947
5
        concurrent_delete_executor.add([&]() -> int {
1948
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
1949
5
            if (!ret) {
1950
5
                auto rs = rowsets.at(rowset_id);
1951
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
1952
5
                metrics_context.total_recycled_num++;
1953
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
1954
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
1955
5
                metrics_context.report();
1956
5
                segment_metrics_context_.report();
1957
5
            }
1958
5
            return ret;
1959
5
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_2clEv
Line
Count
Source
1947
5
        concurrent_delete_executor.add([&]() -> int {
1948
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
1949
5
            if (!ret) {
1950
5
                auto rs = rowsets.at(rowset_id);
1951
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
1952
5
                metrics_context.total_recycled_num++;
1953
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
1954
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
1955
5
                metrics_context.report();
1956
5
                segment_metrics_context_.report();
1957
5
            }
1958
5
            return ret;
1959
5
        });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_2clEv
1960
5
    }
1961
1962
32
    bool finished = true;
1963
32
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
1964
34
    for (int r : rets) {
1965
34
        if (r != 0) {
1966
0
            ret = -1;
1967
0
            break;
1968
0
        }
1969
34
    }
1970
32
    ret = finished ? ret : -1;
1971
32
    return ret;
1972
32
}
1973
1974
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
1975
2.90k
                                         const std::string& rowset_id) {
1976
2.90k
    auto it = accessor_map_.find(resource_id);
1977
2.90k
    if (it == accessor_map_.end()) {
1978
0
        LOG_WARNING("instance has no such resource id")
1979
0
                .tag("instance_id", instance_id_)
1980
0
                .tag("resource_id", resource_id)
1981
0
                .tag("tablet_id", tablet_id)
1982
0
                .tag("rowset_id", rowset_id);
1983
0
        return -1;
1984
0
    }
1985
2.90k
    auto& accessor = it->second;
1986
2.90k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
1987
2.90k
}
1988
1989
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
1990
                                                  RecyclerMetricsContext& metrics_context,
1991
0
                                                  int64_t partition_id, bool is_empty_tablet) {
1992
0
    std::string tablet_key_begin, tablet_key_end;
1993
1994
0
    if (partition_id > 0) {
1995
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
1996
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
1997
0
    } else {
1998
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
1999
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
2000
0
    }
2001
    // for calculate the total num or bytes of recyled objects
2002
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
2003
0
                                                          std::string_view v) -> int {
2004
0
        doris::TabletMetaCloudPB tablet_meta_pb;
2005
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
2006
0
            return 0;
2007
0
        }
2008
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
2009
2010
0
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
2011
0
            return 0;
2012
0
        }
2013
2014
0
        if (!is_empty_tablet) {
2015
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
2016
0
                return 0;
2017
0
            }
2018
0
            tablet_metrics_context_.total_need_recycle_num++;
2019
0
        }
2020
0
        return 0;
2021
0
    };
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_tablets_and_statisticsEllRNS0_22RecyclerMetricsContextElbENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES8_
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_tablets_and_statisticsEllRNS0_22RecyclerMetricsContextElbENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES8_
2022
0
    return scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics),
2023
0
                            [&metrics_context]() -> int {
2024
0
                                metrics_context.report();
2025
0
                                tablet_metrics_context_.report();
2026
0
                                return 0;
2027
0
                            });
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_tablets_and_statisticsEllRNS0_22RecyclerMetricsContextElbENK3$_1clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_tablets_and_statisticsEllRNS0_22RecyclerMetricsContextElbENK3$_1clEv
2028
0
}
2029
2030
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
2031
0
                                                 RecyclerMetricsContext& metrics_context) {
2032
0
    int ret = 0;
2033
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
2034
0
    std::unique_ptr<Transaction> txn;
2035
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2036
0
        LOG_WARNING("failed to recycle tablet ")
2037
0
                .tag("tablet id", tablet_id)
2038
0
                .tag("instance_id", instance_id_)
2039
0
                .tag("reason", "failed to create txn");
2040
0
        ret = -1;
2041
0
    }
2042
0
    GetRowsetResponse resp;
2043
0
    std::string msg;
2044
0
    MetaServiceCode code = MetaServiceCode::OK;
2045
    // get rowsets in tablet
2046
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
2047
0
                        tablet_id, code, msg, &resp);
2048
0
    if (code != MetaServiceCode::OK) {
2049
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
2050
0
                .tag("tablet id", tablet_id)
2051
0
                .tag("msg", msg)
2052
0
                .tag("code", code)
2053
0
                .tag("instance id", instance_id_);
2054
0
        ret = -1;
2055
0
    }
2056
0
    for (const auto& rs_meta : resp.rowset_meta()) {
2057
        /*
2058
        * For compatibility, we skip the loop for [0-1] here. 
2059
        * The purpose of this loop is to delete object files,
2060
        * and since [0-1] only has meta and doesn't have object files, 
2061
        * skipping it doesn't affect system correctness. 
2062
        *
2063
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below 
2064
        * would return error -1 directly, causing the recycle operation to fail.
2065
        *
2066
        * [0-1] doesn't have resource id is a bug.
2067
        * In the future, we will fix this problem, after that,
2068
        * we can remove this if statement.
2069
        *
2070
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
2071
        */
2072
2073
0
        if (rs_meta.end_version() == 1) {
2074
            // Assert that [0-1] has no resource_id to make sure
2075
            // this if statement will not be forgetted to remove
2076
            // when the resource id bug is fixed
2077
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
2078
0
            continue;
2079
0
        }
2080
0
        if (!rs_meta.has_resource_id()) {
2081
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
2082
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
2083
0
                    .tag("instance_id", instance_id_)
2084
0
                    .tag("tablet_id", tablet_id);
2085
0
            continue;
2086
0
        }
2087
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
2088
0
        auto it = accessor_map_.find(rs_meta.resource_id());
2089
        // possible if the accessor is not initilized correctly
2090
0
        if (it == accessor_map_.end()) [[unlikely]] {
2091
0
            LOG_WARNING(
2092
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
2093
0
                    "recycle process")
2094
0
                    .tag("tablet id", tablet_id)
2095
0
                    .tag("instance_id", instance_id_)
2096
0
                    .tag("resource_id", rs_meta.resource_id())
2097
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
2098
0
            continue;
2099
0
        }
2100
2101
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
2102
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
2103
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
2104
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
2105
0
    }
2106
0
    return ret;
2107
0
}
2108
2109
274
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
2110
274
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
2111
274
            .tag("instance_id", instance_id_)
2112
274
            .tag("tablet_id", tablet_id);
2113
2114
274
    int ret = 0;
2115
274
    auto start_time = steady_clock::now();
2116
2117
274
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
2118
2119
    // collect resource ids
2120
254
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
2121
254
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
2122
254
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
2123
254
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
2124
254
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
2125
254
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
2126
2127
254
    std::set<std::string> resource_ids;
2128
254
    int64_t recycle_rowsets_number = 0;
2129
254
    int64_t recycle_segments_number = 0;
2130
254
    int64_t recycle_rowsets_data_size = 0;
2131
254
    int64_t recycle_rowsets_index_size = 0;
2132
254
    int64_t recycle_restore_job_rowsets_number = 0;
2133
254
    int64_t recycle_restore_job_segments_number = 0;
2134
254
    int64_t recycle_restore_job_rowsets_data_size = 0;
2135
254
    int64_t recycle_restore_job_rowsets_index_size = 0;
2136
254
    int64_t max_rowset_version = 0;
2137
254
    int64_t min_rowset_creation_time = INT64_MAX;
2138
254
    int64_t max_rowset_creation_time = 0;
2139
254
    int64_t min_rowset_expiration_time = INT64_MAX;
2140
254
    int64_t max_rowset_expiration_time = 0;
2141
2142
254
    DORIS_CLOUD_DEFER {
2143
254
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2144
254
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
2145
254
                .tag("instance_id", instance_id_)
2146
254
                .tag("tablet_id", tablet_id)
2147
254
                .tag("recycle rowsets number", recycle_rowsets_number)
2148
254
                .tag("recycle segments number", recycle_segments_number)
2149
254
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
2150
254
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
2151
254
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
2152
254
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
2153
254
                .tag("all restore job rowsets recycle data size",
2154
254
                     recycle_restore_job_rowsets_data_size)
2155
254
                .tag("all restore job rowsets recycle index size",
2156
254
                     recycle_restore_job_rowsets_index_size)
2157
254
                .tag("max rowset version", max_rowset_version)
2158
254
                .tag("min rowset creation time", min_rowset_creation_time)
2159
254
                .tag("max rowset creation time", max_rowset_creation_time)
2160
254
                .tag("min rowset expiration time", min_rowset_expiration_time)
2161
254
                .tag("max rowset expiration time", max_rowset_expiration_time)
2162
254
                .tag("ret", ret);
2163
254
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2142
254
    DORIS_CLOUD_DEFER {
2143
254
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2144
254
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
2145
254
                .tag("instance_id", instance_id_)
2146
254
                .tag("tablet_id", tablet_id)
2147
254
                .tag("recycle rowsets number", recycle_rowsets_number)
2148
254
                .tag("recycle segments number", recycle_segments_number)
2149
254
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
2150
254
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
2151
254
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
2152
254
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
2153
254
                .tag("all restore job rowsets recycle data size",
2154
254
                     recycle_restore_job_rowsets_data_size)
2155
254
                .tag("all restore job rowsets recycle index size",
2156
254
                     recycle_restore_job_rowsets_index_size)
2157
254
                .tag("max rowset version", max_rowset_version)
2158
254
                .tag("min rowset creation time", min_rowset_creation_time)
2159
254
                .tag("max rowset creation time", max_rowset_creation_time)
2160
254
                .tag("min rowset expiration time", min_rowset_expiration_time)
2161
254
                .tag("max rowset expiration time", max_rowset_expiration_time)
2162
254
                .tag("ret", ret);
2163
254
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
2164
2165
254
    std::unique_ptr<Transaction> txn;
2166
254
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2167
0
        LOG_WARNING("failed to recycle tablet ")
2168
0
                .tag("tablet id", tablet_id)
2169
0
                .tag("instance_id", instance_id_)
2170
0
                .tag("reason", "failed to create txn");
2171
0
        ret = -1;
2172
0
    }
2173
254
    GetRowsetResponse resp;
2174
254
    std::string msg;
2175
254
    MetaServiceCode code = MetaServiceCode::OK;
2176
    // get rowsets in tablet
2177
254
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
2178
254
                        tablet_id, code, msg, &resp);
2179
254
    if (code != MetaServiceCode::OK) {
2180
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
2181
0
                .tag("tablet id", tablet_id)
2182
0
                .tag("msg", msg)
2183
0
                .tag("code", code)
2184
0
                .tag("instance id", instance_id_);
2185
0
        ret = -1;
2186
0
    }
2187
254
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
2188
2189
2.50k
    for (const auto& rs_meta : resp.rowset_meta()) {
2190
        /*
2191
        * For compatibility, we skip the loop for [0-1] here. 
2192
        * The purpose of this loop is to delete object files,
2193
        * and since [0-1] only has meta and doesn't have object files, 
2194
        * skipping it doesn't affect system correctness. 
2195
        *
2196
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below 
2197
        * would return error -1 directly, causing the recycle operation to fail.
2198
        *
2199
        * [0-1] doesn't have resource id is a bug.
2200
        * In the future, we will fix this problem, after that,
2201
        * we can remove this if statement.
2202
        *
2203
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
2204
        */
2205
2206
2.50k
        if (rs_meta.end_version() == 1) {
2207
            // Assert that [0-1] has no resource_id to make sure
2208
            // this if statement will not be forgetted to remove
2209
            // when the resource id bug is fixed
2210
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
2211
0
            recycle_rowsets_number += 1;
2212
0
            continue;
2213
0
        }
2214
2.50k
        if (!rs_meta.has_resource_id()) {
2215
1
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
2216
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
2217
1
                    .tag("instance_id", instance_id_)
2218
1
                    .tag("tablet_id", tablet_id);
2219
1
            return -1;
2220
1
        }
2221
2.50k
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
2222
2.50k
        auto it = accessor_map_.find(rs_meta.resource_id());
2223
        // possible if the accessor is not initilized correctly
2224
2.50k
        if (it == accessor_map_.end()) [[unlikely]] {
2225
1
            LOG_WARNING(
2226
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
2227
1
                    "recycle process")
2228
1
                    .tag("tablet id", tablet_id)
2229
1
                    .tag("instance_id", instance_id_)
2230
1
                    .tag("resource_id", rs_meta.resource_id())
2231
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
2232
1
            return -1;
2233
1
        }
2234
2.50k
        recycle_rowsets_number += 1;
2235
2.50k
        recycle_segments_number += rs_meta.num_segments();
2236
2.50k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
2237
2.50k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
2238
2.50k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
2239
2.50k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
2240
2.50k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
2241
2.50k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
2242
2.50k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
2243
2.50k
        resource_ids.emplace(rs_meta.resource_id());
2244
2.50k
    }
2245
2246
    // get restore job rowset in tablet
2247
252
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
2248
252
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
2249
252
    if (code != MetaServiceCode::OK) {
2250
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
2251
0
                .tag("tablet id", tablet_id)
2252
0
                .tag("msg", msg)
2253
0
                .tag("code", code)
2254
0
                .tag("instance id", instance_id_);
2255
0
        return -1;
2256
0
    }
2257
2258
252
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
2259
100
        if (!rs_meta.has_resource_id()) {
2260
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
2261
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
2262
0
                    .tag("instance_id", instance_id_)
2263
0
                    .tag("tablet_id", tablet_id);
2264
0
            return -1;
2265
0
        }
2266
2267
100
        auto it = accessor_map_.find(rs_meta.resource_id());
2268
        // possible if the accessor is not initilized correctly
2269
100
        if (it == accessor_map_.end()) [[unlikely]] {
2270
0
            LOG_WARNING(
2271
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
2272
0
                    "recycle process")
2273
0
                    .tag("tablet id", tablet_id)
2274
0
                    .tag("instance_id", instance_id_)
2275
0
                    .tag("resource_id", rs_meta.resource_id())
2276
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
2277
0
            return -1;
2278
0
        }
2279
100
        recycle_restore_job_rowsets_number += 1;
2280
100
        recycle_restore_job_segments_number += rs_meta.num_segments();
2281
100
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
2282
100
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
2283
100
        resource_ids.emplace(rs_meta.resource_id());
2284
100
    }
2285
2286
252
    LOG_INFO("recycle tablet start to delete object")
2287
252
            .tag("instance id", instance_id_)
2288
252
            .tag("tablet id", tablet_id)
2289
252
            .tag("recycle tablet resource ids are",
2290
252
                 std::accumulate(resource_ids.begin(), resource_ids.begin(), std::string(),
2291
252
                                 [](std::string rs_id, const auto& it) {
2292
0
                                     return rs_id.empty() ? it : rs_id + ", " + it;
2293
0
                                 }));
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_1clINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEEEDaSB_RKT_
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_1clINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEEEDaSB_RKT_
2294
2295
252
    SyncExecutor<int> concurrent_delete_executor(
2296
252
            _thread_pool_group.s3_producer_pool,
2297
252
            fmt::format("delete tablet {} s3 rowset", tablet_id),
2298
252
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKi
Line
Count
Source
2298
223
            [](const int& ret) { return ret != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKi
2299
2300
    // delete all rowset data in this tablet
2301
    // ATTN: there may be data leak if not all accessor initilized successfully
2302
    //       partial data deleted if the tablet is stored cross-storage vault
2303
    //       vault id is not attached to TabletMeta...
2304
252
    for (const auto& resource_id : resource_ids) {
2305
223
        concurrent_delete_executor.add([&, rs_id = resource_id,
2306
223
                                        accessor_ptr = accessor_map_[resource_id]]() {
2307
223
            std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01, [&](int*) {
2308
223
                g_bvar_recycler_vault_recycle_task_concurrency.put(
2309
223
                        {instance_id_, metrics_context.operation_type, rs_id}, -1);
2310
223
                metrics_context.report();
2311
223
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clEvENKUlPiE_clES5_
Line
Count
Source
2307
223
            std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01, [&](int*) {
2308
223
                g_bvar_recycler_vault_recycle_task_concurrency.put(
2309
223
                        {instance_id_, metrics_context.operation_type, rs_id}, -1);
2310
223
                metrics_context.report();
2311
223
            });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clEvENKUlPiE_clES5_
2312
223
            g_bvar_recycler_vault_recycle_task_concurrency.put(
2313
223
                    {instance_id_, metrics_context.operation_type, rs_id}, 1);
2314
223
            int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
2315
223
            if (res != 0) {
2316
1
                LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
2317
1
                             << " path=" << accessor_ptr->uri();
2318
1
                g_bvar_recycler_vault_recycle_status.put({instance_id_, rs_id, "abnormal"}, 1);
2319
1
                return -1;
2320
1
            }
2321
222
            g_bvar_recycler_vault_recycle_status.put({instance_id_, rs_id, "normal"}, 1);
2322
222
            return 0;
2323
223
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clEv
Line
Count
Source
2306
223
                                        accessor_ptr = accessor_map_[resource_id]]() {
2307
223
            std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01, [&](int*) {
2308
223
                g_bvar_recycler_vault_recycle_task_concurrency.put(
2309
223
                        {instance_id_, metrics_context.operation_type, rs_id}, -1);
2310
223
                metrics_context.report();
2311
223
            });
2312
223
            g_bvar_recycler_vault_recycle_task_concurrency.put(
2313
223
                    {instance_id_, metrics_context.operation_type, rs_id}, 1);
2314
223
            int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
2315
223
            if (res != 0) {
2316
1
                LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
2317
1
                             << " path=" << accessor_ptr->uri();
2318
1
                g_bvar_recycler_vault_recycle_status.put({instance_id_, rs_id, "abnormal"}, 1);
2319
1
                return -1;
2320
1
            }
2321
222
            g_bvar_recycler_vault_recycle_status.put({instance_id_, rs_id, "normal"}, 1);
2322
222
            return 0;
2323
223
        });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clEv
2324
223
    }
2325
2326
252
    bool finished = true;
2327
252
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
2328
252
    for (int r : rets) {
2329
223
        if (r != 0) {
2330
1
            ret = -1;
2331
1
        }
2332
223
    }
2333
2334
252
    ret = finished ? ret : -1;
2335
2336
252
    if (ret != 0) { // failed recycle tablet data
2337
1
        LOG_WARNING("ret!=0")
2338
1
                .tag("finished", finished)
2339
1
                .tag("ret", ret)
2340
1
                .tag("instance_id", instance_id_)
2341
1
                .tag("tablet_id", tablet_id);
2342
1
        return ret;
2343
1
    }
2344
2345
251
    tablet_metrics_context_.total_recycled_data_size +=
2346
251
            recycle_rowsets_data_size + recycle_rowsets_index_size;
2347
251
    tablet_metrics_context_.total_recycled_num += 1;
2348
251
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
2349
251
    segment_metrics_context_.total_recycled_data_size +=
2350
251
            recycle_rowsets_data_size + recycle_rowsets_index_size;
2351
251
    metrics_context.total_recycled_data_size +=
2352
251
            recycle_rowsets_data_size + recycle_rowsets_index_size;
2353
251
    tablet_metrics_context_.report();
2354
251
    segment_metrics_context_.report();
2355
251
    metrics_context.report();
2356
2357
251
    txn.reset();
2358
251
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2359
0
        LOG_WARNING("failed to recycle tablet ")
2360
0
                .tag("tablet id", tablet_id)
2361
0
                .tag("instance_id", instance_id_)
2362
0
                .tag("reason", "failed to create txn");
2363
0
        ret = -1;
2364
0
    }
2365
    // delete all rowset kv in this tablet
2366
251
    txn->remove(rs_key0, rs_key1);
2367
251
    txn->remove(recyc_rs_key0, recyc_rs_key1);
2368
251
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
2369
2370
    // remove delete bitmap for MoW table
2371
251
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
2372
251
    txn->remove(pending_key);
2373
251
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
2374
251
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
2375
251
    txn->remove(delete_bitmap_start, delete_bitmap_end);
2376
2377
251
    TxnErrorCode err = txn->commit();
2378
251
    if (err != TxnErrorCode::TXN_OK) {
2379
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
2380
0
        ret = -1;
2381
0
    }
2382
2383
251
    if (ret == 0) {
2384
        // All object files under tablet have been deleted
2385
251
        std::lock_guard lock(recycled_tablets_mtx_);
2386
251
        recycled_tablets_.insert(tablet_id);
2387
251
    }
2388
2389
251
    return ret;
2390
252
}
2391
2392
13
int InstanceRecycler::recycle_rowsets() {
2393
13
    const std::string task_name = "recycle_rowsets";
2394
13
    int64_t num_scanned = 0;
2395
13
    int64_t num_expired = 0;
2396
13
    int64_t num_prepare = 0;
2397
13
    int64_t num_compacted = 0;
2398
13
    int64_t num_empty_rowset = 0;
2399
13
    size_t total_rowset_key_size = 0;
2400
13
    size_t total_rowset_value_size = 0;
2401
13
    size_t expired_rowset_size = 0;
2402
13
    std::atomic_long num_recycled = 0;
2403
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2404
2405
13
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
2406
13
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
2407
13
    std::string recyc_rs_key0;
2408
13
    std::string recyc_rs_key1;
2409
13
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
2410
13
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
2411
2412
13
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
2413
2414
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2415
13
    register_recycle_task(task_name, start_time);
2416
2417
13
    DORIS_CLOUD_DEFER {
2418
13
        unregister_recycle_task(task_name);
2419
13
        int64_t cost =
2420
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2421
13
        metrics_context.finish_report();
2422
13
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
2423
13
                .tag("instance_id", instance_id_)
2424
13
                .tag("num_scanned", num_scanned)
2425
13
                .tag("num_expired", num_expired)
2426
13
                .tag("num_recycled", num_recycled)
2427
13
                .tag("num_recycled.prepare", num_prepare)
2428
13
                .tag("num_recycled.compacted", num_compacted)
2429
13
                .tag("num_recycled.empty_rowset", num_empty_rowset)
2430
13
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
2431
13
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
2432
13
                .tag("expired_rowset_meta_size", expired_rowset_size);
2433
13
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
2417
13
    DORIS_CLOUD_DEFER {
2418
13
        unregister_recycle_task(task_name);
2419
13
        int64_t cost =
2420
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2421
13
        metrics_context.finish_report();
2422
13
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
2423
13
                .tag("instance_id", instance_id_)
2424
13
                .tag("num_scanned", num_scanned)
2425
13
                .tag("num_expired", num_expired)
2426
13
                .tag("num_recycled", num_recycled)
2427
13
                .tag("num_recycled.prepare", num_prepare)
2428
13
                .tag("num_recycled.compacted", num_compacted)
2429
13
                .tag("num_recycled.empty_rowset", num_empty_rowset)
2430
13
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
2431
13
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
2432
13
                .tag("expired_rowset_meta_size", expired_rowset_size);
2433
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
2434
2435
13
    std::vector<std::string> rowset_keys;
2436
    // rowset_id -> rowset_meta
2437
    // store rowset id and meta for statistics rs size when delete
2438
13
    std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
2439
2440
    // Store keys of rowset recycled by background workers
2441
13
    std::mutex async_recycled_rowset_keys_mutex;
2442
13
    std::vector<std::string> async_recycled_rowset_keys;
2443
13
    auto worker_pool = std::make_unique<SimpleThreadPool>(
2444
13
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
2445
13
    worker_pool->start();
2446
13
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
2447
900
                                            int64_t tablet_id, const std::string& rowset_id) {
2448
        // Try to delete rowset data in background thread
2449
900
        int ret = worker_pool->submit_with_timeout(
2450
900
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
2451
780
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
2452
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2453
0
                        return;
2454
0
                    }
2455
780
                    std::vector<std::string> keys;
2456
780
                    {
2457
780
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
2458
780
                        async_recycled_rowset_keys.push_back(std::move(key));
2459
780
                        if (async_recycled_rowset_keys.size() > 100) {
2460
7
                            keys.swap(async_recycled_rowset_keys);
2461
7
                        }
2462
780
                    }
2463
780
                    if (keys.empty()) return;
2464
7
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
2465
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
2466
0
                                     << instance_id_;
2467
7
                    } else {
2468
7
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
2469
7
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
2470
7
                                           num_recycled, start_time);
2471
7
                    }
2472
7
                },
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
2450
780
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
2451
780
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
2452
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2453
0
                        return;
2454
0
                    }
2455
780
                    std::vector<std::string> keys;
2456
780
                    {
2457
780
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
2458
780
                        async_recycled_rowset_keys.push_back(std::move(key));
2459
780
                        if (async_recycled_rowset_keys.size() > 100) {
2460
7
                            keys.swap(async_recycled_rowset_keys);
2461
7
                        }
2462
780
                    }
2463
780
                    if (keys.empty()) return;
2464
7
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
2465
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
2466
0
                                     << instance_id_;
2467
7
                    } else {
2468
7
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
2469
7
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
2470
7
                                           num_recycled, start_time);
2471
7
                    }
2472
7
                },
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
2473
900
                0);
2474
900
        if (ret == 0) return 0;
2475
        // Submit task failed, delete rowset data in current thread
2476
120
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
2477
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2478
0
            return -1;
2479
0
        }
2480
120
        rowset_keys.push_back(std::move(key));
2481
120
        return 0;
2482
120
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
2447
900
                                            int64_t tablet_id, const std::string& rowset_id) {
2448
        // Try to delete rowset data in background thread
2449
900
        int ret = worker_pool->submit_with_timeout(
2450
900
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
2451
900
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
2452
900
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2453
900
                        return;
2454
900
                    }
2455
900
                    std::vector<std::string> keys;
2456
900
                    {
2457
900
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
2458
900
                        async_recycled_rowset_keys.push_back(std::move(key));
2459
900
                        if (async_recycled_rowset_keys.size() > 100) {
2460
900
                            keys.swap(async_recycled_rowset_keys);
2461
900
                        }
2462
900
                    }
2463
900
                    if (keys.empty()) return;
2464
900
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
2465
900
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
2466
900
                                     << instance_id_;
2467
900
                    } else {
2468
900
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
2469
900
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
2470
900
                                           num_recycled, start_time);
2471
900
                    }
2472
900
                },
2473
900
                0);
2474
900
        if (ret == 0) return 0;
2475
        // Submit task failed, delete rowset data in current thread
2476
120
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
2477
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2478
0
            return -1;
2479
0
        }
2480
120
        rowset_keys.push_back(std::move(key));
2481
120
        return 0;
2482
120
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
2483
2484
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2485
2486
4.00k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
2487
4.00k
        ++num_scanned;
2488
4.00k
        total_rowset_key_size += k.size();
2489
4.00k
        total_rowset_value_size += v.size();
2490
4.00k
        RecycleRowsetPB rowset;
2491
4.00k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
2492
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
2493
0
            return -1;
2494
0
        }
2495
2496
4.00k
        int64_t current_time = ::time(nullptr);
2497
4.00k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
2498
2499
4.00k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
2500
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
2501
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
2502
4.00k
        if (current_time < expiration) { // not expired
2503
0
            return 0;
2504
0
        }
2505
4.00k
        ++num_expired;
2506
4.00k
        expired_rowset_size += v.size();
2507
4.00k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
2508
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
2509
                // in old version, keep this key-value pair and it needs to be checked manually
2510
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
2511
0
                return -1;
2512
0
            }
2513
250
            if (rowset.resource_id().empty()) [[unlikely]] {
2514
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
2515
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
2516
0
                          << hex(k) << " value=" << proto_to_json(rowset);
2517
0
                rowset_keys.emplace_back(k);
2518
0
                return -1;
2519
0
            }
2520
            // decode rowset_id
2521
250
            auto k1 = k;
2522
250
            k1.remove_prefix(1);
2523
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2524
250
            decode_key(&k1, &out);
2525
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
2526
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
2527
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
2528
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
2529
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
2530
250
                                             rowset.tablet_id(), rowset_id) != 0) {
2531
0
                return -1;
2532
0
            }
2533
250
            return 0;
2534
250
        }
2535
        // TODO(plat1ko): check rowset not referenced
2536
3.75k
        auto rowset_meta = rowset.mutable_rowset_meta();
2537
3.75k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
2538
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
2539
0
                LOG_INFO("recycle rowset that has empty resource id");
2540
0
            } else {
2541
                // other situations, keep this key-value pair and it needs to be checked manually
2542
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
2543
0
                return -1;
2544
0
            }
2545
0
        }
2546
3.75k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
2547
3.75k
                  << " tablet_id=" << rowset_meta->tablet_id()
2548
3.75k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
2549
3.75k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
2550
3.75k
                  << "] txn_id=" << rowset_meta->txn_id()
2551
3.75k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
2552
3.75k
                  << " rowset_meta_size=" << v.size()
2553
3.75k
                  << " creation_time=" << rowset_meta->creation_time();
2554
3.75k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
2555
            // unable to calculate file path, can only be deleted by rowset id prefix
2556
650
            num_prepare += 1;
2557
650
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
2558
650
                                             rowset_meta->tablet_id(),
2559
650
                                             rowset_meta->rowset_id_v2()) != 0) {
2560
0
                return -1;
2561
0
            }
2562
3.10k
        } else {
2563
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
2564
3.10k
            rowset_keys.emplace_back(k);
2565
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
2566
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
2567
3.10k
                ++num_empty_rowset;
2568
3.10k
            }
2569
3.10k
        }
2570
3.75k
        return 0;
2571
3.75k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2486
4.00k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
2487
4.00k
        ++num_scanned;
2488
4.00k
        total_rowset_key_size += k.size();
2489
4.00k
        total_rowset_value_size += v.size();
2490
4.00k
        RecycleRowsetPB rowset;
2491
4.00k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
2492
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
2493
0
            return -1;
2494
0
        }
2495
2496
4.00k
        int64_t current_time = ::time(nullptr);
2497
4.00k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
2498
2499
4.00k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
2500
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
2501
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
2502
4.00k
        if (current_time < expiration) { // not expired
2503
0
            return 0;
2504
0
        }
2505
4.00k
        ++num_expired;
2506
4.00k
        expired_rowset_size += v.size();
2507
4.00k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
2508
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
2509
                // in old version, keep this key-value pair and it needs to be checked manually
2510
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
2511
0
                return -1;
2512
0
            }
2513
250
            if (rowset.resource_id().empty()) [[unlikely]] {
2514
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
2515
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
2516
0
                          << hex(k) << " value=" << proto_to_json(rowset);
2517
0
                rowset_keys.emplace_back(k);
2518
0
                return -1;
2519
0
            }
2520
            // decode rowset_id
2521
250
            auto k1 = k;
2522
250
            k1.remove_prefix(1);
2523
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2524
250
            decode_key(&k1, &out);
2525
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
2526
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
2527
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
2528
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
2529
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
2530
250
                                             rowset.tablet_id(), rowset_id) != 0) {
2531
0
                return -1;
2532
0
            }
2533
250
            return 0;
2534
250
        }
2535
        // TODO(plat1ko): check rowset not referenced
2536
3.75k
        auto rowset_meta = rowset.mutable_rowset_meta();
2537
3.75k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
2538
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
2539
0
                LOG_INFO("recycle rowset that has empty resource id");
2540
0
            } else {
2541
                // other situations, keep this key-value pair and it needs to be checked manually
2542
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
2543
0
                return -1;
2544
0
            }
2545
0
        }
2546
3.75k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
2547
3.75k
                  << " tablet_id=" << rowset_meta->tablet_id()
2548
3.75k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
2549
3.75k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
2550
3.75k
                  << "] txn_id=" << rowset_meta->txn_id()
2551
3.75k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
2552
3.75k
                  << " rowset_meta_size=" << v.size()
2553
3.75k
                  << " creation_time=" << rowset_meta->creation_time();
2554
3.75k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
2555
            // unable to calculate file path, can only be deleted by rowset id prefix
2556
650
            num_prepare += 1;
2557
650
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
2558
650
                                             rowset_meta->tablet_id(),
2559
650
                                             rowset_meta->rowset_id_v2()) != 0) {
2560
0
                return -1;
2561
0
            }
2562
3.10k
        } else {
2563
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
2564
3.10k
            rowset_keys.emplace_back(k);
2565
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
2566
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
2567
3.10k
                ++num_empty_rowset;
2568
3.10k
            }
2569
3.10k
        }
2570
3.75k
        return 0;
2571
3.75k
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
2572
2573
21
    auto loop_done = [&]() -> int {
2574
21
        std::vector<std::string> rowset_keys_to_delete;
2575
        // rowset_id -> rowset_meta
2576
        // store rowset id and meta for statistics rs size when delete
2577
21
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
2578
21
        rowset_keys_to_delete.swap(rowset_keys);
2579
21
        rowsets_to_delete.swap(rowsets);
2580
21
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
2581
21
                             rowsets_to_delete = std::move(rowsets_to_delete)]() {
2582
21
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
2583
21
                                   metrics_context) != 0) {
2584
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
2585
0
                return;
2586
0
            }
2587
21
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
2588
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2589
0
                return;
2590
0
            }
2591
21
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
2592
21
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
2581
21
                             rowsets_to_delete = std::move(rowsets_to_delete)]() {
2582
21
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
2583
21
                                   metrics_context) != 0) {
2584
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
2585
0
                return;
2586
0
            }
2587
21
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
2588
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2589
0
                return;
2590
0
            }
2591
21
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
2592
21
        });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENKUlvE_clEv
2593
21
        return 0;
2594
21
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
2573
21
    auto loop_done = [&]() -> int {
2574
21
        std::vector<std::string> rowset_keys_to_delete;
2575
        // rowset_id -> rowset_meta
2576
        // store rowset id and meta for statistics rs size when delete
2577
21
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
2578
21
        rowset_keys_to_delete.swap(rowset_keys);
2579
21
        rowsets_to_delete.swap(rowsets);
2580
21
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
2581
21
                             rowsets_to_delete = std::move(rowsets_to_delete)]() {
2582
21
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
2583
21
                                   metrics_context) != 0) {
2584
21
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
2585
21
                return;
2586
21
            }
2587
21
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
2588
21
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2589
21
                return;
2590
21
            }
2591
21
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
2592
21
        });
2593
21
        return 0;
2594
21
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
2595
2596
13
    if (config::enable_recycler_stats_metrics) {
2597
0
        scan_and_statistics_rowsets();
2598
0
    }
2599
    // recycle_func and loop_done for scan and recycle
2600
13
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
2601
13
                               std::move(loop_done));
2602
2603
13
    worker_pool->stop();
2604
2605
13
    if (!async_recycled_rowset_keys.empty()) {
2606
2
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
2607
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2608
0
            return -1;
2609
2
        } else {
2610
2
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
2611
2
        }
2612
2
    }
2613
13
    return ret;
2614
13
}
2615
2616
11
int InstanceRecycler::recycle_restore_jobs() {
2617
11
    const std::string task_name = "recycle_restore_jobs";
2618
11
    int64_t num_scanned = 0;
2619
11
    int64_t num_expired = 0;
2620
11
    int64_t num_recycled = 0;
2621
2622
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2623
2624
11
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
2625
11
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
2626
11
    std::string restore_job_key0;
2627
11
    std::string restore_job_key1;
2628
11
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
2629
11
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
2630
2631
11
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
2632
2633
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2634
11
    register_recycle_task(task_name, start_time);
2635
2636
11
    DORIS_CLOUD_DEFER {
2637
11
        unregister_recycle_task(task_name);
2638
11
        int64_t cost =
2639
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2640
11
        metrics_context.finish_report();
2641
11
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
2642
11
                .tag("instance_id", instance_id_)
2643
11
                .tag("num_scanned", num_scanned)
2644
11
                .tag("num_expired", num_expired)
2645
11
                .tag("num_recycled", num_recycled);
2646
11
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
2636
11
    DORIS_CLOUD_DEFER {
2637
11
        unregister_recycle_task(task_name);
2638
11
        int64_t cost =
2639
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2640
11
        metrics_context.finish_report();
2641
11
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
2642
11
                .tag("instance_id", instance_id_)
2643
11
                .tag("num_scanned", num_scanned)
2644
11
                .tag("num_expired", num_expired)
2645
11
                .tag("num_recycled", num_recycled);
2646
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
2647
2648
11
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2649
2650
11
    std::vector<std::string_view> restore_job_keys;
2651
20
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2652
20
        ++num_scanned;
2653
20
        RestoreJobCloudPB restore_job_pb;
2654
20
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
2655
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2656
0
            return -1;
2657
0
        }
2658
20
        int64_t expiration =
2659
20
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
2660
20
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
2661
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
2662
0
                   << " job expiration=" << restore_job_pb.expiration()
2663
0
                   << " creation_time=" << restore_job_pb.creation_time()
2664
0
                   << " state=" << restore_job_pb.state();
2665
20
        int64_t current_time = ::time(nullptr);
2666
20
        if (current_time < expiration) { // not expired
2667
0
            return 0;
2668
0
        }
2669
20
        ++num_expired;
2670
2671
20
        int64_t tablet_id = restore_job_pb.tablet_id();
2672
20
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
2673
20
                  << " restore_job_pb=" << restore_job_pb.DebugString();
2674
2675
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
2676
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
2677
2678
20
        std::unique_ptr<Transaction> txn;
2679
20
        std::string msg;
2680
20
        MetaServiceCode code = MetaServiceCode::OK;
2681
20
        if (code != MetaServiceCode::OK) {
2682
0
            LOG_WARNING("scan restore job rowsets failed when recycle restore jobs")
2683
0
                    .tag("tablet id", tablet_id)
2684
0
                    .tag("msg", msg)
2685
0
                    .tag("code", code)
2686
0
                    .tag("instance id", instance_id_);
2687
0
            return -1;
2688
0
        }
2689
2690
        // Recycle all data and KV associated with the tablet.
2691
        // This includes rowsets, segments, and related resources.
2692
20
        if (recycle_tablet(tablet_id, metrics_context) != 0) {
2693
0
            LOG_WARNING("failed to recycle tablet")
2694
0
                    .tag("tablet_id", tablet_id)
2695
0
                    .tag("instance_id", instance_id_);
2696
0
            return -1;
2697
20
        } else {
2698
            // Delete restore job rowsets kv only if tablet recycling succeeded
2699
            // to prevent data leak.
2700
20
            TxnErrorCode err = txn_kv_->create_txn(&txn);
2701
20
            if (err != TxnErrorCode::TXN_OK) {
2702
0
                LOG_WARNING("failed to recycle restore job")
2703
0
                        .tag("err", err)
2704
0
                        .tag("tablet id", tablet_id)
2705
0
                        .tag("instance_id", instance_id_)
2706
0
                        .tag("reason", "failed to create txn");
2707
0
                return -1;
2708
0
            }
2709
2710
            // delete all restore job rowset kv
2711
20
            txn->remove(restore_job_rs_key0, restore_job_rs_key1);
2712
2713
20
            err = txn->commit();
2714
20
            if (err != TxnErrorCode::TXN_OK) {
2715
0
                LOG_WARNING("failed to recycle tablet restore job rowset kv")
2716
0
                        .tag("err", err)
2717
0
                        .tag("tablet id", tablet_id)
2718
0
                        .tag("instance_id", instance_id_)
2719
0
                        .tag("reason", "failed to commit txn");
2720
0
                return -1;
2721
0
            }
2722
20
        }
2723
2724
20
        metrics_context.total_recycled_num = ++num_recycled;
2725
20
        metrics_context.report();
2726
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2727
20
        restore_job_keys.push_back(k);
2728
2729
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
2730
20
                  << " tablet_id=" << tablet_id;
2731
20
        return 0;
2732
20
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2651
20
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2652
20
        ++num_scanned;
2653
20
        RestoreJobCloudPB restore_job_pb;
2654
20
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
2655
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2656
0
            return -1;
2657
0
        }
2658
20
        int64_t expiration =
2659
20
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
2660
20
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
2661
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
2662
0
                   << " job expiration=" << restore_job_pb.expiration()
2663
0
                   << " creation_time=" << restore_job_pb.creation_time()
2664
0
                   << " state=" << restore_job_pb.state();
2665
20
        int64_t current_time = ::time(nullptr);
2666
20
        if (current_time < expiration) { // not expired
2667
0
            return 0;
2668
0
        }
2669
20
        ++num_expired;
2670
2671
20
        int64_t tablet_id = restore_job_pb.tablet_id();
2672
20
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
2673
20
                  << " restore_job_pb=" << restore_job_pb.DebugString();
2674
2675
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
2676
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
2677
2678
20
        std::unique_ptr<Transaction> txn;
2679
20
        std::string msg;
2680
20
        MetaServiceCode code = MetaServiceCode::OK;
2681
20
        if (code != MetaServiceCode::OK) {
2682
0
            LOG_WARNING("scan restore job rowsets failed when recycle restore jobs")
2683
0
                    .tag("tablet id", tablet_id)
2684
0
                    .tag("msg", msg)
2685
0
                    .tag("code", code)
2686
0
                    .tag("instance id", instance_id_);
2687
0
            return -1;
2688
0
        }
2689
2690
        // Recycle all data and KV associated with the tablet.
2691
        // This includes rowsets, segments, and related resources.
2692
20
        if (recycle_tablet(tablet_id, metrics_context) != 0) {
2693
0
            LOG_WARNING("failed to recycle tablet")
2694
0
                    .tag("tablet_id", tablet_id)
2695
0
                    .tag("instance_id", instance_id_);
2696
0
            return -1;
2697
20
        } else {
2698
            // Delete restore job rowsets kv only if tablet recycling succeeded
2699
            // to prevent data leak.
2700
20
            TxnErrorCode err = txn_kv_->create_txn(&txn);
2701
20
            if (err != TxnErrorCode::TXN_OK) {
2702
0
                LOG_WARNING("failed to recycle restore job")
2703
0
                        .tag("err", err)
2704
0
                        .tag("tablet id", tablet_id)
2705
0
                        .tag("instance_id", instance_id_)
2706
0
                        .tag("reason", "failed to create txn");
2707
0
                return -1;
2708
0
            }
2709
2710
            // delete all restore job rowset kv
2711
20
            txn->remove(restore_job_rs_key0, restore_job_rs_key1);
2712
2713
20
            err = txn->commit();
2714
20
            if (err != TxnErrorCode::TXN_OK) {
2715
0
                LOG_WARNING("failed to recycle tablet restore job rowset kv")
2716
0
                        .tag("err", err)
2717
0
                        .tag("tablet id", tablet_id)
2718
0
                        .tag("instance_id", instance_id_)
2719
0
                        .tag("reason", "failed to commit txn");
2720
0
                return -1;
2721
0
            }
2722
20
        }
2723
2724
20
        metrics_context.total_recycled_num = ++num_recycled;
2725
20
        metrics_context.report();
2726
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2727
20
        restore_job_keys.push_back(k);
2728
2729
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
2730
20
                  << " tablet_id=" << tablet_id;
2731
20
        return 0;
2732
20
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
2733
2734
11
    auto loop_done = [&restore_job_keys, this]() -> int {
2735
1
        if (restore_job_keys.empty()) return 0;
2736
1
        DORIS_CLOUD_DEFER {
2737
1
            restore_job_keys.clear();
2738
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2736
1
        DORIS_CLOUD_DEFER {
2737
1
            restore_job_keys.clear();
2738
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
2739
2740
1
        std::unique_ptr<Transaction> txn;
2741
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2742
1
        if (err != TxnErrorCode::TXN_OK) {
2743
0
            LOG_WARNING("failed to recycle restore job")
2744
0
                    .tag("err", err)
2745
0
                    .tag("instance_id", instance_id_)
2746
0
                    .tag("reason", "failed to create txn");
2747
0
            return -1;
2748
0
        }
2749
20
        for (auto& k : restore_job_keys) {
2750
20
            txn->remove(k);
2751
20
        }
2752
1
        err = txn->commit();
2753
1
        if (err != TxnErrorCode::TXN_OK) {
2754
0
            LOG_WARNING("failed to recycle restore job")
2755
0
                    .tag("err", err)
2756
0
                    .tag("instance_id", instance_id_)
2757
0
                    .tag("reason", "failed to commit txn");
2758
0
            return -1;
2759
0
        }
2760
1
        return 0;
2761
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
2734
1
    auto loop_done = [&restore_job_keys, this]() -> int {
2735
1
        if (restore_job_keys.empty()) return 0;
2736
1
        DORIS_CLOUD_DEFER {
2737
1
            restore_job_keys.clear();
2738
1
        };
2739
2740
1
        std::unique_ptr<Transaction> txn;
2741
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2742
1
        if (err != TxnErrorCode::TXN_OK) {
2743
0
            LOG_WARNING("failed to recycle restore job")
2744
0
                    .tag("err", err)
2745
0
                    .tag("instance_id", instance_id_)
2746
0
                    .tag("reason", "failed to create txn");
2747
0
            return -1;
2748
0
        }
2749
20
        for (auto& k : restore_job_keys) {
2750
20
            txn->remove(k);
2751
20
        }
2752
1
        err = txn->commit();
2753
1
        if (err != TxnErrorCode::TXN_OK) {
2754
0
            LOG_WARNING("failed to recycle restore job")
2755
0
                    .tag("err", err)
2756
0
                    .tag("instance_id", instance_id_)
2757
0
                    .tag("reason", "failed to commit txn");
2758
0
            return -1;
2759
0
        }
2760
1
        return 0;
2761
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
2762
2763
11
    if (config::enable_recycler_stats_metrics) {
2764
0
        scan_and_statistics_restore_jobs();
2765
0
    }
2766
2767
11
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
2768
11
                            std::move(loop_done));
2769
11
}
2770
2771
17
int InstanceRecycler::recycle_tmp_rowsets() {
2772
17
    const std::string task_name = "recycle_tmp_rowsets";
2773
17
    int64_t num_scanned = 0;
2774
17
    int64_t num_expired = 0;
2775
17
    int64_t num_recycled = 0;
2776
17
    size_t expired_rowset_size = 0;
2777
17
    size_t total_rowset_key_size = 0;
2778
17
    size_t total_rowset_value_size = 0;
2779
17
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2780
2781
17
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
2782
17
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
2783
17
    std::string tmp_rs_key0;
2784
17
    std::string tmp_rs_key1;
2785
17
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
2786
17
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
2787
2788
17
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
2789
2790
17
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2791
17
    register_recycle_task(task_name, start_time);
2792
2793
17
    DORIS_CLOUD_DEFER {
2794
17
        unregister_recycle_task(task_name);
2795
17
        int64_t cost =
2796
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2797
17
        metrics_context.finish_report();
2798
17
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
2799
17
                .tag("instance_id", instance_id_)
2800
17
                .tag("num_scanned", num_scanned)
2801
17
                .tag("num_expired", num_expired)
2802
17
                .tag("num_recycled", num_recycled)
2803
17
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
2804
17
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
2805
17
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
2806
17
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
2793
13
    DORIS_CLOUD_DEFER {
2794
13
        unregister_recycle_task(task_name);
2795
13
        int64_t cost =
2796
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2797
13
        metrics_context.finish_report();
2798
13
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
2799
13
                .tag("instance_id", instance_id_)
2800
13
                .tag("num_scanned", num_scanned)
2801
13
                .tag("num_expired", num_expired)
2802
13
                .tag("num_recycled", num_recycled)
2803
13
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
2804
13
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
2805
13
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
2806
13
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
2793
4
    DORIS_CLOUD_DEFER {
2794
4
        unregister_recycle_task(task_name);
2795
4
        int64_t cost =
2796
4
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2797
4
        metrics_context.finish_report();
2798
4
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
2799
4
                .tag("instance_id", instance_id_)
2800
4
                .tag("num_scanned", num_scanned)
2801
4
                .tag("num_expired", num_expired)
2802
4
                .tag("num_recycled", num_recycled)
2803
4
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
2804
4
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
2805
4
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
2806
4
    };
2807
2808
    // Elements in `tmp_rowset_keys` has the same lifetime as `it`
2809
17
    std::vector<std::string_view> tmp_rowset_keys;
2810
    // rowset_id -> rowset_meta
2811
    // store tmp_rowset id and meta for statistics rs size when delete
2812
17
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
2813
2814
17
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2815
2816
17
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &tmp_rowsets,
2817
17
                             &expired_rowset_size, &total_rowset_key_size, &total_rowset_value_size,
2818
3.05k
                             &earlest_ts, this](std::string_view k, std::string_view v) -> int {
2819
3.05k
        ++num_scanned;
2820
3.05k
        total_rowset_key_size += k.size();
2821
3.05k
        total_rowset_value_size += v.size();
2822
3.05k
        doris::RowsetMetaCloudPB rowset;
2823
3.05k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
2824
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
2825
0
            return -1;
2826
0
        }
2827
3.05k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
2828
3.05k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
2829
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
2830
0
                   << " txn_expiration=" << rowset.txn_expiration()
2831
0
                   << " rowset_creation_time=" << rowset.creation_time();
2832
3.05k
        int64_t current_time = ::time(nullptr);
2833
3.05k
        if (current_time < expiration) { // not expired
2834
0
            return 0;
2835
0
        }
2836
2837
3.05k
        DCHECK_GT(rowset.txn_id(), 0)
2838
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
2839
3.05k
        if (!is_txn_finished(txn_kv_, instance_id_, rowset.txn_id())) {
2840
10
            LOG(INFO) << "txn is not finished, skip recycle tmp rowset, instance_id="
2841
10
                      << instance_id_ << " tablet_id=" << rowset.tablet_id()
2842
10
                      << " rowset_id=" << rowset.rowset_id_v2() << " version=["
2843
10
                      << rowset.start_version() << '-' << rowset.end_version()
2844
10
                      << "] txn_id=" << rowset.txn_id()
2845
10
                      << " creation_time=" << rowset.creation_time() << " expiration=" << expiration
2846
10
                      << " txn_expiration=" << rowset.txn_expiration();
2847
10
            return 0;
2848
10
        }
2849
2850
3.04k
        ++num_expired;
2851
3.04k
        expired_rowset_size += v.size();
2852
3.04k
        if (!rowset.has_resource_id()) {
2853
20
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
2854
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
2855
0
                return -1;
2856
0
            }
2857
            // might be a delete pred rowset
2858
20
            tmp_rowset_keys.push_back(k);
2859
20
            return 0;
2860
20
        }
2861
        // TODO(plat1ko): check rowset not referenced
2862
3.02k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
2863
3.02k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
2864
3.02k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
2865
3.02k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
2866
3.02k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
2867
3.02k
                  << " num_expired=" << num_expired;
2868
2869
3.02k
        tmp_rowset_keys.push_back(k);
2870
3.02k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
2871
3.02k
        return 0;
2872
3.04k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2818
3.02k
                             &earlest_ts, this](std::string_view k, std::string_view v) -> int {
2819
3.02k
        ++num_scanned;
2820
3.02k
        total_rowset_key_size += k.size();
2821
3.02k
        total_rowset_value_size += v.size();
2822
3.02k
        doris::RowsetMetaCloudPB rowset;
2823
3.02k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
2824
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
2825
0
            return -1;
2826
0
        }
2827
3.02k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
2828
3.02k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
2829
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
2830
0
                   << " txn_expiration=" << rowset.txn_expiration()
2831
0
                   << " rowset_creation_time=" << rowset.creation_time();
2832
3.02k
        int64_t current_time = ::time(nullptr);
2833
3.02k
        if (current_time < expiration) { // not expired
2834
0
            return 0;
2835
0
        }
2836
2837
3.02k
        DCHECK_GT(rowset.txn_id(), 0)
2838
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
2839
3.02k
        if (!is_txn_finished(txn_kv_, instance_id_, rowset.txn_id())) {
2840
0
            LOG(INFO) << "txn is not finished, skip recycle tmp rowset, instance_id="
2841
0
                      << instance_id_ << " tablet_id=" << rowset.tablet_id()
2842
0
                      << " rowset_id=" << rowset.rowset_id_v2() << " version=["
2843
0
                      << rowset.start_version() << '-' << rowset.end_version()
2844
0
                      << "] txn_id=" << rowset.txn_id()
2845
0
                      << " creation_time=" << rowset.creation_time() << " expiration=" << expiration
2846
0
                      << " txn_expiration=" << rowset.txn_expiration();
2847
0
            return 0;
2848
0
        }
2849
2850
3.02k
        ++num_expired;
2851
3.02k
        expired_rowset_size += v.size();
2852
3.02k
        if (!rowset.has_resource_id()) {
2853
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
2854
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
2855
0
                return -1;
2856
0
            }
2857
            // might be a delete pred rowset
2858
0
            tmp_rowset_keys.push_back(k);
2859
0
            return 0;
2860
0
        }
2861
        // TODO(plat1ko): check rowset not referenced
2862
3.02k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
2863
3.02k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
2864
3.02k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
2865
3.02k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
2866
3.02k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
2867
3.02k
                  << " num_expired=" << num_expired;
2868
2869
3.02k
        tmp_rowset_keys.push_back(k);
2870
3.02k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
2871
3.02k
        return 0;
2872
3.02k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2818
30
                             &earlest_ts, this](std::string_view k, std::string_view v) -> int {
2819
30
        ++num_scanned;
2820
30
        total_rowset_key_size += k.size();
2821
30
        total_rowset_value_size += v.size();
2822
30
        doris::RowsetMetaCloudPB rowset;
2823
30
        if (!rowset.ParseFromArray(v.data(), v.size())) {
2824
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
2825
0
            return -1;
2826
0
        }
2827
30
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
2828
30
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
2829
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
2830
0
                   << " txn_expiration=" << rowset.txn_expiration()
2831
0
                   << " rowset_creation_time=" << rowset.creation_time();
2832
30
        int64_t current_time = ::time(nullptr);
2833
30
        if (current_time < expiration) { // not expired
2834
0
            return 0;
2835
0
        }
2836
2837
30
        DCHECK_GT(rowset.txn_id(), 0)
2838
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
2839
30
        if (!is_txn_finished(txn_kv_, instance_id_, rowset.txn_id())) {
2840
10
            LOG(INFO) << "txn is not finished, skip recycle tmp rowset, instance_id="
2841
10
                      << instance_id_ << " tablet_id=" << rowset.tablet_id()
2842
10
                      << " rowset_id=" << rowset.rowset_id_v2() << " version=["
2843
10
                      << rowset.start_version() << '-' << rowset.end_version()
2844
10
                      << "] txn_id=" << rowset.txn_id()
2845
10
                      << " creation_time=" << rowset.creation_time() << " expiration=" << expiration
2846
10
                      << " txn_expiration=" << rowset.txn_expiration();
2847
10
            return 0;
2848
10
        }
2849
2850
20
        ++num_expired;
2851
20
        expired_rowset_size += v.size();
2852
20
        if (!rowset.has_resource_id()) {
2853
20
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
2854
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
2855
0
                return -1;
2856
0
            }
2857
            // might be a delete pred rowset
2858
20
            tmp_rowset_keys.push_back(k);
2859
20
            return 0;
2860
20
        }
2861
        // TODO(plat1ko): check rowset not referenced
2862
0
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
2863
0
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
2864
0
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
2865
0
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
2866
0
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
2867
0
                  << " num_expired=" << num_expired;
2868
2869
0
        tmp_rowset_keys.push_back(k);
2870
0
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
2871
0
        return 0;
2872
20
    };
2873
2874
17
    auto loop_done = [&tmp_rowset_keys, &tmp_rowsets, &num_recycled, &metrics_context,
2875
17
                      this]() -> int {
2876
6
        DORIS_CLOUD_DEFER {
2877
6
            tmp_rowset_keys.clear();
2878
6
            tmp_rowsets.clear();
2879
6
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2876
3
        DORIS_CLOUD_DEFER {
2877
3
            tmp_rowset_keys.clear();
2878
3
            tmp_rowsets.clear();
2879
3
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2876
3
        DORIS_CLOUD_DEFER {
2877
3
            tmp_rowset_keys.clear();
2878
3
            tmp_rowsets.clear();
2879
3
        };
2880
6
        if (delete_rowset_data(tmp_rowsets, RowsetRecyclingState::TMP_ROWSET, metrics_context) !=
2881
6
            0) {
2882
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2883
0
            return -1;
2884
0
        }
2885
6
        if (txn_remove(txn_kv_.get(), tmp_rowset_keys) != 0) {
2886
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2887
0
            return -1;
2888
0
        }
2889
6
        num_recycled += tmp_rowset_keys.size();
2890
6
        return 0;
2891
6
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
2875
3
                      this]() -> int {
2876
3
        DORIS_CLOUD_DEFER {
2877
3
            tmp_rowset_keys.clear();
2878
3
            tmp_rowsets.clear();
2879
3
        };
2880
3
        if (delete_rowset_data(tmp_rowsets, RowsetRecyclingState::TMP_ROWSET, metrics_context) !=
2881
3
            0) {
2882
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2883
0
            return -1;
2884
0
        }
2885
3
        if (txn_remove(txn_kv_.get(), tmp_rowset_keys) != 0) {
2886
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2887
0
            return -1;
2888
0
        }
2889
3
        num_recycled += tmp_rowset_keys.size();
2890
3
        return 0;
2891
3
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
2875
3
                      this]() -> int {
2876
3
        DORIS_CLOUD_DEFER {
2877
3
            tmp_rowset_keys.clear();
2878
3
            tmp_rowsets.clear();
2879
3
        };
2880
3
        if (delete_rowset_data(tmp_rowsets, RowsetRecyclingState::TMP_ROWSET, metrics_context) !=
2881
3
            0) {
2882
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2883
0
            return -1;
2884
0
        }
2885
3
        if (txn_remove(txn_kv_.get(), tmp_rowset_keys) != 0) {
2886
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2887
0
            return -1;
2888
0
        }
2889
3
        num_recycled += tmp_rowset_keys.size();
2890
3
        return 0;
2891
3
    };
2892
2893
17
    if (config::enable_recycler_stats_metrics) {
2894
0
        scan_and_statistics_tmp_rowsets();
2895
0
    }
2896
    // recycle_func and loop_done for scan and recycle
2897
17
    return scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
2898
17
                            std::move(loop_done));
2899
17
}
2900
2901
int InstanceRecycler::scan_and_recycle(
2902
        std::string begin, std::string_view end,
2903
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
2904
190
        std::function<int()> loop_done) {
2905
190
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
2906
190
    int ret = 0;
2907
190
    int64_t cnt = 0;
2908
190
    int get_range_retried = 0;
2909
190
    std::string err;
2910
190
    DORIS_CLOUD_DEFER_COPY(begin, end) {
2911
190
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
2912
190
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
2913
190
                  << " ret=" << ret << " err=" << err;
2914
190
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
2910
171
    DORIS_CLOUD_DEFER_COPY(begin, end) {
2911
171
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
2912
171
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
2913
171
                  << " ret=" << ret << " err=" << err;
2914
171
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
2910
19
    DORIS_CLOUD_DEFER_COPY(begin, end) {
2911
19
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
2912
19
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
2913
19
                  << " ret=" << ret << " err=" << err;
2914
19
    };
2915
2916
190
    std::unique_ptr<RangeGetIterator> it;
2917
213
    do {
2918
213
        if (get_range_retried > 1000) {
2919
0
            err = "txn_get exceeds max retry, may not scan all keys";
2920
0
            ret = -1;
2921
0
            return -1;
2922
0
        }
2923
213
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
2924
213
        if (get_ret != 0) { // txn kv may complain "Request for future version"
2925
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
2926
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
2927
0
                         << " get_range_retried=" << get_range_retried;
2928
0
            ++get_range_retried;
2929
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
2930
0
            continue; // try again
2931
0
        }
2932
213
        if (!it->has_next()) {
2933
105
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
2934
105
            break; // scan finished
2935
105
        }
2936
37.5k
        while (it->has_next()) {
2937
37.3k
            ++cnt;
2938
            // recycle corresponding resources
2939
37.3k
            auto [k, v] = it->next();
2940
37.3k
            if (!it->has_next()) {
2941
108
                begin = k;
2942
108
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
2943
108
            }
2944
            // if we want to continue scanning, the recycle_func should not return non-zero
2945
37.3k
            if (recycle_func(k, v) != 0) {
2946
22
                err = "recycle_func error";
2947
22
                ret = -1;
2948
22
            }
2949
37.3k
        }
2950
108
        begin.push_back('\x00'); // Update to next smallest key for iteration
2951
        // if we want to continue scanning, the recycle_func should not return non-zero
2952
108
        if (loop_done && loop_done() != 0) {
2953
2
            err = "loop_done error";
2954
2
            ret = -1;
2955
2
        }
2956
108
    } while (it->more() && !stopped());
2957
190
    return ret;
2958
190
}
2959
2960
20
int InstanceRecycler::abort_timeout_txn() {
2961
20
    const std::string task_name = "abort_timeout_txn";
2962
20
    int64_t num_scanned = 0;
2963
20
    int64_t num_timeout = 0;
2964
20
    int64_t num_abort = 0;
2965
20
    int64_t num_advance = 0;
2966
20
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2967
2968
20
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
2969
20
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
2970
20
    std::string begin_txn_running_key;
2971
20
    std::string end_txn_running_key;
2972
20
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
2973
20
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
2974
2975
20
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
2976
2977
20
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2978
20
    register_recycle_task(task_name, start_time);
2979
2980
20
    DORIS_CLOUD_DEFER {
2981
20
        unregister_recycle_task(task_name);
2982
20
        int64_t cost =
2983
20
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2984
20
        metrics_context.finish_report();
2985
20
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
2986
20
                .tag("instance_id", instance_id_)
2987
20
                .tag("num_scanned", num_scanned)
2988
20
                .tag("num_timeout", num_timeout)
2989
20
                .tag("num_abort", num_abort)
2990
20
                .tag("num_advance", num_advance);
2991
20
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
2980
16
    DORIS_CLOUD_DEFER {
2981
16
        unregister_recycle_task(task_name);
2982
16
        int64_t cost =
2983
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2984
16
        metrics_context.finish_report();
2985
16
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
2986
16
                .tag("instance_id", instance_id_)
2987
16
                .tag("num_scanned", num_scanned)
2988
16
                .tag("num_timeout", num_timeout)
2989
16
                .tag("num_abort", num_abort)
2990
16
                .tag("num_advance", num_advance);
2991
16
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
2980
4
    DORIS_CLOUD_DEFER {
2981
4
        unregister_recycle_task(task_name);
2982
4
        int64_t cost =
2983
4
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2984
4
        metrics_context.finish_report();
2985
4
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
2986
4
                .tag("instance_id", instance_id_)
2987
4
                .tag("num_scanned", num_scanned)
2988
4
                .tag("num_timeout", num_timeout)
2989
4
                .tag("num_abort", num_abort)
2990
4
                .tag("num_advance", num_advance);
2991
4
    };
2992
2993
20
    int64_t current_time =
2994
20
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
2995
2996
20
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
2997
20
                                  &current_time, &metrics_context,
2998
20
                                  this](std::string_view k, std::string_view v) -> int {
2999
10
        ++num_scanned;
3000
3001
10
        std::unique_ptr<Transaction> txn;
3002
10
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3003
10
        if (err != TxnErrorCode::TXN_OK) {
3004
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
3005
0
            return -1;
3006
0
        }
3007
10
        std::string_view k1 = k;
3008
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
3009
10
        k1.remove_prefix(1); // Remove key space
3010
10
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3011
10
        if (decode_key(&k1, &out) != 0) {
3012
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
3013
0
            return -1;
3014
0
        }
3015
10
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
3016
10
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
3017
10
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
3018
        // Update txn_info
3019
10
        std::string txn_inf_key, txn_inf_val;
3020
10
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
3021
10
        err = txn->get(txn_inf_key, &txn_inf_val);
3022
10
        if (err != TxnErrorCode::TXN_OK) {
3023
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
3024
0
            return -1;
3025
0
        }
3026
10
        TxnInfoPB txn_info;
3027
10
        if (!txn_info.ParseFromString(txn_inf_val)) {
3028
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
3029
0
            return -1;
3030
0
        }
3031
3032
10
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
3033
4
            txn.reset();
3034
4
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
3035
4
            std::shared_ptr<TxnLazyCommitTask> task =
3036
4
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
3037
4
            std::pair<MetaServiceCode, std::string> ret = task->wait();
3038
4
            if (ret.first != MetaServiceCode::OK) {
3039
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
3040
0
                             << "msg=" << ret.second;
3041
0
                return -1;
3042
0
            }
3043
4
            ++num_advance;
3044
4
            return 0;
3045
6
        } else {
3046
6
            TxnRunningPB txn_running_pb;
3047
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
3048
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
3049
0
                return -1;
3050
0
            }
3051
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
3052
4
                return 0;
3053
4
            }
3054
2
            ++num_timeout;
3055
3056
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
3057
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
3058
2
            txn_info.set_finish_time(current_time);
3059
2
            txn_info.set_reason("timeout");
3060
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
3061
2
            txn_inf_val.clear();
3062
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
3063
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
3064
0
                return -1;
3065
0
            }
3066
2
            txn->put(txn_inf_key, txn_inf_val);
3067
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
3068
            // Put recycle txn key
3069
2
            std::string recyc_txn_key, recyc_txn_val;
3070
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
3071
2
            RecycleTxnPB recycle_txn_pb;
3072
2
            recycle_txn_pb.set_creation_time(current_time);
3073
2
            recycle_txn_pb.set_label(txn_info.label());
3074
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
3075
0
                LOG_WARNING("failed to serialize txn recycle info")
3076
0
                        .tag("key", hex(k))
3077
0
                        .tag("db_id", db_id)
3078
0
                        .tag("txn_id", txn_id);
3079
0
                return -1;
3080
0
            }
3081
2
            txn->put(recyc_txn_key, recyc_txn_val);
3082
            // Remove txn running key
3083
2
            txn->remove(k);
3084
2
            err = txn->commit();
3085
2
            if (err != TxnErrorCode::TXN_OK) {
3086
0
                LOG_WARNING("failed to commit txn err={}", err)
3087
0
                        .tag("key", hex(k))
3088
0
                        .tag("db_id", db_id)
3089
0
                        .tag("txn_id", txn_id);
3090
0
                return -1;
3091
0
            }
3092
2
            metrics_context.total_recycled_num = ++num_abort;
3093
2
            metrics_context.report();
3094
2
        }
3095
3096
2
        return 0;
3097
10
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2998
6
                                  this](std::string_view k, std::string_view v) -> int {
2999
6
        ++num_scanned;
3000
3001
6
        std::unique_ptr<Transaction> txn;
3002
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3003
6
        if (err != TxnErrorCode::TXN_OK) {
3004
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
3005
0
            return -1;
3006
0
        }
3007
6
        std::string_view k1 = k;
3008
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
3009
6
        k1.remove_prefix(1); // Remove key space
3010
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3011
6
        if (decode_key(&k1, &out) != 0) {
3012
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
3013
0
            return -1;
3014
0
        }
3015
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
3016
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
3017
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
3018
        // Update txn_info
3019
6
        std::string txn_inf_key, txn_inf_val;
3020
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
3021
6
        err = txn->get(txn_inf_key, &txn_inf_val);
3022
6
        if (err != TxnErrorCode::TXN_OK) {
3023
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
3024
0
            return -1;
3025
0
        }
3026
6
        TxnInfoPB txn_info;
3027
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
3028
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
3029
0
            return -1;
3030
0
        }
3031
3032
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
3033
0
            txn.reset();
3034
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
3035
0
            std::shared_ptr<TxnLazyCommitTask> task =
3036
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
3037
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
3038
0
            if (ret.first != MetaServiceCode::OK) {
3039
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
3040
0
                             << "msg=" << ret.second;
3041
0
                return -1;
3042
0
            }
3043
0
            ++num_advance;
3044
0
            return 0;
3045
6
        } else {
3046
6
            TxnRunningPB txn_running_pb;
3047
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
3048
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
3049
0
                return -1;
3050
0
            }
3051
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
3052
4
                return 0;
3053
4
            }
3054
2
            ++num_timeout;
3055
3056
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
3057
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
3058
2
            txn_info.set_finish_time(current_time);
3059
2
            txn_info.set_reason("timeout");
3060
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
3061
2
            txn_inf_val.clear();
3062
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
3063
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
3064
0
                return -1;
3065
0
            }
3066
2
            txn->put(txn_inf_key, txn_inf_val);
3067
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
3068
            // Put recycle txn key
3069
2
            std::string recyc_txn_key, recyc_txn_val;
3070
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
3071
2
            RecycleTxnPB recycle_txn_pb;
3072
2
            recycle_txn_pb.set_creation_time(current_time);
3073
2
            recycle_txn_pb.set_label(txn_info.label());
3074
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
3075
0
                LOG_WARNING("failed to serialize txn recycle info")
3076
0
                        .tag("key", hex(k))
3077
0
                        .tag("db_id", db_id)
3078
0
                        .tag("txn_id", txn_id);
3079
0
                return -1;
3080
0
            }
3081
2
            txn->put(recyc_txn_key, recyc_txn_val);
3082
            // Remove txn running key
3083
2
            txn->remove(k);
3084
2
            err = txn->commit();
3085
2
            if (err != TxnErrorCode::TXN_OK) {
3086
0
                LOG_WARNING("failed to commit txn err={}", err)
3087
0
                        .tag("key", hex(k))
3088
0
                        .tag("db_id", db_id)
3089
0
                        .tag("txn_id", txn_id);
3090
0
                return -1;
3091
0
            }
3092
2
            metrics_context.total_recycled_num = ++num_abort;
3093
2
            metrics_context.report();
3094
2
        }
3095
3096
2
        return 0;
3097
6
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2998
4
                                  this](std::string_view k, std::string_view v) -> int {
2999
4
        ++num_scanned;
3000
3001
4
        std::unique_ptr<Transaction> txn;
3002
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3003
4
        if (err != TxnErrorCode::TXN_OK) {
3004
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
3005
0
            return -1;
3006
0
        }
3007
4
        std::string_view k1 = k;
3008
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
3009
4
        k1.remove_prefix(1); // Remove key space
3010
4
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3011
4
        if (decode_key(&k1, &out) != 0) {
3012
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
3013
0
            return -1;
3014
0
        }
3015
4
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
3016
4
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
3017
4
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
3018
        // Update txn_info
3019
4
        std::string txn_inf_key, txn_inf_val;
3020
4
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
3021
4
        err = txn->get(txn_inf_key, &txn_inf_val);
3022
4
        if (err != TxnErrorCode::TXN_OK) {
3023
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
3024
0
            return -1;
3025
0
        }
3026
4
        TxnInfoPB txn_info;
3027
4
        if (!txn_info.ParseFromString(txn_inf_val)) {
3028
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
3029
0
            return -1;
3030
0
        }
3031
3032
4
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
3033
4
            txn.reset();
3034
4
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
3035
4
            std::shared_ptr<TxnLazyCommitTask> task =
3036
4
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
3037
4
            std::pair<MetaServiceCode, std::string> ret = task->wait();
3038
4
            if (ret.first != MetaServiceCode::OK) {
3039
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
3040
0
                             << "msg=" << ret.second;
3041
0
                return -1;
3042
0
            }
3043
4
            ++num_advance;
3044
4
            return 0;
3045
4
        } else {
3046
0
            TxnRunningPB txn_running_pb;
3047
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
3048
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
3049
0
                return -1;
3050
0
            }
3051
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
3052
0
                return 0;
3053
0
            }
3054
0
            ++num_timeout;
3055
3056
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
3057
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
3058
0
            txn_info.set_finish_time(current_time);
3059
0
            txn_info.set_reason("timeout");
3060
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
3061
0
            txn_inf_val.clear();
3062
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
3063
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
3064
0
                return -1;
3065
0
            }
3066
0
            txn->put(txn_inf_key, txn_inf_val);
3067
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
3068
            // Put recycle txn key
3069
0
            std::string recyc_txn_key, recyc_txn_val;
3070
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
3071
0
            RecycleTxnPB recycle_txn_pb;
3072
0
            recycle_txn_pb.set_creation_time(current_time);
3073
0
            recycle_txn_pb.set_label(txn_info.label());
3074
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
3075
0
                LOG_WARNING("failed to serialize txn recycle info")
3076
0
                        .tag("key", hex(k))
3077
0
                        .tag("db_id", db_id)
3078
0
                        .tag("txn_id", txn_id);
3079
0
                return -1;
3080
0
            }
3081
0
            txn->put(recyc_txn_key, recyc_txn_val);
3082
            // Remove txn running key
3083
0
            txn->remove(k);
3084
0
            err = txn->commit();
3085
0
            if (err != TxnErrorCode::TXN_OK) {
3086
0
                LOG_WARNING("failed to commit txn err={}", err)
3087
0
                        .tag("key", hex(k))
3088
0
                        .tag("db_id", db_id)
3089
0
                        .tag("txn_id", txn_id);
3090
0
                return -1;
3091
0
            }
3092
0
            metrics_context.total_recycled_num = ++num_abort;
3093
0
            metrics_context.report();
3094
0
        }
3095
3096
0
        return 0;
3097
4
    };
3098
3099
20
    if (config::enable_recycler_stats_metrics) {
3100
0
        scan_and_statistics_abort_timeout_txn();
3101
0
    }
3102
    // recycle_func and loop_done for scan and recycle
3103
20
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
3104
20
                            std::move(handle_txn_running_kv));
3105
20
}
3106
3107
19
int InstanceRecycler::recycle_expired_txn_label() {
3108
19
    const std::string task_name = "recycle_expired_txn_label";
3109
19
    int64_t num_scanned = 0;
3110
19
    int64_t num_expired = 0;
3111
19
    int64_t num_recycled = 0;
3112
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
3113
19
    int ret = 0;
3114
3115
19
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
3116
19
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
3117
19
    std::string begin_recycle_txn_key;
3118
19
    std::string end_recycle_txn_key;
3119
19
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
3120
19
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
3121
19
    std::vector<std::string> recycle_txn_info_keys;
3122
3123
19
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
3124
3125
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
3126
19
    register_recycle_task(task_name, start_time);
3127
19
    DORIS_CLOUD_DEFER {
3128
19
        unregister_recycle_task(task_name);
3129
19
        int64_t cost =
3130
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3131
19
        metrics_context.finish_report();
3132
19
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
3133
19
                .tag("instance_id", instance_id_)
3134
19
                .tag("num_scanned", num_scanned)
3135
19
                .tag("num_expired", num_expired)
3136
19
                .tag("num_recycled", num_recycled);
3137
19
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
3127
16
    DORIS_CLOUD_DEFER {
3128
16
        unregister_recycle_task(task_name);
3129
16
        int64_t cost =
3130
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3131
16
        metrics_context.finish_report();
3132
16
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
3133
16
                .tag("instance_id", instance_id_)
3134
16
                .tag("num_scanned", num_scanned)
3135
16
                .tag("num_expired", num_expired)
3136
16
                .tag("num_recycled", num_recycled);
3137
16
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
3127
3
    DORIS_CLOUD_DEFER {
3128
3
        unregister_recycle_task(task_name);
3129
3
        int64_t cost =
3130
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3131
3
        metrics_context.finish_report();
3132
3
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
3133
3
                .tag("instance_id", instance_id_)
3134
3
                .tag("num_scanned", num_scanned)
3135
3
                .tag("num_expired", num_expired)
3136
3
                .tag("num_recycled", num_recycled);
3137
3
    };
3138
3139
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
3140
3141
19
    SyncExecutor<int> concurrent_delete_executor(
3142
19
            _thread_pool_group.s3_producer_pool,
3143
19
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
3144
23.0k
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
3144
23.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
3144
3
            [](const int& ret) { return ret != 0; });
3145
3146
19
    int64_t current_time_ms =
3147
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
3148
3149
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
3150
30.0k
        ++num_scanned;
3151
30.0k
        RecycleTxnPB recycle_txn_pb;
3152
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
3153
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
3154
0
            return -1;
3155
0
        }
3156
30.0k
        if ((config::force_immediate_recycle) ||
3157
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
3158
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
3159
30.0k
             current_time_ms)) {
3160
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
3161
23.0k
            num_expired++;
3162
23.0k
            recycle_txn_info_keys.emplace_back(k);
3163
23.0k
        }
3164
30.0k
        return 0;
3165
30.0k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3149
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
3150
30.0k
        ++num_scanned;
3151
30.0k
        RecycleTxnPB recycle_txn_pb;
3152
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
3153
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
3154
0
            return -1;
3155
0
        }
3156
30.0k
        if ((config::force_immediate_recycle) ||
3157
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
3158
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
3159
30.0k
             current_time_ms)) {
3160
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
3161
23.0k
            num_expired++;
3162
23.0k
            recycle_txn_info_keys.emplace_back(k);
3163
23.0k
        }
3164
30.0k
        return 0;
3165
30.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3149
3
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
3150
3
        ++num_scanned;
3151
3
        RecycleTxnPB recycle_txn_pb;
3152
3
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
3153
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
3154
0
            return -1;
3155
0
        }
3156
3
        if ((config::force_immediate_recycle) ||
3157
3
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
3158
3
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
3159
3
             current_time_ms)) {
3160
3
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
3161
3
            num_expired++;
3162
3
            recycle_txn_info_keys.emplace_back(k);
3163
3
        }
3164
3
        return 0;
3165
3
    };
3166
3167
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
3168
23.0k
        std::string_view k1 = k;
3169
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
3170
23.0k
        k1.remove_prefix(1); // Remove key space
3171
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3172
23.0k
        int ret = decode_key(&k1, &out);
3173
23.0k
        if (ret != 0) {
3174
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
3175
0
            return -1;
3176
0
        }
3177
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
3178
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
3179
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
3180
23.0k
        std::unique_ptr<Transaction> txn;
3181
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3182
23.0k
        if (err != TxnErrorCode::TXN_OK) {
3183
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
3184
0
            return -1;
3185
0
        }
3186
        // Remove txn index kv
3187
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
3188
23.0k
        txn->remove(index_key);
3189
        // Remove txn info kv
3190
23.0k
        std::string info_key, info_val;
3191
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
3192
23.0k
        err = txn->get(info_key, &info_val);
3193
23.0k
        if (err != TxnErrorCode::TXN_OK) {
3194
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
3195
0
            return -1;
3196
0
        }
3197
23.0k
        TxnInfoPB txn_info;
3198
23.0k
        if (!txn_info.ParseFromString(info_val)) {
3199
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
3200
0
            return -1;
3201
0
        }
3202
23.0k
        txn->remove(info_key);
3203
        // Remove sub txn index kvs
3204
23.0k
        std::vector<std::string> sub_txn_index_keys;
3205
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
3206
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
3207
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
3208
22.9k
        }
3209
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
3210
22.9k
            txn->remove(sub_txn_index_key);
3211
22.9k
        }
3212
        // Update txn label
3213
23.0k
        std::string label_key, label_val;
3214
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
3215
23.0k
        err = txn->get(label_key, &label_val);
3216
23.0k
        if (err != TxnErrorCode::TXN_OK) {
3217
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
3218
0
                         << " err=" << err;
3219
0
            return -1;
3220
0
        }
3221
23.0k
        TxnLabelPB txn_label;
3222
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
3223
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
3224
0
            return -1;
3225
0
        }
3226
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
3227
23.0k
        if (it != txn_label.txn_ids().end()) {
3228
23.0k
            txn_label.mutable_txn_ids()->erase(it);
3229
23.0k
        }
3230
23.0k
        if (txn_label.txn_ids().empty()) {
3231
23.0k
            txn->remove(label_key);
3232
23.0k
        } else {
3233
0
            if (!txn_label.SerializeToString(&label_val)) {
3234
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
3235
0
                return -1;
3236
0
            }
3237
0
            txn->atomic_set_ver_value(label_key, label_val);
3238
0
        }
3239
        // Remove recycle txn kv
3240
23.0k
        txn->remove(k);
3241
23.0k
        err = txn->commit();
3242
23.0k
        if (err != TxnErrorCode::TXN_OK) {
3243
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
3244
0
            return -1;
3245
0
        }
3246
23.0k
        metrics_context.total_recycled_num = ++num_recycled;
3247
23.0k
        metrics_context.report();
3248
3249
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
3250
23.0k
        return 0;
3251
23.0k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
3167
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
3168
23.0k
        std::string_view k1 = k;
3169
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
3170
23.0k
        k1.remove_prefix(1); // Remove key space
3171
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3172
23.0k
        int ret = decode_key(&k1, &out);
3173
23.0k
        if (ret != 0) {
3174
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
3175
0
            return -1;
3176
0
        }
3177
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
3178
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
3179
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
3180
23.0k
        std::unique_ptr<Transaction> txn;
3181
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3182
23.0k
        if (err != TxnErrorCode::TXN_OK) {
3183
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
3184
0
            return -1;
3185
0
        }
3186
        // Remove txn index kv
3187
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
3188
23.0k
        txn->remove(index_key);
3189
        // Remove txn info kv
3190
23.0k
        std::string info_key, info_val;
3191
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
3192
23.0k
        err = txn->get(info_key, &info_val);
3193
23.0k
        if (err != TxnErrorCode::TXN_OK) {
3194
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
3195
0
            return -1;
3196
0
        }
3197
23.0k
        TxnInfoPB txn_info;
3198
23.0k
        if (!txn_info.ParseFromString(info_val)) {
3199
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
3200
0
            return -1;
3201
0
        }
3202
23.0k
        txn->remove(info_key);
3203
        // Remove sub txn index kvs
3204
23.0k
        std::vector<std::string> sub_txn_index_keys;
3205
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
3206
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
3207
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
3208
22.9k
        }
3209
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
3210
22.9k
            txn->remove(sub_txn_index_key);
3211
22.9k
        }
3212
        // Update txn label
3213
23.0k
        std::string label_key, label_val;
3214
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
3215
23.0k
        err = txn->get(label_key, &label_val);
3216
23.0k
        if (err != TxnErrorCode::TXN_OK) {
3217
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
3218
0
                         << " err=" << err;
3219
0
            return -1;
3220
0
        }
3221
23.0k
        TxnLabelPB txn_label;
3222
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
3223
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
3224
0
            return -1;
3225
0
        }
3226
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
3227
23.0k
        if (it != txn_label.txn_ids().end()) {
3228
23.0k
            txn_label.mutable_txn_ids()->erase(it);
3229
23.0k
        }
3230
23.0k
        if (txn_label.txn_ids().empty()) {
3231
23.0k
            txn->remove(label_key);
3232
23.0k
        } else {
3233
0
            if (!txn_label.SerializeToString(&label_val)) {
3234
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
3235
0
                return -1;
3236
0
            }
3237
0
            txn->atomic_set_ver_value(label_key, label_val);
3238
0
        }
3239
        // Remove recycle txn kv
3240
23.0k
        txn->remove(k);
3241
23.0k
        err = txn->commit();
3242
23.0k
        if (err != TxnErrorCode::TXN_OK) {
3243
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
3244
0
            return -1;
3245
0
        }
3246
23.0k
        metrics_context.total_recycled_num = ++num_recycled;
3247
23.0k
        metrics_context.report();
3248
3249
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
3250
23.0k
        return 0;
3251
23.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
3167
3
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
3168
3
        std::string_view k1 = k;
3169
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
3170
3
        k1.remove_prefix(1); // Remove key space
3171
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3172
3
        int ret = decode_key(&k1, &out);
3173
3
        if (ret != 0) {
3174
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
3175
0
            return -1;
3176
0
        }
3177
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
3178
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
3179
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
3180
3
        std::unique_ptr<Transaction> txn;
3181
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3182
3
        if (err != TxnErrorCode::TXN_OK) {
3183
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
3184
0
            return -1;
3185
0
        }
3186
        // Remove txn index kv
3187
3
        auto index_key = txn_index_key({instance_id_, txn_id});
3188
3
        txn->remove(index_key);
3189
        // Remove txn info kv
3190
3
        std::string info_key, info_val;
3191
3
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
3192
3
        err = txn->get(info_key, &info_val);
3193
3
        if (err != TxnErrorCode::TXN_OK) {
3194
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
3195
0
            return -1;
3196
0
        }
3197
3
        TxnInfoPB txn_info;
3198
3
        if (!txn_info.ParseFromString(info_val)) {
3199
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
3200
0
            return -1;
3201
0
        }
3202
3
        txn->remove(info_key);
3203
        // Remove sub txn index kvs
3204
3
        std::vector<std::string> sub_txn_index_keys;
3205
3
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
3206
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
3207
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
3208
0
        }
3209
3
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
3210
0
            txn->remove(sub_txn_index_key);
3211
0
        }
3212
        // Update txn label
3213
3
        std::string label_key, label_val;
3214
3
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
3215
3
        err = txn->get(label_key, &label_val);
3216
3
        if (err != TxnErrorCode::TXN_OK) {
3217
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
3218
0
                         << " err=" << err;
3219
0
            return -1;
3220
0
        }
3221
3
        TxnLabelPB txn_label;
3222
3
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
3223
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
3224
0
            return -1;
3225
0
        }
3226
3
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
3227
3
        if (it != txn_label.txn_ids().end()) {
3228
3
            txn_label.mutable_txn_ids()->erase(it);
3229
3
        }
3230
3
        if (txn_label.txn_ids().empty()) {
3231
3
            txn->remove(label_key);
3232
3
        } else {
3233
0
            if (!txn_label.SerializeToString(&label_val)) {
3234
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
3235
0
                return -1;
3236
0
            }
3237
0
            txn->atomic_set_ver_value(label_key, label_val);
3238
0
        }
3239
        // Remove recycle txn kv
3240
3
        txn->remove(k);
3241
3
        err = txn->commit();
3242
3
        if (err != TxnErrorCode::TXN_OK) {
3243
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
3244
0
            return -1;
3245
0
        }
3246
3
        metrics_context.total_recycled_num = ++num_recycled;
3247
3
        metrics_context.report();
3248
3249
3
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
3250
3
        return 0;
3251
3
    };
3252
3253
19
    auto loop_done = [&]() -> int {
3254
10
        DORIS_CLOUD_DEFER {
3255
10
            recycle_txn_info_keys.clear();
3256
10
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3254
7
        DORIS_CLOUD_DEFER {
3255
7
            recycle_txn_info_keys.clear();
3256
7
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3254
3
        DORIS_CLOUD_DEFER {
3255
3
            recycle_txn_info_keys.clear();
3256
3
        };
3257
10
        TEST_SYNC_POINT_CALLBACK(
3258
10
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
3259
10
                &recycle_txn_info_keys);
3260
23.0k
        for (const auto& k : recycle_txn_info_keys) {
3261
23.0k
            concurrent_delete_executor.add([&]() {
3262
23.0k
                if (delete_recycle_txn_kv(k) != 0) {
3263
0
                    LOG_WARNING("failed to delete recycle txn kv")
3264
0
                            .tag("instance id", instance_id_)
3265
0
                            .tag("key", hex(k));
3266
0
                    return -1;
3267
0
                }
3268
23.0k
                return 0;
3269
23.0k
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
3261
23.0k
            concurrent_delete_executor.add([&]() {
3262
23.0k
                if (delete_recycle_txn_kv(k) != 0) {
3263
0
                    LOG_WARNING("failed to delete recycle txn kv")
3264
0
                            .tag("instance id", instance_id_)
3265
0
                            .tag("key", hex(k));
3266
0
                    return -1;
3267
0
                }
3268
23.0k
                return 0;
3269
23.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
3261
3
            concurrent_delete_executor.add([&]() {
3262
3
                if (delete_recycle_txn_kv(k) != 0) {
3263
0
                    LOG_WARNING("failed to delete recycle txn kv")
3264
0
                            .tag("instance id", instance_id_)
3265
0
                            .tag("key", hex(k));
3266
0
                    return -1;
3267
0
                }
3268
3
                return 0;
3269
3
            });
3270
23.0k
        }
3271
10
        bool finished = true;
3272
10
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
3273
23.0k
        for (int r : rets) {
3274
23.0k
            if (r != 0) {
3275
0
                ret = -1;
3276
0
            }
3277
23.0k
        }
3278
3279
10
        ret = finished ? ret : -1;
3280
3281
10
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
3282
3283
10
        if (ret != 0) {
3284
2
            LOG_WARNING("recycle txn kv ret!=0")
3285
2
                    .tag("finished", finished)
3286
2
                    .tag("ret", ret)
3287
2
                    .tag("instance_id", instance_id_);
3288
2
            return ret;
3289
2
        }
3290
8
        return ret;
3291
10
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
3253
7
    auto loop_done = [&]() -> int {
3254
7
        DORIS_CLOUD_DEFER {
3255
7
            recycle_txn_info_keys.clear();
3256
7
        };
3257
7
        TEST_SYNC_POINT_CALLBACK(
3258
7
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
3259
7
                &recycle_txn_info_keys);
3260
23.0k
        for (const auto& k : recycle_txn_info_keys) {
3261
23.0k
            concurrent_delete_executor.add([&]() {
3262
23.0k
                if (delete_recycle_txn_kv(k) != 0) {
3263
23.0k
                    LOG_WARNING("failed to delete recycle txn kv")
3264
23.0k
                            .tag("instance id", instance_id_)
3265
23.0k
                            .tag("key", hex(k));
3266
23.0k
                    return -1;
3267
23.0k
                }
3268
23.0k
                return 0;
3269
23.0k
            });
3270
23.0k
        }
3271
7
        bool finished = true;
3272
7
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
3273
23.0k
        for (int r : rets) {
3274
23.0k
            if (r != 0) {
3275
0
                ret = -1;
3276
0
            }
3277
23.0k
        }
3278
3279
7
        ret = finished ? ret : -1;
3280
3281
7
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
3282
3283
7
        if (ret != 0) {
3284
2
            LOG_WARNING("recycle txn kv ret!=0")
3285
2
                    .tag("finished", finished)
3286
2
                    .tag("ret", ret)
3287
2
                    .tag("instance_id", instance_id_);
3288
2
            return ret;
3289
2
        }
3290
5
        return ret;
3291
7
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
3253
3
    auto loop_done = [&]() -> int {
3254
3
        DORIS_CLOUD_DEFER {
3255
3
            recycle_txn_info_keys.clear();
3256
3
        };
3257
3
        TEST_SYNC_POINT_CALLBACK(
3258
3
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
3259
3
                &recycle_txn_info_keys);
3260
3
        for (const auto& k : recycle_txn_info_keys) {
3261
3
            concurrent_delete_executor.add([&]() {
3262
3
                if (delete_recycle_txn_kv(k) != 0) {
3263
3
                    LOG_WARNING("failed to delete recycle txn kv")
3264
3
                            .tag("instance id", instance_id_)
3265
3
                            .tag("key", hex(k));
3266
3
                    return -1;
3267
3
                }
3268
3
                return 0;
3269
3
            });
3270
3
        }
3271
3
        bool finished = true;
3272
3
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
3273
3
        for (int r : rets) {
3274
3
            if (r != 0) {
3275
0
                ret = -1;
3276
0
            }
3277
3
        }
3278
3279
3
        ret = finished ? ret : -1;
3280
3281
3
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
3282
3283
3
        if (ret != 0) {
3284
0
            LOG_WARNING("recycle txn kv ret!=0")
3285
0
                    .tag("finished", finished)
3286
0
                    .tag("ret", ret)
3287
0
                    .tag("instance_id", instance_id_);
3288
0
            return ret;
3289
0
        }
3290
3
        return ret;
3291
3
    };
3292
3293
19
    if (config::enable_recycler_stats_metrics) {
3294
0
        scan_and_statistics_expired_txn_label();
3295
0
    }
3296
    // recycle_func and loop_done for scan and recycle
3297
19
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
3298
19
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
3299
19
}
3300
3301
struct CopyJobIdTuple {
3302
    std::string instance_id;
3303
    std::string stage_id;
3304
    long table_id;
3305
    std::string copy_id;
3306
    std::string stage_path;
3307
};
3308
struct BatchObjStoreAccessor {
3309
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
3310
                          TxnKv* txn_kv)
3311
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
3312
3
    ~BatchObjStoreAccessor() {
3313
3
        if (!paths_.empty()) {
3314
3
            consume();
3315
3
        }
3316
3
    }
3317
3318
    /**
3319
    * To implicitely do batch work and submit the batch delete task to s3
3320
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
3321
    *
3322
    * @param copy_job The protubuf struct consists of the copy job files.
3323
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
3324
    *            it would last until we finish the delete task, here we need pass one string value
3325
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
3326
    */
3327
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
3328
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
3329
5
        auto& file_keys = copy_file_keys_[key];
3330
5
        file_keys.log_trace =
3331
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
3332
5
                            instance_id, stage_id, table_id, copy_id, path);
3333
5
        std::string_view log_trace = file_keys.log_trace;
3334
2.03k
        for (const auto& file : copy_job.object_files()) {
3335
2.03k
            auto relative_path = file.relative_path();
3336
2.03k
            paths_.push_back(relative_path);
3337
2.03k
            file_keys.keys.push_back(copy_file_key(
3338
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
3339
2.03k
            LOG_INFO(log_trace)
3340
2.03k
                    .tag("relative_path", relative_path)
3341
2.03k
                    .tag("batch_count", batch_count_);
3342
2.03k
        }
3343
5
        LOG_INFO(log_trace)
3344
5
                .tag("objects_num", copy_job.object_files().size())
3345
5
                .tag("batch_count", batch_count_);
3346
        // 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
3347
        // recommend using delete objects when objects num is less than 10)
3348
5
        if (paths_.size() < 1000) {
3349
3
            return;
3350
3
        }
3351
2
        consume();
3352
2
    }
3353
3354
private:
3355
5
    void consume() {
3356
5
        DORIS_CLOUD_DEFER {
3357
5
            paths_.clear();
3358
5
            copy_file_keys_.clear();
3359
5
            batch_count_++;
3360
3361
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
3362
5
                        batch_count_);
3363
5
        };
3364
3365
5
        StopWatch sw;
3366
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
3367
5
        if (0 != accessor_->delete_files(paths_)) {
3368
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
3369
2
                        paths_.size(), batch_count_, sw.elapsed_us());
3370
2
            return;
3371
2
        }
3372
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
3373
3
                    paths_.size(), batch_count_, sw.elapsed_us());
3374
        // delete fdb's keys
3375
3
        for (auto& file_keys : copy_file_keys_) {
3376
3
            auto& [log_trace, keys] = file_keys.second;
3377
3
            std::unique_ptr<Transaction> txn;
3378
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
3379
0
                LOG(WARNING) << "failed to create txn";
3380
0
                continue;
3381
0
            }
3382
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
3383
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
3384
            // limited, should not cause the txn commit failed.
3385
1.02k
            for (const auto& key : keys) {
3386
1.02k
                txn->remove(key);
3387
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
3388
1.02k
            }
3389
3
            txn->remove(file_keys.first);
3390
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
3391
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
3392
0
                continue;
3393
0
            }
3394
3
        }
3395
3
    }
3396
    std::shared_ptr<StorageVaultAccessor> accessor_;
3397
    // the path of the s3 files to be deleted
3398
    std::vector<std::string> paths_;
3399
    struct CopyFiles {
3400
        std::string log_trace;
3401
        std::vector<std::string> keys;
3402
    };
3403
    // pair<std::string, std::vector<std::string>>
3404
    // first: instance_id_ stage_id table_id query_id
3405
    // second: keys to be deleted
3406
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
3407
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
3408
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
3409
    // which can together uniquely identifies different tasks for tracing log
3410
    uint64_t& batch_count_;
3411
    TxnKv* txn_kv_;
3412
};
3413
3414
13
int InstanceRecycler::recycle_copy_jobs() {
3415
13
    int64_t num_scanned = 0;
3416
13
    int64_t num_finished = 0;
3417
13
    int64_t num_expired = 0;
3418
13
    int64_t num_recycled = 0;
3419
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
3420
13
    uint64_t batch_count = 0;
3421
13
    const std::string task_name = "recycle_copy_jobs";
3422
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
3423
3424
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
3425
3426
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
3427
13
    register_recycle_task(task_name, start_time);
3428
3429
13
    DORIS_CLOUD_DEFER {
3430
13
        unregister_recycle_task(task_name);
3431
13
        int64_t cost =
3432
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3433
13
        metrics_context.finish_report();
3434
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
3435
13
                .tag("instance_id", instance_id_)
3436
13
                .tag("num_scanned", num_scanned)
3437
13
                .tag("num_finished", num_finished)
3438
13
                .tag("num_expired", num_expired)
3439
13
                .tag("num_recycled", num_recycled);
3440
13
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
3429
13
    DORIS_CLOUD_DEFER {
3430
13
        unregister_recycle_task(task_name);
3431
13
        int64_t cost =
3432
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3433
13
        metrics_context.finish_report();
3434
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
3435
13
                .tag("instance_id", instance_id_)
3436
13
                .tag("num_scanned", num_scanned)
3437
13
                .tag("num_finished", num_finished)
3438
13
                .tag("num_expired", num_expired)
3439
13
                .tag("num_recycled", num_recycled);
3440
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
3441
3442
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
3443
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
3444
13
    std::string key0;
3445
13
    std::string key1;
3446
13
    copy_job_key(key_info0, &key0);
3447
13
    copy_job_key(key_info1, &key1);
3448
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
3449
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
3450
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
3451
16
                         this](std::string_view k, std::string_view v) -> int {
3452
16
        ++num_scanned;
3453
16
        CopyJobPB copy_job;
3454
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
3455
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
3456
0
            return -1;
3457
0
        }
3458
3459
        // decode copy job key
3460
16
        auto k1 = k;
3461
16
        k1.remove_prefix(1);
3462
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3463
16
        decode_key(&k1, &out);
3464
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
3465
        // -> CopyJobPB
3466
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
3467
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
3468
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
3469
3470
16
        bool check_storage = true;
3471
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
3472
12
            ++num_finished;
3473
3474
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
3475
7
                auto it = stage_accessor_map.find(stage_id);
3476
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
3477
7
                std::string_view path;
3478
7
                if (it != stage_accessor_map.end()) {
3479
2
                    accessor = it->second;
3480
5
                } else {
3481
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
3482
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
3483
5
                                                      &inner_accessor);
3484
5
                    if (ret < 0) { // error
3485
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
3486
0
                        return -1;
3487
5
                    } else if (ret == 0) {
3488
3
                        path = inner_accessor->uri();
3489
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
3490
3
                                inner_accessor, batch_count, txn_kv_.get());
3491
3
                        stage_accessor_map.emplace(stage_id, accessor);
3492
3
                    } else { // stage not found, skip check storage
3493
2
                        check_storage = false;
3494
2
                    }
3495
5
                }
3496
7
                if (check_storage) {
3497
                    // TODO delete objects with key and etag is not supported
3498
5
                    accessor->add(std::move(copy_job), std::string(k),
3499
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
3500
5
                    return 0;
3501
5
                }
3502
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
3503
5
                int64_t current_time =
3504
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
3505
5
                if (copy_job.finish_time_ms() > 0) {
3506
2
                    if (!config::force_immediate_recycle &&
3507
2
                        current_time < copy_job.finish_time_ms() +
3508
2
                                               config::copy_job_max_retention_second * 1000) {
3509
1
                        return 0;
3510
1
                    }
3511
3
                } else {
3512
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
3513
3
                    if (!config::force_immediate_recycle &&
3514
3
                        current_time < copy_job.start_time_ms() +
3515
3
                                               config::copy_job_max_retention_second * 1000) {
3516
1
                        return 0;
3517
1
                    }
3518
3
                }
3519
5
            }
3520
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
3521
4
            int64_t current_time =
3522
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
3523
            // if copy job is timeout: delete all copy file kvs and copy job kv
3524
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
3525
2
                return 0;
3526
2
            }
3527
2
            ++num_expired;
3528
2
        }
3529
3530
        // delete all copy files
3531
7
        std::vector<std::string> copy_file_keys;
3532
70
        for (auto& file : copy_job.object_files()) {
3533
70
            copy_file_keys.push_back(copy_file_key(
3534
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
3535
70
        }
3536
7
        std::unique_ptr<Transaction> txn;
3537
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3538
0
            LOG(WARNING) << "failed to create txn";
3539
0
            return -1;
3540
0
        }
3541
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
3542
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
3543
        // limited, should not cause the txn commit failed.
3544
70
        for (const auto& key : copy_file_keys) {
3545
70
            txn->remove(key);
3546
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
3547
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
3548
70
                      << ", query_id=" << copy_id;
3549
70
        }
3550
7
        txn->remove(k);
3551
7
        TxnErrorCode err = txn->commit();
3552
7
        if (err != TxnErrorCode::TXN_OK) {
3553
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
3554
0
            return -1;
3555
0
        }
3556
3557
7
        metrics_context.total_recycled_num = ++num_recycled;
3558
7
        metrics_context.report();
3559
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3560
7
        return 0;
3561
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3451
16
                         this](std::string_view k, std::string_view v) -> int {
3452
16
        ++num_scanned;
3453
16
        CopyJobPB copy_job;
3454
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
3455
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
3456
0
            return -1;
3457
0
        }
3458
3459
        // decode copy job key
3460
16
        auto k1 = k;
3461
16
        k1.remove_prefix(1);
3462
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3463
16
        decode_key(&k1, &out);
3464
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
3465
        // -> CopyJobPB
3466
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
3467
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
3468
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
3469
3470
16
        bool check_storage = true;
3471
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
3472
12
            ++num_finished;
3473
3474
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
3475
7
                auto it = stage_accessor_map.find(stage_id);
3476
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
3477
7
                std::string_view path;
3478
7
                if (it != stage_accessor_map.end()) {
3479
2
                    accessor = it->second;
3480
5
                } else {
3481
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
3482
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
3483
5
                                                      &inner_accessor);
3484
5
                    if (ret < 0) { // error
3485
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
3486
0
                        return -1;
3487
5
                    } else if (ret == 0) {
3488
3
                        path = inner_accessor->uri();
3489
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
3490
3
                                inner_accessor, batch_count, txn_kv_.get());
3491
3
                        stage_accessor_map.emplace(stage_id, accessor);
3492
3
                    } else { // stage not found, skip check storage
3493
2
                        check_storage = false;
3494
2
                    }
3495
5
                }
3496
7
                if (check_storage) {
3497
                    // TODO delete objects with key and etag is not supported
3498
5
                    accessor->add(std::move(copy_job), std::string(k),
3499
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
3500
5
                    return 0;
3501
5
                }
3502
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
3503
5
                int64_t current_time =
3504
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
3505
5
                if (copy_job.finish_time_ms() > 0) {
3506
2
                    if (!config::force_immediate_recycle &&
3507
2
                        current_time < copy_job.finish_time_ms() +
3508
2
                                               config::copy_job_max_retention_second * 1000) {
3509
1
                        return 0;
3510
1
                    }
3511
3
                } else {
3512
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
3513
3
                    if (!config::force_immediate_recycle &&
3514
3
                        current_time < copy_job.start_time_ms() +
3515
3
                                               config::copy_job_max_retention_second * 1000) {
3516
1
                        return 0;
3517
1
                    }
3518
3
                }
3519
5
            }
3520
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
3521
4
            int64_t current_time =
3522
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
3523
            // if copy job is timeout: delete all copy file kvs and copy job kv
3524
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
3525
2
                return 0;
3526
2
            }
3527
2
            ++num_expired;
3528
2
        }
3529
3530
        // delete all copy files
3531
7
        std::vector<std::string> copy_file_keys;
3532
70
        for (auto& file : copy_job.object_files()) {
3533
70
            copy_file_keys.push_back(copy_file_key(
3534
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
3535
70
        }
3536
7
        std::unique_ptr<Transaction> txn;
3537
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3538
0
            LOG(WARNING) << "failed to create txn";
3539
0
            return -1;
3540
0
        }
3541
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
3542
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
3543
        // limited, should not cause the txn commit failed.
3544
70
        for (const auto& key : copy_file_keys) {
3545
70
            txn->remove(key);
3546
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
3547
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
3548
70
                      << ", query_id=" << copy_id;
3549
70
        }
3550
7
        txn->remove(k);
3551
7
        TxnErrorCode err = txn->commit();
3552
7
        if (err != TxnErrorCode::TXN_OK) {
3553
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
3554
0
            return -1;
3555
0
        }
3556
3557
7
        metrics_context.total_recycled_num = ++num_recycled;
3558
7
        metrics_context.report();
3559
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3560
7
        return 0;
3561
7
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
3562
3563
13
    if (config::enable_recycler_stats_metrics) {
3564
0
        scan_and_statistics_copy_jobs();
3565
0
    }
3566
    // recycle_func and loop_done for scan and recycle
3567
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
3568
13
}
3569
3570
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
3571
                                             const StagePB::StageType& stage_type,
3572
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
3573
5
#ifdef UNIT_TEST
3574
    // In unit test, external use the same accessor as the internal stage
3575
5
    auto it = accessor_map_.find(stage_id);
3576
5
    if (it != accessor_map_.end()) {
3577
3
        *accessor = it->second;
3578
3
    } else {
3579
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
3580
2
        return 1;
3581
2
    }
3582
#else
3583
    // init s3 accessor and add to accessor map
3584
    auto stage_it =
3585
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
3586
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
3587
3588
    if (stage_it == instance_info_.stages().end()) {
3589
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
3590
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
3591
        return 1;
3592
    }
3593
3594
    const auto& object_store_info = stage_it->obj_info();
3595
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
3596
3597
    S3Conf s3_conf;
3598
    if (stage_type == StagePB::EXTERNAL) {
3599
        if (stage_access_type == StagePB::AKSK) {
3600
            auto conf = S3Conf::from_obj_store_info(object_store_info);
3601
            if (!conf) {
3602
                return -1;
3603
            }
3604
3605
            s3_conf = std::move(*conf);
3606
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
3607
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
3608
            if (!conf) {
3609
                return -1;
3610
            }
3611
3612
            s3_conf = std::move(*conf);
3613
            if (instance_info_.ram_user().has_encryption_info()) {
3614
                AkSkPair plain_ak_sk_pair;
3615
                int ret = decrypt_ak_sk_helper(
3616
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
3617
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
3618
                if (ret != 0) {
3619
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
3620
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
3621
                    return -1;
3622
                }
3623
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
3624
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
3625
            } else {
3626
                s3_conf.ak = instance_info_.ram_user().ak();
3627
                s3_conf.sk = instance_info_.ram_user().sk();
3628
            }
3629
        } else {
3630
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
3631
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
3632
            return -1;
3633
        }
3634
    } else if (stage_type == StagePB::INTERNAL) {
3635
        int idx = stoi(object_store_info.id());
3636
        if (idx > instance_info_.obj_info().size() || idx < 1) {
3637
            LOG(WARNING) << "invalid idx: " << idx;
3638
            return -1;
3639
        }
3640
3641
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
3642
        auto conf = S3Conf::from_obj_store_info(old_obj);
3643
        if (!conf) {
3644
            return -1;
3645
        }
3646
3647
        s3_conf = std::move(*conf);
3648
        s3_conf.prefix = object_store_info.prefix();
3649
    } else {
3650
        LOG(WARNING) << "unknown stage type " << stage_type;
3651
        return -1;
3652
    }
3653
3654
    std::shared_ptr<S3Accessor> s3_accessor;
3655
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
3656
    if (ret != 0) {
3657
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
3658
        return -1;
3659
    }
3660
3661
    *accessor = std::move(s3_accessor);
3662
#endif
3663
3
    return 0;
3664
5
}
3665
3666
11
int InstanceRecycler::recycle_stage() {
3667
11
    int64_t num_scanned = 0;
3668
11
    int64_t num_recycled = 0;
3669
11
    const std::string task_name = "recycle_stage";
3670
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
3671
3672
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
3673
3674
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
3675
11
    register_recycle_task(task_name, start_time);
3676
3677
11
    DORIS_CLOUD_DEFER {
3678
11
        unregister_recycle_task(task_name);
3679
11
        int64_t cost =
3680
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3681
11
        metrics_context.finish_report();
3682
11
        LOG_WARNING("recycle stage, cost={}s", cost)
3683
11
                .tag("instance_id", instance_id_)
3684
11
                .tag("num_scanned", num_scanned)
3685
11
                .tag("num_recycled", num_recycled);
3686
11
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
3677
11
    DORIS_CLOUD_DEFER {
3678
11
        unregister_recycle_task(task_name);
3679
11
        int64_t cost =
3680
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3681
11
        metrics_context.finish_report();
3682
11
        LOG_WARNING("recycle stage, cost={}s", cost)
3683
11
                .tag("instance_id", instance_id_)
3684
11
                .tag("num_scanned", num_scanned)
3685
11
                .tag("num_recycled", num_recycled);
3686
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
3687
3688
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
3689
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
3690
11
    std::string key0 = recycle_stage_key(key_info0);
3691
11
    std::string key1 = recycle_stage_key(key_info1);
3692
3693
11
    std::vector<std::string_view> stage_keys;
3694
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
3695
11
                         this](std::string_view k, std::string_view v) -> int {
3696
1
        ++num_scanned;
3697
1
        RecycleStagePB recycle_stage;
3698
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
3699
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
3700
0
            return -1;
3701
0
        }
3702
3703
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
3704
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
3705
0
            LOG(WARNING) << "invalid idx: " << idx;
3706
0
            return -1;
3707
0
        }
3708
3709
1
        std::shared_ptr<StorageVaultAccessor> accessor;
3710
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
3711
1
                [&] {
3712
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
3713
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
3714
1
                    if (!s3_conf) {
3715
1
                        return -1;
3716
1
                    }
3717
3718
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
3719
1
                    std::shared_ptr<S3Accessor> s3_accessor;
3720
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
3721
1
                    if (ret != 0) {
3722
1
                        return -1;
3723
1
                    }
3724
3725
1
                    accessor = std::move(s3_accessor);
3726
1
                    return 0;
3727
1
                }(),
3728
1
                "recycle_stage:get_accessor", &accessor);
3729
3730
1
        if (ret != 0) {
3731
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
3732
0
            return ret;
3733
0
        }
3734
3735
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
3736
1
                .tag("instance_id", instance_id_)
3737
1
                .tag("stage_id", recycle_stage.stage().stage_id())
3738
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
3739
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
3740
1
                .tag("obj_info_id", idx)
3741
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
3742
1
        ret = accessor->delete_all();
3743
1
        if (ret != 0) {
3744
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
3745
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
3746
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
3747
0
                         << ", ret=" << ret;
3748
0
            return -1;
3749
0
        }
3750
1
        metrics_context.total_recycled_num = ++num_recycled;
3751
1
        metrics_context.report();
3752
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
3753
1
        stage_keys.push_back(k);
3754
1
        return 0;
3755
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3695
1
                         this](std::string_view k, std::string_view v) -> int {
3696
1
        ++num_scanned;
3697
1
        RecycleStagePB recycle_stage;
3698
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
3699
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
3700
0
            return -1;
3701
0
        }
3702
3703
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
3704
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
3705
0
            LOG(WARNING) << "invalid idx: " << idx;
3706
0
            return -1;
3707
0
        }
3708
3709
1
        std::shared_ptr<StorageVaultAccessor> accessor;
3710
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
3711
1
                [&] {
3712
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
3713
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
3714
1
                    if (!s3_conf) {
3715
1
                        return -1;
3716
1
                    }
3717
3718
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
3719
1
                    std::shared_ptr<S3Accessor> s3_accessor;
3720
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
3721
1
                    if (ret != 0) {
3722
1
                        return -1;
3723
1
                    }
3724
3725
1
                    accessor = std::move(s3_accessor);
3726
1
                    return 0;
3727
1
                }(),
3728
1
                "recycle_stage:get_accessor", &accessor);
3729
3730
1
        if (ret != 0) {
3731
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
3732
0
            return ret;
3733
0
        }
3734
3735
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
3736
1
                .tag("instance_id", instance_id_)
3737
1
                .tag("stage_id", recycle_stage.stage().stage_id())
3738
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
3739
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
3740
1
                .tag("obj_info_id", idx)
3741
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
3742
1
        ret = accessor->delete_all();
3743
1
        if (ret != 0) {
3744
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
3745
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
3746
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
3747
0
                         << ", ret=" << ret;
3748
0
            return -1;
3749
0
        }
3750
1
        metrics_context.total_recycled_num = ++num_recycled;
3751
1
        metrics_context.report();
3752
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
3753
1
        stage_keys.push_back(k);
3754
1
        return 0;
3755
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
3756
3757
11
    auto loop_done = [&stage_keys, this]() -> int {
3758
1
        if (stage_keys.empty()) return 0;
3759
1
        DORIS_CLOUD_DEFER {
3760
1
            stage_keys.clear();
3761
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3759
1
        DORIS_CLOUD_DEFER {
3760
1
            stage_keys.clear();
3761
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
3762
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
3763
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3764
0
            return -1;
3765
0
        }
3766
1
        return 0;
3767
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
3757
1
    auto loop_done = [&stage_keys, this]() -> int {
3758
1
        if (stage_keys.empty()) return 0;
3759
1
        DORIS_CLOUD_DEFER {
3760
1
            stage_keys.clear();
3761
1
        };
3762
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
3763
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3764
0
            return -1;
3765
0
        }
3766
1
        return 0;
3767
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
3768
11
    if (config::enable_recycler_stats_metrics) {
3769
0
        scan_and_statistics_stage();
3770
0
    }
3771
    // recycle_func and loop_done for scan and recycle
3772
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
3773
11
}
3774
3775
10
int InstanceRecycler::recycle_expired_stage_objects() {
3776
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
3777
3778
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
3779
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
3780
3781
10
    DORIS_CLOUD_DEFER {
3782
10
        int64_t cost =
3783
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3784
10
        metrics_context.finish_report();
3785
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
3786
10
                .tag("instance_id", instance_id_);
3787
10
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
3781
10
    DORIS_CLOUD_DEFER {
3782
10
        int64_t cost =
3783
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3784
10
        metrics_context.finish_report();
3785
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
3786
10
                .tag("instance_id", instance_id_);
3787
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
3788
3789
10
    int ret = 0;
3790
3791
10
    if (config::enable_recycler_stats_metrics) {
3792
0
        scan_and_statistics_expired_stage_objects();
3793
0
    }
3794
3795
10
    for (const auto& stage : instance_info_.stages()) {
3796
0
        std::stringstream ss;
3797
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
3798
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
3799
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
3800
0
           << ", prefix=" << stage.obj_info().prefix();
3801
3802
0
        if (stopped()) {
3803
0
            break;
3804
0
        }
3805
0
        if (stage.type() == StagePB::EXTERNAL) {
3806
0
            continue;
3807
0
        }
3808
0
        int idx = stoi(stage.obj_info().id());
3809
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
3810
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
3811
0
            continue;
3812
0
        }
3813
3814
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
3815
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
3816
0
        if (!s3_conf) {
3817
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
3818
0
            continue;
3819
0
        }
3820
3821
0
        s3_conf->prefix = stage.obj_info().prefix();
3822
0
        std::shared_ptr<S3Accessor> accessor;
3823
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
3824
0
        if (ret1 != 0) {
3825
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
3826
0
            ret = -1;
3827
0
            continue;
3828
0
        }
3829
3830
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
3831
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
3832
0
            ret = -1;
3833
0
            continue;
3834
0
        }
3835
3836
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
3837
0
        int64_t expiration_time =
3838
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
3839
0
                config::internal_stage_objects_expire_time_second;
3840
0
        if (config::force_immediate_recycle) {
3841
0
            expiration_time = INT64_MAX;
3842
0
        }
3843
0
        ret1 = accessor->delete_all(expiration_time);
3844
0
        if (ret1 != 0) {
3845
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
3846
0
                         << ss.str();
3847
0
            ret = -1;
3848
0
            continue;
3849
0
        }
3850
0
        metrics_context.total_recycled_num++;
3851
0
        metrics_context.report();
3852
0
    }
3853
10
    return ret;
3854
10
}
3855
3856
132
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
3857
132
    std::lock_guard lock(recycle_tasks_mutex);
3858
132
    running_recycle_tasks[task_name] = start_time;
3859
132
}
3860
3861
132
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
3862
132
    std::lock_guard lock(recycle_tasks_mutex);
3863
132
    DCHECK(running_recycle_tasks[task_name] > 0);
3864
132
    running_recycle_tasks.erase(task_name);
3865
132
}
3866
3867
21
bool InstanceRecycler::check_recycle_tasks() {
3868
21
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
3869
21
    {
3870
21
        std::lock_guard lock(recycle_tasks_mutex);
3871
21
        tmp_running_recycle_tasks = running_recycle_tasks;
3872
21
    }
3873
3874
21
    bool found = false;
3875
21
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
3876
21
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
3877
20
        int64_t cost = now - start_time;
3878
20
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
3879
20
            LOG_INFO("recycle task cost too much time cost={}s", cost)
3880
20
                    .tag("instance_id", instance_id_)
3881
20
                    .tag("task", task_name);
3882
20
            found = true;
3883
20
        }
3884
20
    }
3885
3886
21
    return found;
3887
21
}
3888
3889
// Scan and statistics indexes that need to be recycled
3890
0
int InstanceRecycler::scan_and_statistics_indexes() {
3891
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
3892
3893
0
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
3894
0
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
3895
0
    std::string index_key0;
3896
0
    std::string index_key1;
3897
0
    recycle_index_key(index_key_info0, &index_key0);
3898
0
    recycle_index_key(index_key_info1, &index_key1);
3899
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
3900
3901
0
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
3902
0
        RecycleIndexPB index_pb;
3903
0
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
3904
0
            return 0;
3905
0
        }
3906
0
        int64_t current_time = ::time(nullptr);
3907
0
        if (current_time <
3908
0
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
3909
0
            return 0;
3910
0
        }
3911
        // decode index_id
3912
0
        auto k1 = k;
3913
0
        k1.remove_prefix(1);
3914
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3915
0
        decode_key(&k1, &out);
3916
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
3917
0
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
3918
0
        std::unique_ptr<Transaction> txn;
3919
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3920
0
        if (err != TxnErrorCode::TXN_OK) {
3921
0
            return 0;
3922
0
        }
3923
0
        std::string val;
3924
0
        err = txn->get(k, &val);
3925
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3926
0
            return 0;
3927
0
        }
3928
0
        if (err != TxnErrorCode::TXN_OK) {
3929
0
            return 0;
3930
0
        }
3931
0
        index_pb.Clear();
3932
0
        if (!index_pb.ParseFromString(val)) {
3933
0
            return 0;
3934
0
        }
3935
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
3936
0
            return 0;
3937
0
        }
3938
0
        metrics_context.total_need_recycle_num++;
3939
0
        return 0;
3940
0
    };
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
3941
3942
0
    return scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv),
3943
0
                            [&metrics_context]() -> int {
3944
0
                                metrics_context.report(true);
3945
0
                                segment_metrics_context_.report(true);
3946
0
                                tablet_metrics_context_.report(true);
3947
0
                                return 0;
3948
0
                            });
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_1clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_1clEv
3949
0
}
3950
3951
// Scan and statistics partitions that need to be recycled
3952
0
int InstanceRecycler::scan_and_statistics_partitions() {
3953
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
3954
3955
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
3956
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
3957
0
    std::string part_key0;
3958
0
    std::string part_key1;
3959
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
3960
3961
0
    recycle_partition_key(part_key_info0, &part_key0);
3962
0
    recycle_partition_key(part_key_info1, &part_key1);
3963
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
3964
0
        RecyclePartitionPB part_pb;
3965
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3966
0
            return 0;
3967
0
        }
3968
0
        int64_t current_time = ::time(nullptr);
3969
0
        if (current_time <
3970
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
3971
0
            return 0;
3972
0
        }
3973
        // decode partition_id
3974
0
        auto k1 = k;
3975
0
        k1.remove_prefix(1);
3976
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3977
0
        decode_key(&k1, &out);
3978
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3979
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3980
        // Change state to RECYCLING
3981
0
        std::unique_ptr<Transaction> txn;
3982
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3983
0
        if (err != TxnErrorCode::TXN_OK) {
3984
0
            return 0;
3985
0
        }
3986
0
        std::string val;
3987
0
        err = txn->get(k, &val);
3988
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3989
0
            return 0;
3990
0
        }
3991
0
        if (err != TxnErrorCode::TXN_OK) {
3992
0
            return 0;
3993
0
        }
3994
0
        part_pb.Clear();
3995
0
        if (!part_pb.ParseFromString(val)) {
3996
0
            return 0;
3997
0
        }
3998
        // Partitions with PREPARED state MUST have no data
3999
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
4000
0
        int ret = 0;
4001
0
        for (int64_t index_id : part_pb.index_id()) {
4002
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
4003
0
                                            partition_id, is_empty_tablet) != 0) {
4004
0
                ret = 0;
4005
0
            }
4006
0
        }
4007
0
        metrics_context.total_need_recycle_num++;
4008
0
        return ret;
4009
0
    };
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler30scan_and_statistics_partitionsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler30scan_and_statistics_partitionsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
4010
0
    return scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv),
4011
0
                            [&metrics_context]() -> int {
4012
0
                                metrics_context.report(true);
4013
0
                                segment_metrics_context_.report(true);
4014
0
                                tablet_metrics_context_.report(true);
4015
0
                                return 0;
4016
0
                            });
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler30scan_and_statistics_partitionsEvENK3$_1clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler30scan_and_statistics_partitionsEvENK3$_1clEv
4017
0
}
4018
4019
// Scan and statistics rowsets that need to be recycled
4020
0
int InstanceRecycler::scan_and_statistics_rowsets() {
4021
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
4022
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
4023
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
4024
0
    std::string recyc_rs_key0;
4025
0
    std::string recyc_rs_key1;
4026
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
4027
0
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
4028
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
4029
4030
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
4031
0
        RecycleRowsetPB rowset;
4032
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
4033
0
            return 0;
4034
0
        }
4035
0
        int64_t current_time = ::time(nullptr);
4036
0
        if (current_time <
4037
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
4038
0
            return 0;
4039
0
        }
4040
0
        if (!rowset.has_type()) {
4041
0
            if (!rowset.has_resource_id()) [[unlikely]] {
4042
0
                return 0;
4043
0
            }
4044
0
            if (rowset.resource_id().empty()) [[unlikely]] {
4045
0
                return 0;
4046
0
            }
4047
0
            return 0;
4048
0
        }
4049
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
4050
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
4051
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
4052
0
                return 0;
4053
0
            }
4054
0
        }
4055
0
        metrics_context.total_need_recycle_num++;
4056
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
4057
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
4058
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
4059
0
        return 0;
4060
0
    };
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_rowsetsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_rowsetsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
4061
0
    return scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
4062
0
                            [&metrics_context]() -> int {
4063
0
                                metrics_context.report(true);
4064
0
                                segment_metrics_context_.report(true);
4065
0
                                return 0;
4066
0
                            });
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_rowsetsEvENK3$_1clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_rowsetsEvENK3$_1clEv
4067
0
}
4068
4069
// Scan and statistics tmp_rowsets that need to be recycled
4070
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
4071
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
4072
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
4073
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
4074
0
    std::string tmp_rs_key0;
4075
0
    std::string tmp_rs_key1;
4076
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
4077
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
4078
4079
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
4080
4081
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
4082
0
        doris::RowsetMetaCloudPB rowset;
4083
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
4084
0
            return 0;
4085
0
        }
4086
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
4087
0
        int64_t current_time = ::time(nullptr);
4088
0
        if (current_time < expiration) {
4089
0
            return 0;
4090
0
        }
4091
4092
0
        DCHECK_GT(rowset.txn_id(), 0)
4093
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
4094
0
        if (!is_txn_finished(txn_kv_, instance_id_, rowset.txn_id())) {
4095
0
            return 0;
4096
0
        }
4097
4098
0
        if (!rowset.has_resource_id()) {
4099
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
4100
0
                return 0;
4101
0
            }
4102
0
            return 0;
4103
0
        }
4104
4105
0
        metrics_context.total_need_recycle_num++;
4106
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
4107
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
4108
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
4109
0
        return 0;
4110
0
    };
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler31scan_and_statistics_tmp_rowsetsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler31scan_and_statistics_tmp_rowsetsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
4111
0
    return scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv),
4112
0
                            [&metrics_context]() -> int {
4113
0
                                metrics_context.report(true);
4114
0
                                segment_metrics_context_.report(true);
4115
0
                                return 0;
4116
0
                            });
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler31scan_and_statistics_tmp_rowsetsEvENK3$_1clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler31scan_and_statistics_tmp_rowsetsEvENK3$_1clEv
4117
0
}
4118
4119
// Scan and statistics abort_timeout_txn that need to be recycled
4120
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
4121
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
4122
4123
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
4124
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
4125
0
    std::string begin_txn_running_key;
4126
0
    std::string end_txn_running_key;
4127
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
4128
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
4129
4130
0
    int64_t current_time =
4131
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
4132
4133
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
4134
0
                                               std::string_view k, std::string_view v) -> int {
4135
0
        std::unique_ptr<Transaction> txn;
4136
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
4137
0
        if (err != TxnErrorCode::TXN_OK) {
4138
0
            return 0;
4139
0
        }
4140
0
        std::string_view k1 = k;
4141
0
        k1.remove_prefix(1);
4142
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
4143
0
        if (decode_key(&k1, &out) != 0) {
4144
0
            return 0;
4145
0
        }
4146
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
4147
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
4148
        // Update txn_info
4149
0
        std::string txn_inf_key, txn_inf_val;
4150
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
4151
0
        err = txn->get(txn_inf_key, &txn_inf_val);
4152
0
        if (err != TxnErrorCode::TXN_OK) {
4153
0
            return 0;
4154
0
        }
4155
0
        TxnInfoPB txn_info;
4156
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
4157
0
            return 0;
4158
0
        }
4159
4160
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
4161
0
            TxnRunningPB txn_running_pb;
4162
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
4163
0
                return 0;
4164
0
            }
4165
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
4166
0
                return 0;
4167
0
            }
4168
0
            metrics_context.total_need_recycle_num++;
4169
0
        }
4170
0
        return 0;
4171
0
    };
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler37scan_and_statistics_abort_timeout_txnEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler37scan_and_statistics_abort_timeout_txnEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
4172
0
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
4173
0
                            std::move(handle_abort_timeout_txn_kv), [&metrics_context]() -> int {
4174
0
                                metrics_context.report(true);
4175
0
                                return 0;
4176
0
                            });
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler37scan_and_statistics_abort_timeout_txnEvENK3$_1clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler37scan_and_statistics_abort_timeout_txnEvENK3$_1clEv
4177
0
}
4178
4179
// Scan and statistics expired_txn_label that need to be recycled
4180
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
4181
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
4182
4183
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
4184
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
4185
0
    std::string begin_recycle_txn_key;
4186
0
    std::string end_recycle_txn_key;
4187
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
4188
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
4189
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
4190
0
    int64_t current_time_ms =
4191
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
4192
4193
    // for calculate the total num or bytes of recyled objects
4194
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
4195
0
        RecycleTxnPB recycle_txn_pb;
4196
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
4197
0
            return 0;
4198
0
        }
4199
0
        if ((config::force_immediate_recycle) ||
4200
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
4201
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
4202
0
             current_time_ms)) {
4203
0
            metrics_context.total_need_recycle_num++;
4204
0
        }
4205
0
        return 0;
4206
0
    };
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler37scan_and_statistics_expired_txn_labelEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler37scan_and_statistics_expired_txn_labelEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
4207
0
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
4208
0
                            std::move(handle_expired_txn_label_kv), [&metrics_context]() -> int {
4209
0
                                metrics_context.report(true);
4210
0
                                return 0;
4211
0
                            });
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler37scan_and_statistics_expired_txn_labelEvENK3$_1clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler37scan_and_statistics_expired_txn_labelEvENK3$_1clEv
4212
0
}
4213
4214
// Scan and statistics copy_jobs that need to be recycled
4215
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
4216
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
4217
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
4218
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
4219
0
    std::string key0;
4220
0
    std::string key1;
4221
0
    copy_job_key(key_info0, &key0);
4222
0
    copy_job_key(key_info1, &key1);
4223
4224
    // for calculate the total num or bytes of recyled objects
4225
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
4226
0
        CopyJobPB copy_job;
4227
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
4228
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
4229
0
            return 0;
4230
0
        }
4231
4232
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
4233
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
4234
0
                int64_t current_time =
4235
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
4236
0
                if (copy_job.finish_time_ms() > 0) {
4237
0
                    if (!config::force_immediate_recycle &&
4238
0
                        current_time < copy_job.finish_time_ms() +
4239
0
                                               config::copy_job_max_retention_second * 1000) {
4240
0
                        return 0;
4241
0
                    }
4242
0
                } else {
4243
0
                    if (!config::force_immediate_recycle &&
4244
0
                        current_time < copy_job.start_time_ms() +
4245
0
                                               config::copy_job_max_retention_second * 1000) {
4246
0
                        return 0;
4247
0
                    }
4248
0
                }
4249
0
            }
4250
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
4251
0
            int64_t current_time =
4252
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
4253
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
4254
0
                return 0;
4255
0
            }
4256
0
        }
4257
0
        metrics_context.total_need_recycle_num++;
4258
0
        return 0;
4259
0
    };
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29scan_and_statistics_copy_jobsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29scan_and_statistics_copy_jobsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
4260
4261
0
    return scan_and_recycle(key0, key1, std::move(scan_and_statistics),
4262
0
                            [&metrics_context]() -> int {
4263
0
                                metrics_context.report(true);
4264
0
                                return 0;
4265
0
                            });
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29scan_and_statistics_copy_jobsEvENK3$_1clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29scan_and_statistics_copy_jobsEvENK3$_1clEv
4266
0
}
4267
4268
// Scan and statistics stage that need to be recycled
4269
0
int InstanceRecycler::scan_and_statistics_stage() {
4270
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
4271
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
4272
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
4273
0
    std::string key0 = recycle_stage_key(key_info0);
4274
0
    std::string key1 = recycle_stage_key(key_info1);
4275
4276
    // for calculate the total num or bytes of recyled objects
4277
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
4278
0
                                                        std::string_view v) -> int {
4279
0
        RecycleStagePB recycle_stage;
4280
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
4281
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
4282
0
            return 0;
4283
0
        }
4284
4285
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
4286
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
4287
0
            LOG(WARNING) << "invalid idx: " << idx;
4288
0
            return 0;
4289
0
        }
4290
4291
0
        std::shared_ptr<StorageVaultAccessor> accessor;
4292
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
4293
0
                [&] {
4294
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
4295
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
4296
0
                    if (!s3_conf) {
4297
0
                        return 0;
4298
0
                    }
4299
4300
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
4301
0
                    std::shared_ptr<S3Accessor> s3_accessor;
4302
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
4303
0
                    if (ret != 0) {
4304
0
                        return 0;
4305
0
                    }
4306
4307
0
                    accessor = std::move(s3_accessor);
4308
0
                    return 0;
4309
0
                }(),
4310
0
                "recycle_stage:get_accessor", &accessor);
4311
4312
0
        if (ret != 0) {
4313
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
4314
0
            return 0;
4315
0
        }
4316
4317
0
        metrics_context.total_need_recycle_num++;
4318
0
        return 0;
4319
0
    };
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25scan_and_statistics_stageEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25scan_and_statistics_stageEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
4320
4321
0
    return scan_and_recycle(key0, key1, std::move(scan_and_statistics),
4322
0
                            [&metrics_context]() -> int {
4323
0
                                metrics_context.report(true);
4324
0
                                return 0;
4325
0
                            });
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25scan_and_statistics_stageEvENK3$_1clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25scan_and_statistics_stageEvENK3$_1clEv
4326
0
}
4327
4328
// Scan and statistics expired_stage_objects that need to be recycled
4329
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
4330
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
4331
4332
    // for calculate the total num or bytes of recyled objects
4333
0
    auto scan_and_statistics = [&metrics_context, this]() {
4334
0
        for (const auto& stage : instance_info_.stages()) {
4335
0
            if (stopped()) {
4336
0
                break;
4337
0
            }
4338
0
            if (stage.type() == StagePB::EXTERNAL) {
4339
0
                continue;
4340
0
            }
4341
0
            int idx = stoi(stage.obj_info().id());
4342
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
4343
0
                continue;
4344
0
            }
4345
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
4346
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
4347
0
            if (!s3_conf) {
4348
0
                continue;
4349
0
            }
4350
0
            s3_conf->prefix = stage.obj_info().prefix();
4351
0
            std::shared_ptr<S3Accessor> accessor;
4352
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
4353
0
            if (ret1 != 0) {
4354
0
                continue;
4355
0
            }
4356
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
4357
0
                continue;
4358
0
            }
4359
0
            metrics_context.total_need_recycle_num++;
4360
0
        }
4361
0
    };
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
4362
4363
0
    scan_and_statistics();
4364
0
    metrics_context.report(true);
4365
0
    return 0;
4366
0
}
4367
4368
// Scan and statistics versions that need to be recycled
4369
0
int InstanceRecycler::scan_and_statistics_versions() {
4370
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
4371
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
4372
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
4373
4374
0
    int64_t last_scanned_table_id = 0;
4375
0
    bool is_recycled = false; // Is last scanned kv recycled
4376
    // for calculate the total num or bytes of recyled objects
4377
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
4378
0
                                       std::string_view k, std::string_view) {
4379
0
        auto k1 = k;
4380
0
        k1.remove_prefix(1);
4381
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
4382
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
4383
0
        decode_key(&k1, &out);
4384
0
        DCHECK_EQ(out.size(), 6) << k;
4385
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
4386
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
4387
0
            metrics_context.total_need_recycle_num +=
4388
0
                    is_recycled; // Version kv of this table has been recycled
4389
0
            return 0;
4390
0
        }
4391
0
        last_scanned_table_id = table_id;
4392
0
        is_recycled = false;
4393
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
4394
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
4395
0
        std::unique_ptr<Transaction> txn;
4396
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
4397
0
        if (err != TxnErrorCode::TXN_OK) {
4398
0
            return 0;
4399
0
        }
4400
0
        std::unique_ptr<RangeGetIterator> iter;
4401
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
4402
0
        if (err != TxnErrorCode::TXN_OK) {
4403
0
            return 0;
4404
0
        }
4405
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
4406
0
            return 0;
4407
0
        }
4408
0
        metrics_context.total_need_recycle_num++;
4409
0
        is_recycled = true;
4410
0
        return 0;
4411
0
    };
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler28scan_and_statistics_versionsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler28scan_and_statistics_versionsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
4412
4413
0
    return scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics),
4414
0
                            [&metrics_context]() -> int {
4415
0
                                metrics_context.report(true);
4416
0
                                return 0;
4417
0
                            });
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler28scan_and_statistics_versionsEvENK3$_1clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler28scan_and_statistics_versionsEvENK3$_1clEv
4418
0
}
4419
4420
// Scan and statistics restore jobs that need to be recycled
4421
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
4422
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
4423
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
4424
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
4425
0
    std::string restore_job_key0;
4426
0
    std::string restore_job_key1;
4427
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
4428
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
4429
4430
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
4431
4432
    // for calculate the total num or bytes of recyled objects
4433
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
4434
0
        RestoreJobCloudPB restore_job_pb;
4435
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
4436
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
4437
0
            return 0;
4438
0
        }
4439
0
        int64_t expiration =
4440
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
4441
0
        int64_t current_time = ::time(nullptr);
4442
0
        if (current_time < expiration) { // not expired
4443
0
            return 0;
4444
0
        }
4445
0
        metrics_context.total_need_recycle_num++;
4446
0
        return 0;
4447
0
    };
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler32scan_and_statistics_restore_jobsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler32scan_and_statistics_restore_jobsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
4448
4449
0
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics),
4450
0
                            [&metrics_context]() -> int {
4451
0
                                metrics_context.report(true);
4452
0
                                return 0;
4453
0
                            });
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler32scan_and_statistics_restore_jobsEvENK3$_1clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler32scan_and_statistics_restore_jobsEvENK3$_1clEv
4454
0
}
4455
4456
} // namespace doris::cloud