Coverage Report

Created: 2025-06-13 12:16

/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/server.h>
21
#include <butil/endpoint.h>
22
#include <gen_cpp/cloud.pb.h>
23
#include <gen_cpp/olap_file.pb.h>
24
25
#include <atomic>
26
#include <chrono>
27
#include <cstddef>
28
#include <cstdint>
29
#include <deque>
30
#include <numeric>
31
#include <string>
32
#include <string_view>
33
34
#include "common/stopwatch.h"
35
#include "meta-service/meta_service.h"
36
#include "meta-service/meta_service_helper.h"
37
#include "meta-service/meta_service_schema.h"
38
#include "meta-service/txn_kv.h"
39
#include "meta-service/txn_kv_error.h"
40
#include "recycler/checker.h"
41
#include "recycler/hdfs_accessor.h"
42
#include "recycler/s3_accessor.h"
43
#include "recycler/storage_vault_accessor.h"
44
#ifdef UNIT_TEST
45
#include "../test/mock_accessor.h"
46
#endif
47
#include "common/bvars.h"
48
#include "common/config.h"
49
#include "common/encryption_util.h"
50
#include "common/logging.h"
51
#include "common/simple_thread_pool.h"
52
#include "common/util.h"
53
#include "cpp/sync_point.h"
54
#include "meta-service/keys.h"
55
#include "recycler/recycler_service.h"
56
#include "recycler/sync_executor.h"
57
#include "recycler/util.h"
58
59
namespace doris::cloud {
60
61
using namespace std::chrono;
62
63
// return 0 for success get a key, 1 for key not found, negative for error
64
0
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
65
0
    std::unique_ptr<Transaction> txn;
66
0
    TxnErrorCode err = txn_kv->create_txn(&txn);
67
0
    if (err != TxnErrorCode::TXN_OK) {
68
0
        return -1;
69
0
    }
70
0
    switch (txn->get(key, &val, true)) {
71
0
    case TxnErrorCode::TXN_OK:
72
0
        return 0;
73
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
74
0
        return 1;
75
0
    default:
76
0
        return -1;
77
0
    };
78
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
79
80
// 0 for success, negative for error
81
static int txn_get(TxnKv* txn_kv, std::string_view begin, std::string_view end,
82
199
                   std::unique_ptr<RangeGetIterator>& it) {
83
199
    std::unique_ptr<Transaction> txn;
84
199
    TxnErrorCode err = txn_kv->create_txn(&txn);
85
199
    if (err != TxnErrorCode::TXN_OK) {
86
0
        return -1;
87
0
    }
88
199
    switch (txn->get(begin, end, &it, true)) {
89
199
    case TxnErrorCode::TXN_OK:
90
199
        return 0;
91
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
92
0
        return 1;
93
0
    default:
94
0
        return -1;
95
199
    };
96
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
82
180
                   std::unique_ptr<RangeGetIterator>& it) {
83
180
    std::unique_ptr<Transaction> txn;
84
180
    TxnErrorCode err = txn_kv->create_txn(&txn);
85
180
    if (err != TxnErrorCode::TXN_OK) {
86
0
        return -1;
87
0
    }
88
180
    switch (txn->get(begin, end, &it, true)) {
89
180
    case TxnErrorCode::TXN_OK:
90
180
        return 0;
91
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
92
0
        return 1;
93
0
    default:
94
0
        return -1;
95
180
    };
96
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
82
19
                   std::unique_ptr<RangeGetIterator>& it) {
83
19
    std::unique_ptr<Transaction> txn;
84
19
    TxnErrorCode err = txn_kv->create_txn(&txn);
85
19
    if (err != TxnErrorCode::TXN_OK) {
86
0
        return -1;
87
0
    }
88
19
    switch (txn->get(begin, end, &it, true)) {
89
19
    case TxnErrorCode::TXN_OK:
90
19
        return 0;
91
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
92
0
        return 1;
93
0
    default:
94
0
        return -1;
95
19
    };
96
0
}
97
98
// return 0 for success otherwise error
99
10
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
100
10
    std::unique_ptr<Transaction> txn;
101
10
    TxnErrorCode err = txn_kv->create_txn(&txn);
102
10
    if (err != TxnErrorCode::TXN_OK) {
103
0
        return -1;
104
0
    }
105
3.04k
    for (auto k : keys) {
106
3.04k
        txn->remove(k);
107
3.04k
    }
108
10
    switch (txn->commit()) {
109
10
    case TxnErrorCode::TXN_OK:
110
10
        return 0;
111
0
    case TxnErrorCode::TXN_CONFLICT:
112
0
        return -1;
113
0
    default:
114
0
        return -1;
115
10
    }
116
10
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
99
6
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
100
6
    std::unique_ptr<Transaction> txn;
101
6
    TxnErrorCode err = txn_kv->create_txn(&txn);
102
6
    if (err != TxnErrorCode::TXN_OK) {
103
0
        return -1;
104
0
    }
105
3.02k
    for (auto k : keys) {
106
3.02k
        txn->remove(k);
107
3.02k
    }
108
6
    switch (txn->commit()) {
109
6
    case TxnErrorCode::TXN_OK:
110
6
        return 0;
111
0
    case TxnErrorCode::TXN_CONFLICT:
112
0
        return -1;
113
0
    default:
114
0
        return -1;
115
6
    }
116
6
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
99
4
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
100
4
    std::unique_ptr<Transaction> txn;
101
4
    TxnErrorCode err = txn_kv->create_txn(&txn);
102
4
    if (err != TxnErrorCode::TXN_OK) {
103
0
        return -1;
104
0
    }
105
21
    for (auto k : keys) {
106
21
        txn->remove(k);
107
21
    }
108
4
    switch (txn->commit()) {
109
4
    case TxnErrorCode::TXN_OK:
110
4
        return 0;
111
0
    case TxnErrorCode::TXN_CONFLICT:
112
0
        return -1;
113
0
    default:
114
0
        return -1;
115
4
    }
116
4
}
117
118
// return 0 for success otherwise error
119
30
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
120
30
    std::unique_ptr<Transaction> txn;
121
30
    TxnErrorCode err = txn_kv->create_txn(&txn);
122
30
    if (err != TxnErrorCode::TXN_OK) {
123
0
        return -1;
124
0
    }
125
4.00k
    for (auto& k : keys) {
126
4.00k
        txn->remove(k);
127
4.00k
    }
128
30
    switch (txn->commit()) {
129
30
    case TxnErrorCode::TXN_OK:
130
30
        return 0;
131
0
    case TxnErrorCode::TXN_CONFLICT:
132
0
        return -1;
133
0
    default:
134
0
        return -1;
135
30
    }
136
30
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
119
30
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
120
30
    std::unique_ptr<Transaction> txn;
121
30
    TxnErrorCode err = txn_kv->create_txn(&txn);
122
30
    if (err != TxnErrorCode::TXN_OK) {
123
0
        return -1;
124
0
    }
125
4.00k
    for (auto& k : keys) {
126
4.00k
        txn->remove(k);
127
4.00k
    }
128
30
    switch (txn->commit()) {
129
30
    case TxnErrorCode::TXN_OK:
130
30
        return 0;
131
0
    case TxnErrorCode::TXN_CONFLICT:
132
0
        return -1;
133
0
    default:
134
0
        return -1;
135
30
    }
136
30
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
137
138
// return 0 for success otherwise error
139
[[maybe_unused]] static int txn_remove(TxnKv* txn_kv, std::string_view begin,
140
0
                                       std::string_view end) {
141
0
    std::unique_ptr<Transaction> txn;
142
0
    TxnErrorCode err = txn_kv->create_txn(&txn);
143
0
    if (err != TxnErrorCode::TXN_OK) {
144
0
        return -1;
145
0
    }
146
0
    txn->remove(begin, end);
147
0
    switch (txn->commit()) {
148
0
    case TxnErrorCode::TXN_OK:
149
0
        return 0;
150
0
    case TxnErrorCode::TXN_CONFLICT:
151
0
        return -1;
152
0
    default:
153
0
        return -1;
154
0
    }
155
0
}
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
156
157
static inline void check_recycle_task(const std::string& instance_id, const std::string& task_name,
158
                                      int64_t num_scanned, int64_t num_recycled,
159
29
                                      int64_t start_time) {
160
29
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
161
0
        int64_t cost =
162
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
163
0
        if (cost > config::recycle_task_threshold_seconds) {
164
0
            LOG_INFO("recycle task cost too much time cost={}s", cost)
165
0
                    .tag("instance_id", instance_id)
166
0
                    .tag("task", task_name)
167
0
                    .tag("num_scanned", num_scanned)
168
0
                    .tag("num_recycled", num_recycled);
169
0
        }
170
0
    }
171
29
    return;
172
29
}
recycler_test.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
159
27
                                      int64_t start_time) {
160
27
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
161
0
        int64_t cost =
162
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
163
0
        if (cost > config::recycle_task_threshold_seconds) {
164
0
            LOG_INFO("recycle task cost too much time cost={}s", cost)
165
0
                    .tag("instance_id", instance_id)
166
0
                    .tag("task", task_name)
167
0
                    .tag("num_scanned", num_scanned)
168
0
                    .tag("num_recycled", num_recycled);
169
0
        }
170
0
    }
171
27
    return;
172
27
}
recycler.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
159
2
                                      int64_t start_time) {
160
2
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
161
0
        int64_t cost =
162
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
163
0
        if (cost > config::recycle_task_threshold_seconds) {
164
0
            LOG_INFO("recycle task cost too much time cost={}s", cost)
165
0
                    .tag("instance_id", instance_id)
166
0
                    .tag("task", task_name)
167
0
                    .tag("num_scanned", num_scanned)
168
0
                    .tag("num_recycled", num_recycled);
169
0
        }
170
0
    }
171
2
    return;
172
2
}
173
174
4
Recycler::Recycler(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
175
4
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
176
177
4
    auto s3_producer_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
178
4
                                                               "s3_producer_pool");
179
4
    s3_producer_pool->start();
180
4
    auto recycle_tablet_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
181
4
                                                                  "recycle_tablet_pool");
182
4
    recycle_tablet_pool->start();
183
4
    auto group_recycle_function_pool = std::make_shared<SimpleThreadPool>(
184
4
            config::recycle_pool_parallelism, "group_recycle_function_pool");
185
4
    group_recycle_function_pool->start();
186
4
    _thread_pool_group =
187
4
            RecyclerThreadPoolGroup(std::move(s3_producer_pool), std::move(recycle_tablet_pool),
188
4
                                    std::move(group_recycle_function_pool));
189
190
4
    txn_lazy_committer_ = std::make_shared<TxnLazyCommitter>(txn_kv_);
191
4
}
192
193
4
Recycler::~Recycler() {
194
4
    if (!stopped()) {
195
0
        stop();
196
0
    }
197
4
}
198
199
4
void Recycler::instance_scanner_callback() {
200
    // sleep 60 seconds before scheduling for the launch procedure to complete:
201
    // some bad hdfs connection may cause some log to stdout stderr
202
    // which may pollute .out file and affect the script to check success
203
4
    std::this_thread::sleep_for(
204
4
            std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
205
8
    while (!stopped()) {
206
4
        std::vector<InstanceInfoPB> instances;
207
4
        get_all_instances(txn_kv_.get(), instances);
208
        // TODO(plat1ko): delete job recycle kv of non-existent instances
209
4
        LOG(INFO) << "Recycler get instances: " << [&instances] {
210
4
            std::stringstream ss;
211
30
            for (auto& i : instances) ss << ' ' << i.instance_id();
212
4
            return ss.str();
213
4
        }();
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
Line
Count
Source
209
4
        LOG(INFO) << "Recycler get instances: " << [&instances] {
210
4
            std::stringstream ss;
211
30
            for (auto& i : instances) ss << ' ' << i.instance_id();
212
4
            return ss.str();
213
4
        }();
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
214
4
        if (!instances.empty()) {
215
            // enqueue instances
216
3
            std::lock_guard lock(mtx_);
217
30
            for (auto& instance : instances) {
218
30
                if (instance_filter_.filter_out(instance.instance_id())) continue;
219
30
                auto [_, success] = pending_instance_set_.insert(instance.instance_id());
220
                // skip instance already in pending queue
221
30
                if (success) {
222
30
                    pending_instance_queue_.push_back(std::move(instance));
223
30
                }
224
30
            }
225
3
            pending_instance_cond_.notify_all();
226
3
        }
227
4
        {
228
4
            std::unique_lock lock(mtx_);
229
4
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
230
8
                               [&]() { return stopped(); });
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
230
8
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
231
4
        }
232
4
    }
233
4
}
234
235
8
void Recycler::recycle_callback() {
236
38
    while (!stopped()) {
237
37
        InstanceInfoPB instance;
238
37
        {
239
37
            std::unique_lock lock(mtx_);
240
37
            pending_instance_cond_.wait(
241
50
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
241
50
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
242
37
            if (stopped()) {
243
7
                return;
244
7
            }
245
30
            instance = std::move(pending_instance_queue_.front());
246
30
            pending_instance_queue_.pop_front();
247
30
            pending_instance_set_.erase(instance.instance_id());
248
30
        }
249
0
        auto& instance_id = instance.instance_id();
250
30
        {
251
30
            std::lock_guard lock(mtx_);
252
            // skip instance in recycling
253
30
            if (recycling_instance_map_.count(instance_id)) continue;
254
30
        }
255
30
        auto instance_recycler = std::make_shared<InstanceRecycler>(
256
30
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
257
258
30
        if (int r = instance_recycler->init(); r != 0) {
259
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
260
0
                         << " ret=" << r;
261
0
            continue;
262
0
        }
263
30
        std::string recycle_job_key;
264
30
        job_recycle_key({instance_id}, &recycle_job_key);
265
30
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
266
30
                                               ip_port_, config::recycle_interval_seconds * 1000);
267
30
        if (ret != 0) { // Prepare failed
268
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
269
20
                         << " ret=" << ret;
270
20
            continue;
271
20
        } else {
272
10
            std::lock_guard lock(mtx_);
273
10
            recycling_instance_map_.emplace(instance_id, instance_recycler);
274
10
        }
275
10
        if (stopped()) return;
276
10
        LOG_INFO("begin to recycle instance").tag("instance_id", instance_id);
277
10
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
278
10
        ret = instance_recycler->do_recycle();
279
        // If instance recycler has been aborted, don't finish this job
280
10
        if (!instance_recycler->stopped()) {
281
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
282
10
                                        ret == 0, ctime_ms);
283
10
        }
284
10
        {
285
10
            std::lock_guard lock(mtx_);
286
10
            recycling_instance_map_.erase(instance_id);
287
10
        }
288
10
        auto elpased_ms =
289
10
                duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count() -
290
10
                ctime_ms;
291
10
        LOG_INFO("finish recycle instance")
292
10
                .tag("instance_id", instance_id)
293
10
                .tag("cost_ms", elpased_ms);
294
10
    }
295
8
}
296
297
4
void Recycler::lease_recycle_jobs() {
298
54
    while (!stopped()) {
299
50
        std::vector<std::string> instances;
300
50
        instances.reserve(recycling_instance_map_.size());
301
50
        {
302
50
            std::lock_guard lock(mtx_);
303
50
            for (auto& [id, _] : recycling_instance_map_) {
304
30
                instances.push_back(id);
305
30
            }
306
50
        }
307
50
        for (auto& i : instances) {
308
30
            std::string recycle_job_key;
309
30
            job_recycle_key({i}, &recycle_job_key);
310
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
311
30
            if (ret == 1) {
312
0
                std::lock_guard lock(mtx_);
313
0
                if (auto it = recycling_instance_map_.find(i);
314
0
                    it != recycling_instance_map_.end()) {
315
0
                    it->second->stop();
316
0
                }
317
0
            }
318
30
        }
319
50
        {
320
50
            std::unique_lock lock(mtx_);
321
50
            notifier_.wait_for(lock,
322
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
323
100
                               [&]() { return stopped(); });
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
323
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
324
50
        }
325
50
    }
326
4
}
327
328
4
void Recycler::check_recycle_tasks() {
329
7
    while (!stopped()) {
330
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
331
3
        {
332
3
            std::lock_guard lock(mtx_);
333
3
            recycling_instance_map = recycling_instance_map_;
334
3
        }
335
3
        for (auto& entry : recycling_instance_map) {
336
0
            entry.second->check_recycle_tasks();
337
0
        }
338
339
3
        std::unique_lock lock(mtx_);
340
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
341
6
                           [&]() { return stopped(); });
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
341
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
342
3
    }
343
4
}
344
345
4
int Recycler::start(brpc::Server* server) {
346
4
    instance_filter_.reset(config::recycle_whitelist, config::recycle_blacklist);
347
348
4
    if (config::enable_checker) {
349
0
        checker_ = std::make_unique<Checker>(txn_kv_);
350
0
        int ret = checker_->start();
351
0
        std::string msg;
352
0
        if (ret != 0) {
353
0
            msg = "failed to start checker";
354
0
            LOG(ERROR) << msg;
355
0
            std::cerr << msg << std::endl;
356
0
            return ret;
357
0
        }
358
0
        msg = "checker started";
359
0
        LOG(INFO) << msg;
360
0
        std::cout << msg << std::endl;
361
0
    }
362
363
4
    if (server) {
364
        // Add service
365
1
        auto recycler_service =
366
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
367
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
368
1
    }
369
370
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
370
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
371
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
372
8
        workers_.emplace_back([this] { recycle_callback(); });
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
372
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
373
8
    }
374
375
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
376
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
377
4
    return 0;
378
4
}
379
380
4
void Recycler::stop() {
381
4
    stopped_ = true;
382
4
    notifier_.notify_all();
383
4
    pending_instance_cond_.notify_all();
384
4
    {
385
4
        std::lock_guard lock(mtx_);
386
4
        for (auto& [_, recycler] : recycling_instance_map_) {
387
0
            recycler->stop();
388
0
        }
389
4
    }
390
20
    for (auto& w : workers_) {
391
20
        if (w.joinable()) w.join();
392
20
    }
393
4
    if (checker_) {
394
0
        checker_->stop();
395
0
    }
396
4
}
397
398
class InstanceRecycler::InvertedIndexIdCache {
399
public:
400
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
401
73
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
402
403
    // Return 0 if success, 1 if schema kv not found, negative for error
404
3.55k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
405
3.55k
        {
406
3.55k
            std::lock_guard lock(mtx_);
407
3.55k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
408
644
                return 0;
409
644
            }
410
2.90k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
411
2.90k
                it != inverted_index_id_map_.end()) {
412
2.37k
                res = it->second;
413
2.37k
                return 0;
414
2.37k
            }
415
2.90k
        }
416
        // Get schema from kv
417
        // TODO(plat1ko): Single flight
418
532
        std::unique_ptr<Transaction> txn;
419
532
        TxnErrorCode err = txn_kv_->create_txn(&txn);
420
532
        if (err != TxnErrorCode::TXN_OK) {
421
0
            LOG(WARNING) << "failed to create txn, err=" << err;
422
0
            return -1;
423
0
        }
424
532
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
425
532
        ValueBuf val_buf;
426
532
        err = cloud::get(txn.get(), schema_key, &val_buf);
427
532
        if (err != TxnErrorCode::TXN_OK) {
428
500
            LOG(WARNING) << "failed to get schema, err=" << err;
429
500
            return static_cast<int>(err);
430
500
        }
431
32
        doris::TabletSchemaCloudPB schema;
432
32
        if (!parse_schema_value(val_buf, &schema)) {
433
0
            LOG(WARNING) << "malformed schema value, key=" << hex(schema_key);
434
0
            return -1;
435
0
        }
436
32
        if (schema.index_size() > 0) {
437
26
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
438
26
            if (schema.has_inverted_index_storage_format()) {
439
23
                index_format = schema.inverted_index_storage_format();
440
23
            }
441
26
            res.first = index_format;
442
26
            res.second.reserve(schema.index_size());
443
62
            for (auto& i : schema.index()) {
444
62
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
445
62
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
446
62
                }
447
62
            }
448
26
        }
449
32
        insert(index_id, schema_version, res);
450
32
        return 0;
451
32
    }
452
453
    // Empty `ids` means this schema has no inverted index
454
32
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
455
32
        if (index_info.second.empty()) {
456
6
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
457
6
            std::lock_guard lock(mtx_);
458
6
            schemas_without_inverted_index_.emplace(index_id, schema_version);
459
26
        } else {
460
26
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
461
26
            std::lock_guard lock(mtx_);
462
26
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
463
26
        }
464
32
    }
465
466
private:
467
    std::string instance_id_;
468
    std::shared_ptr<TxnKv> txn_kv_;
469
470
    std::mutex mtx_;
471
    using Key = std::pair<int64_t, int32_t>; // <index_id, schema_version>
472
    struct HashOfKey {
473
6.49k
        size_t operator()(const Key& key) const {
474
6.49k
            size_t seed = 0;
475
6.49k
            seed = std::hash<int64_t> {}(key.first);
476
6.49k
            seed = std::hash<int32_t> {}(key.second);
477
6.49k
            return seed;
478
6.49k
        }
479
    };
480
    // <index_id, schema_version> -> inverted_index_ids
481
    std::unordered_map<Key, InvertedIndexInfo, HashOfKey> inverted_index_id_map_;
482
    // Store <index_id, schema_version> of schema which doesn't have inverted index
483
    std::unordered_set<Key, HashOfKey> schemas_without_inverted_index_;
484
};
485
486
InstanceRecycler::InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
487
                                   RecyclerThreadPoolGroup thread_pool_group,
488
                                   std::shared_ptr<TxnLazyCommitter> txn_lazy_committer)
489
        : txn_kv_(std::move(txn_kv)),
490
          instance_id_(instance.instance_id()),
491
          instance_info_(instance),
492
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
493
          _thread_pool_group(std::move(thread_pool_group)),
494
73
          txn_lazy_committer_(std::move(txn_lazy_committer)) {};
495
496
73
InstanceRecycler::~InstanceRecycler() = default;
497
498
73
int InstanceRecycler::init_obj_store_accessors() {
499
73
    for (const auto& obj_info : instance_info_.obj_info()) {
500
54
#ifdef UNIT_TEST
501
54
        auto accessor = std::make_shared<MockAccessor>();
502
#else
503
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
504
        if (!s3_conf) {
505
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
506
            return -1;
507
        }
508
509
        std::shared_ptr<S3Accessor> accessor;
510
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
511
        if (ret != 0) {
512
            LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
513
                         << " resource_id=" << obj_info.id();
514
            return ret;
515
        }
516
#endif
517
54
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
518
54
    }
519
520
73
    return 0;
521
73
}
522
523
73
int InstanceRecycler::init_storage_vault_accessors() {
524
73
    if (instance_info_.resource_ids().empty()) {
525
66
        return 0;
526
66
    }
527
528
7
    FullRangeGetIteratorOptions opts(txn_kv_);
529
7
    opts.prefetch = true;
530
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
531
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
532
533
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
534
18
        auto [k, v] = *kv;
535
18
        StorageVaultPB vault;
536
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
537
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
538
0
            return -1;
539
0
        }
540
18
        std::string recycler_storage_vault_white_list = accumulate(
541
18
                config::recycler_storage_vault_white_list.begin(),
542
18
                config::recycler_storage_vault_white_list.end(), std::string(),
543
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
543
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
544
18
        LOG_INFO("config::recycler_storage_vault_white_list")
545
18
                .tag("", recycler_storage_vault_white_list);
546
18
        if (!config::recycler_storage_vault_white_list.empty()) {
547
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
548
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
549
8
                it == config::recycler_storage_vault_white_list.end()) {
550
2
                LOG_WARNING(
551
2
                        "failed to init accessor for vault because this vault is not in "
552
2
                        "config::recycler_storage_vault_white_list. ")
553
2
                        .tag(" vault name:", vault.name())
554
2
                        .tag(" config::recycler_storage_vault_white_list:",
555
2
                             recycler_storage_vault_white_list);
556
2
                continue;
557
2
            }
558
8
        }
559
16
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
560
16
                                 &accessor_map_, &vault);
561
16
        if (vault.has_hdfs_info()) {
562
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
563
9
            int ret = accessor->init();
564
9
            if (ret != 0) {
565
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
566
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
567
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
568
4
                continue;
569
4
            }
570
5
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
571
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
572
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
573
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
574
7
        } else if (vault.has_obj_info()) {
575
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
576
7
            if (!s3_conf) {
577
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
578
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
579
1
                continue;
580
1
            }
581
582
6
            std::shared_ptr<S3Accessor> accessor;
583
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
584
6
            if (ret != 0) {
585
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
586
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
587
0
                             << " ret=" << ret
588
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
589
0
                continue;
590
0
            }
591
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
592
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
593
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
594
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
595
6
        }
596
16
    }
597
598
7
    if (!it->is_valid()) {
599
0
        LOG_WARNING("failed to get storage vault kv");
600
0
        return -1;
601
0
    }
602
603
7
    if (accessor_map_.empty()) {
604
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
605
1
        return -2;
606
1
    }
607
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
608
6
             instance_id_);
609
610
6
    return 0;
611
7
}
612
613
73
int InstanceRecycler::init() {
614
73
    int ret = init_obj_store_accessors();
615
73
    if (ret != 0) {
616
0
        return ret;
617
0
    }
618
619
73
    return init_storage_vault_accessors();
620
73
}
621
622
template <typename... Func>
623
80
auto task_wrapper(Func... funcs) -> std::function<int()> {
624
80
    return [funcs...]() {
625
80
        return [](std::initializer_list<int> ret_vals) {
626
80
            int i = 0;
627
100
            for (int ret : ret_vals) {
628
100
                if (ret != 0) {
629
0
                    i = ret;
630
0
                }
631
100
            }
632
80
            return i;
633
80
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_1ZNS2_10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
20
            for (int ret : ret_vals) {
628
20
                if (ret != 0) {
629
0
                    i = ret;
630
0
                }
631
20
            }
632
10
            return i;
633
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
10
            for (int ret : ret_vals) {
628
10
                if (ret != 0) {
629
0
                    i = ret;
630
0
                }
631
10
            }
632
10
            return i;
633
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
10
            for (int ret : ret_vals) {
628
10
                if (ret != 0) {
629
0
                    i = ret;
630
0
                }
631
10
            }
632
10
            return i;
633
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_5ZNS2_10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
20
            for (int ret : ret_vals) {
628
20
                if (ret != 0) {
629
0
                    i = ret;
630
0
                }
631
20
            }
632
10
            return i;
633
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
10
            for (int ret : ret_vals) {
628
10
                if (ret != 0) {
629
0
                    i = ret;
630
0
                }
631
10
            }
632
10
            return i;
633
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
10
            for (int ret : ret_vals) {
628
10
                if (ret != 0) {
629
0
                    i = ret;
630
0
                }
631
10
            }
632
10
            return i;
633
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
10
            for (int ret : ret_vals) {
628
10
                if (ret != 0) {
629
0
                    i = ret;
630
0
                }
631
10
            }
632
10
            return i;
633
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
10
            for (int ret : ret_vals) {
628
10
                if (ret != 0) {
629
0
                    i = ret;
630
0
                }
631
10
            }
632
10
            return i;
633
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_
634
80
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_1ZNS2_10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
624
10
    return [funcs...]() {
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
10
            for (int ret : ret_vals) {
628
10
                if (ret != 0) {
629
10
                    i = ret;
630
10
                }
631
10
            }
632
10
            return i;
633
10
        }({funcs()...});
634
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
624
10
    return [funcs...]() {
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
10
            for (int ret : ret_vals) {
628
10
                if (ret != 0) {
629
10
                    i = ret;
630
10
                }
631
10
            }
632
10
            return i;
633
10
        }({funcs()...});
634
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
624
10
    return [funcs...]() {
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
10
            for (int ret : ret_vals) {
628
10
                if (ret != 0) {
629
10
                    i = ret;
630
10
                }
631
10
            }
632
10
            return i;
633
10
        }({funcs()...});
634
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_5ZNS2_10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
624
10
    return [funcs...]() {
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
10
            for (int ret : ret_vals) {
628
10
                if (ret != 0) {
629
10
                    i = ret;
630
10
                }
631
10
            }
632
10
            return i;
633
10
        }({funcs()...});
634
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
624
10
    return [funcs...]() {
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
10
            for (int ret : ret_vals) {
628
10
                if (ret != 0) {
629
10
                    i = ret;
630
10
                }
631
10
            }
632
10
            return i;
633
10
        }({funcs()...});
634
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
624
10
    return [funcs...]() {
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
10
            for (int ret : ret_vals) {
628
10
                if (ret != 0) {
629
10
                    i = ret;
630
10
                }
631
10
            }
632
10
            return i;
633
10
        }({funcs()...});
634
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
624
10
    return [funcs...]() {
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
10
            for (int ret : ret_vals) {
628
10
                if (ret != 0) {
629
10
                    i = ret;
630
10
                }
631
10
            }
632
10
            return i;
633
10
        }({funcs()...});
634
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
624
10
    return [funcs...]() {
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
10
            for (int ret : ret_vals) {
628
10
                if (ret != 0) {
629
10
                    i = ret;
630
10
                }
631
10
            }
632
10
            return i;
633
10
        }({funcs()...});
634
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
635
80
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_1ZNS2_10do_recycleEvE3$_2EEESt8functionIFivEEDpT_
Line
Count
Source
623
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
624
10
    return [funcs...]() {
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
10
            for (int ret : ret_vals) {
628
10
                if (ret != 0) {
629
10
                    i = ret;
630
10
                }
631
10
            }
632
10
            return i;
633
10
        }({funcs()...});
634
10
    };
635
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
623
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
624
10
    return [funcs...]() {
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
10
            for (int ret : ret_vals) {
628
10
                if (ret != 0) {
629
10
                    i = ret;
630
10
                }
631
10
            }
632
10
            return i;
633
10
        }({funcs()...});
634
10
    };
635
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4EEESt8functionIFivEEDpT_
Line
Count
Source
623
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
624
10
    return [funcs...]() {
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
10
            for (int ret : ret_vals) {
628
10
                if (ret != 0) {
629
10
                    i = ret;
630
10
                }
631
10
            }
632
10
            return i;
633
10
        }({funcs()...});
634
10
    };
635
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_5ZNS2_10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
623
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
624
10
    return [funcs...]() {
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
10
            for (int ret : ret_vals) {
628
10
                if (ret != 0) {
629
10
                    i = ret;
630
10
                }
631
10
            }
632
10
            return i;
633
10
        }({funcs()...});
634
10
    };
635
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
623
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
624
10
    return [funcs...]() {
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
10
            for (int ret : ret_vals) {
628
10
                if (ret != 0) {
629
10
                    i = ret;
630
10
                }
631
10
            }
632
10
            return i;
633
10
        }({funcs()...});
634
10
    };
635
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
623
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
624
10
    return [funcs...]() {
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
10
            for (int ret : ret_vals) {
628
10
                if (ret != 0) {
629
10
                    i = ret;
630
10
                }
631
10
            }
632
10
            return i;
633
10
        }({funcs()...});
634
10
    };
635
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9EEESt8functionIFivEEDpT_
Line
Count
Source
623
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
624
10
    return [funcs...]() {
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
10
            for (int ret : ret_vals) {
628
10
                if (ret != 0) {
629
10
                    i = ret;
630
10
                }
631
10
            }
632
10
            return i;
633
10
        }({funcs()...});
634
10
    };
635
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
623
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
624
10
    return [funcs...]() {
625
10
        return [](std::initializer_list<int> ret_vals) {
626
10
            int i = 0;
627
10
            for (int ret : ret_vals) {
628
10
                if (ret != 0) {
629
10
                    i = ret;
630
10
                }
631
10
            }
632
10
            return i;
633
10
        }({funcs()...});
634
10
    };
635
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_
636
637
10
int InstanceRecycler::do_recycle() {
638
10
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
639
10
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
640
0
        return recycle_deleted_instance();
641
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
642
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
643
10
                                        fmt::format("instance id {}", instance_id_),
644
80
                                        [](int r) { return r != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEi
Line
Count
Source
644
80
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEi
645
10
        sync_executor
646
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
647
                                   // becase they may both recycle the same set of tablets
648
                        // recycle dropped table or idexes(mv, rollup)
649
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEv
Line
Count
Source
649
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEv
650
                        // recycle dropped partitions
651
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
651
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
652
10
                .add(task_wrapper(
653
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_3clEv
Line
Count
Source
653
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_3clEv
654
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
654
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
655
10
                .add(task_wrapper(
656
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
656
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
657
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
657
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
658
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_7clEv
Line
Count
Source
658
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_7clEv
659
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
659
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
660
10
                .add(task_wrapper(
661
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
661
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
662
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }));
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
662
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }));
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
663
10
        bool finished = true;
664
10
        std::vector<int> rets = sync_executor.when_all(&finished);
665
80
        for (int ret : rets) {
666
80
            if (ret != 0) {
667
0
                return ret;
668
0
            }
669
80
        }
670
10
        return finished ? 0 : -1;
671
10
    } else {
672
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
673
0
                     << " instance_id=" << instance_id_;
674
0
        return -1;
675
0
    }
676
10
}
677
678
/**
679
 * 1. delete all remote data
680
 * 2. delete all kv
681
 * 3. remove instance kv
682
 */
683
1
int InstanceRecycler::recycle_deleted_instance() {
684
1
    LOG_INFO("begin to recycle deleted instance").tag("instance_id", instance_id_);
685
686
1
    int ret = 0;
687
1
    auto start_time = steady_clock::now();
688
689
1
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
690
1
        auto cost = duration<float>(steady_clock::now() - start_time).count();
691
1
        LOG(INFO) << (ret == 0 ? "successfully" : "failed to")
692
1
                  << " recycle deleted instance, cost=" << cost
693
1
                  << "s, instance_id=" << instance_id_;
694
1
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEPi
Line
Count
Source
689
1
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
690
1
        auto cost = duration<float>(steady_clock::now() - start_time).count();
691
1
        LOG(INFO) << (ret == 0 ? "successfully" : "failed to")
692
1
                  << " recycle deleted instance, cost=" << cost
693
1
                  << "s, instance_id=" << instance_id_;
694
1
    });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEPi
695
696
    // delete all remote data
697
2
    for (auto& [_, accessor] : accessor_map_) {
698
2
        if (stopped()) {
699
0
            return ret;
700
0
        }
701
702
2
        LOG(INFO) << "begin to delete all objects in " << accessor->uri();
703
2
        int del_ret = accessor->delete_all();
704
2
        if (del_ret == 0) {
705
2
            LOG(INFO) << "successfully delete all objects in " << accessor->uri();
706
2
        } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
707
            // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
708
            // so the recycling has been successful.
709
0
            ret = -1;
710
0
        }
711
2
    }
712
713
1
    if (ret != 0) {
714
0
        LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
715
0
        return ret;
716
0
    }
717
718
    // delete all kv
719
1
    std::unique_ptr<Transaction> txn;
720
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
721
1
    if (err != TxnErrorCode::TXN_OK) {
722
0
        LOG(WARNING) << "failed to create txn";
723
0
        ret = -1;
724
0
        return -1;
725
0
    }
726
1
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
727
    // delete kv before deleting objects to prevent the checker from misjudging data loss
728
1
    std::string start_txn_key = txn_key_prefix(instance_id_);
729
1
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
730
1
    txn->remove(start_txn_key, end_txn_key);
731
1
    std::string start_version_key = version_key_prefix(instance_id_);
732
1
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
733
1
    txn->remove(start_version_key, end_version_key);
734
1
    std::string start_meta_key = meta_key_prefix(instance_id_);
735
1
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
736
1
    txn->remove(start_meta_key, end_meta_key);
737
1
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
738
1
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
739
1
    txn->remove(start_recycle_key, end_recycle_key);
740
1
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
741
1
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
742
1
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
743
1
    std::string start_copy_key = copy_key_prefix(instance_id_);
744
1
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
745
1
    txn->remove(start_copy_key, end_copy_key);
746
    // should not remove job key range, because we need to reserve job recycle kv
747
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
748
1
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
749
1
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
750
1
    txn->remove(start_job_tablet_key, end_job_tablet_key);
751
1
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
752
1
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
753
1
    std::string start_vault_key = storage_vault_key(key_info0);
754
1
    std::string end_vault_key = storage_vault_key(key_info1);
755
1
    txn->remove(start_vault_key, end_vault_key);
756
1
    err = txn->commit();
757
1
    if (err != TxnErrorCode::TXN_OK) {
758
0
        LOG(WARNING) << "failed to delete all kv, instance_id=" << instance_id_ << ", err=" << err;
759
0
        ret = -1;
760
0
    }
761
762
1
    if (ret == 0) {
763
        // remove instance kv
764
        // ATTN: MUST ensure that cloud platform won't regenerate the same instance id
765
1
        err = txn_kv_->create_txn(&txn);
766
1
        if (err != TxnErrorCode::TXN_OK) {
767
0
            LOG(WARNING) << "failed to create txn";
768
0
            ret = -1;
769
0
            return ret;
770
0
        }
771
1
        std::string key;
772
1
        instance_key({instance_id_}, &key);
773
1
        txn->remove(key);
774
1
        err = txn->commit();
775
1
        if (err != TxnErrorCode::TXN_OK) {
776
0
            LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
777
0
                         << " err=" << err;
778
0
            ret = -1;
779
0
        }
780
1
    }
781
1
    return ret;
782
1
}
783
784
14
int InstanceRecycler::recycle_indexes() {
785
14
    const std::string task_name = "recycle_indexes";
786
14
    int64_t num_scanned = 0;
787
14
    int64_t num_expired = 0;
788
14
    int64_t num_recycled = 0;
789
790
14
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
791
14
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
792
14
    std::string index_key0;
793
14
    std::string index_key1;
794
14
    recycle_index_key(index_key_info0, &index_key0);
795
14
    recycle_index_key(index_key_info1, &index_key1);
796
797
14
    LOG_INFO("begin to recycle indexes").tag("instance_id", instance_id_);
798
799
14
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
800
14
    register_recycle_task(task_name, start_time);
801
802
14
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
803
14
        unregister_recycle_task(task_name);
804
14
        int64_t cost =
805
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
806
14
        LOG_INFO("recycle indexes finished, cost={}s", cost)
807
14
                .tag("instance_id", instance_id_)
808
14
                .tag("num_scanned", num_scanned)
809
14
                .tag("num_expired", num_expired)
810
14
                .tag("num_recycled", num_recycled);
811
14
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEPi
Line
Count
Source
802
12
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
803
12
        unregister_recycle_task(task_name);
804
12
        int64_t cost =
805
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
806
12
        LOG_INFO("recycle indexes finished, cost={}s", cost)
807
12
                .tag("instance_id", instance_id_)
808
12
                .tag("num_scanned", num_scanned)
809
12
                .tag("num_expired", num_expired)
810
12
                .tag("num_recycled", num_recycled);
811
12
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEPi
Line
Count
Source
802
2
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
803
2
        unregister_recycle_task(task_name);
804
2
        int64_t cost =
805
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
806
2
        LOG_INFO("recycle indexes finished, cost={}s", cost)
807
2
                .tag("instance_id", instance_id_)
808
2
                .tag("num_scanned", num_scanned)
809
2
                .tag("num_expired", num_expired)
810
2
                .tag("num_recycled", num_recycled);
811
2
    });
812
813
14
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
814
815
14
    auto calc_expiration = [&earlest_ts, this](const RecycleIndexPB& index) {
816
8
        if (config::force_immediate_recycle) {
817
2
            return 0L;
818
2
        }
819
6
        int64_t expiration = index.expiration() > 0 ? index.expiration() : index.creation_time();
820
6
        int64_t retention_seconds = config::retention_seconds;
821
6
        if (index.state() == RecycleIndexPB::DROPPED) {
822
6
            retention_seconds =
823
6
                    std::min(config::dropped_index_retention_seconds, retention_seconds);
824
6
        }
825
6
        int64_t final_expiration = expiration + retention_seconds;
826
6
        if (earlest_ts > final_expiration) {
827
2
            earlest_ts = final_expiration;
828
2
            g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, earlest_ts);
829
2
        }
830
6
        return final_expiration;
831
8
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_3clERKNS0_14RecycleIndexPBE
Line
Count
Source
815
6
    auto calc_expiration = [&earlest_ts, this](const RecycleIndexPB& index) {
816
6
        if (config::force_immediate_recycle) {
817
0
            return 0L;
818
0
        }
819
6
        int64_t expiration = index.expiration() > 0 ? index.expiration() : index.creation_time();
820
6
        int64_t retention_seconds = config::retention_seconds;
821
6
        if (index.state() == RecycleIndexPB::DROPPED) {
822
6
            retention_seconds =
823
6
                    std::min(config::dropped_index_retention_seconds, retention_seconds);
824
6
        }
825
6
        int64_t final_expiration = expiration + retention_seconds;
826
6
        if (earlest_ts > final_expiration) {
827
2
            earlest_ts = final_expiration;
828
2
            g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, earlest_ts);
829
2
        }
830
6
        return final_expiration;
831
6
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_3clERKNS0_14RecycleIndexPBE
Line
Count
Source
815
2
    auto calc_expiration = [&earlest_ts, this](const RecycleIndexPB& index) {
816
2
        if (config::force_immediate_recycle) {
817
2
            return 0L;
818
2
        }
819
0
        int64_t expiration = index.expiration() > 0 ? index.expiration() : index.creation_time();
820
0
        int64_t retention_seconds = config::retention_seconds;
821
0
        if (index.state() == RecycleIndexPB::DROPPED) {
822
0
            retention_seconds =
823
0
                    std::min(config::dropped_index_retention_seconds, retention_seconds);
824
0
        }
825
0
        int64_t final_expiration = expiration + retention_seconds;
826
0
        if (earlest_ts > final_expiration) {
827
0
            earlest_ts = final_expiration;
828
0
            g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, earlest_ts);
829
0
        }
830
0
        return final_expiration;
831
2
    };
832
833
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
834
14
    std::vector<std::string_view> index_keys;
835
14
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
836
8
        ++num_scanned;
837
8
        RecycleIndexPB index_pb;
838
8
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
839
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
840
0
            return -1;
841
0
        }
842
8
        int64_t current_time = ::time(nullptr);
843
8
        if (current_time < calc_expiration(index_pb)) { // not expired
844
0
            return 0;
845
0
        }
846
8
        ++num_expired;
847
        // decode index_id
848
8
        auto k1 = k;
849
8
        k1.remove_prefix(1);
850
8
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
851
8
        decode_key(&k1, &out);
852
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
853
8
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
854
8
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
855
8
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
856
8
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
857
        // Change state to RECYCLING
858
8
        std::unique_ptr<Transaction> txn;
859
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
860
8
        if (err != TxnErrorCode::TXN_OK) {
861
0
            LOG_WARNING("failed to create txn").tag("err", err);
862
0
            return -1;
863
0
        }
864
8
        std::string val;
865
8
        err = txn->get(k, &val);
866
8
        if (err ==
867
8
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
868
0
            LOG_INFO("index {} has been recycled or committed", index_id);
869
0
            return 0;
870
0
        }
871
8
        if (err != TxnErrorCode::TXN_OK) {
872
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
873
0
            return -1;
874
0
        }
875
8
        index_pb.Clear();
876
8
        if (!index_pb.ParseFromString(val)) {
877
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
878
0
            return -1;
879
0
        }
880
8
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
881
7
            index_pb.set_state(RecycleIndexPB::RECYCLING);
882
7
            txn->put(k, index_pb.SerializeAsString());
883
7
            err = txn->commit();
884
7
            if (err != TxnErrorCode::TXN_OK) {
885
0
                LOG_WARNING("failed to commit txn").tag("err", err);
886
0
                return -1;
887
0
            }
888
7
        }
889
8
        if (recycle_tablets(index_pb.table_id(), index_id) != 0) {
890
1
            LOG_WARNING("failed to recycle tablets under index")
891
1
                    .tag("table_id", index_pb.table_id())
892
1
                    .tag("instance_id", instance_id_)
893
1
                    .tag("index_id", index_id);
894
1
            return -1;
895
1
        }
896
7
        ++num_recycled;
897
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
898
7
        index_keys.push_back(k);
899
7
        return 0;
900
8
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
835
6
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
836
6
        ++num_scanned;
837
6
        RecycleIndexPB index_pb;
838
6
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
839
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
840
0
            return -1;
841
0
        }
842
6
        int64_t current_time = ::time(nullptr);
843
6
        if (current_time < calc_expiration(index_pb)) { // not expired
844
0
            return 0;
845
0
        }
846
6
        ++num_expired;
847
        // decode index_id
848
6
        auto k1 = k;
849
6
        k1.remove_prefix(1);
850
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
851
6
        decode_key(&k1, &out);
852
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
853
6
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
854
6
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
855
6
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
856
6
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
857
        // Change state to RECYCLING
858
6
        std::unique_ptr<Transaction> txn;
859
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
860
6
        if (err != TxnErrorCode::TXN_OK) {
861
0
            LOG_WARNING("failed to create txn").tag("err", err);
862
0
            return -1;
863
0
        }
864
6
        std::string val;
865
6
        err = txn->get(k, &val);
866
6
        if (err ==
867
6
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
868
0
            LOG_INFO("index {} has been recycled or committed", index_id);
869
0
            return 0;
870
0
        }
871
6
        if (err != TxnErrorCode::TXN_OK) {
872
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
873
0
            return -1;
874
0
        }
875
6
        index_pb.Clear();
876
6
        if (!index_pb.ParseFromString(val)) {
877
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
878
0
            return -1;
879
0
        }
880
6
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
881
6
            index_pb.set_state(RecycleIndexPB::RECYCLING);
882
6
            txn->put(k, index_pb.SerializeAsString());
883
6
            err = txn->commit();
884
6
            if (err != TxnErrorCode::TXN_OK) {
885
0
                LOG_WARNING("failed to commit txn").tag("err", err);
886
0
                return -1;
887
0
            }
888
6
        }
889
6
        if (recycle_tablets(index_pb.table_id(), index_id) != 0) {
890
0
            LOG_WARNING("failed to recycle tablets under index")
891
0
                    .tag("table_id", index_pb.table_id())
892
0
                    .tag("instance_id", instance_id_)
893
0
                    .tag("index_id", index_id);
894
0
            return -1;
895
0
        }
896
6
        ++num_recycled;
897
6
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
898
6
        index_keys.push_back(k);
899
6
        return 0;
900
6
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
835
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
836
2
        ++num_scanned;
837
2
        RecycleIndexPB index_pb;
838
2
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
839
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
840
0
            return -1;
841
0
        }
842
2
        int64_t current_time = ::time(nullptr);
843
2
        if (current_time < calc_expiration(index_pb)) { // not expired
844
0
            return 0;
845
0
        }
846
2
        ++num_expired;
847
        // decode index_id
848
2
        auto k1 = k;
849
2
        k1.remove_prefix(1);
850
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
851
2
        decode_key(&k1, &out);
852
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
853
2
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
854
2
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
855
2
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
856
2
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
857
        // Change state to RECYCLING
858
2
        std::unique_ptr<Transaction> txn;
859
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
860
2
        if (err != TxnErrorCode::TXN_OK) {
861
0
            LOG_WARNING("failed to create txn").tag("err", err);
862
0
            return -1;
863
0
        }
864
2
        std::string val;
865
2
        err = txn->get(k, &val);
866
2
        if (err ==
867
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
868
0
            LOG_INFO("index {} has been recycled or committed", index_id);
869
0
            return 0;
870
0
        }
871
2
        if (err != TxnErrorCode::TXN_OK) {
872
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
873
0
            return -1;
874
0
        }
875
2
        index_pb.Clear();
876
2
        if (!index_pb.ParseFromString(val)) {
877
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
878
0
            return -1;
879
0
        }
880
2
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
881
1
            index_pb.set_state(RecycleIndexPB::RECYCLING);
882
1
            txn->put(k, index_pb.SerializeAsString());
883
1
            err = txn->commit();
884
1
            if (err != TxnErrorCode::TXN_OK) {
885
0
                LOG_WARNING("failed to commit txn").tag("err", err);
886
0
                return -1;
887
0
            }
888
1
        }
889
2
        if (recycle_tablets(index_pb.table_id(), index_id) != 0) {
890
1
            LOG_WARNING("failed to recycle tablets under index")
891
1
                    .tag("table_id", index_pb.table_id())
892
1
                    .tag("instance_id", instance_id_)
893
1
                    .tag("index_id", index_id);
894
1
            return -1;
895
1
        }
896
1
        ++num_recycled;
897
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
898
1
        index_keys.push_back(k);
899
1
        return 0;
900
2
    };
901
902
14
    auto loop_done = [&index_keys, this]() -> int {
903
4
        if (index_keys.empty()) return 0;
904
3
        std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01,
905
3
                                                              [&](int*) { index_keys.clear(); });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clEvENKUlPiE_clES3_
Line
Count
Source
905
2
                                                              [&](int*) { index_keys.clear(); });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clEvENKUlPiE_clES3_
Line
Count
Source
905
1
                                                              [&](int*) { index_keys.clear(); });
906
3
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
907
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
908
0
            return -1;
909
0
        }
910
3
        return 0;
911
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clEv
Line
Count
Source
902
2
    auto loop_done = [&index_keys, this]() -> int {
903
2
        if (index_keys.empty()) return 0;
904
2
        std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01,
905
2
                                                              [&](int*) { index_keys.clear(); });
906
2
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
907
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
908
0
            return -1;
909
0
        }
910
2
        return 0;
911
2
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clEv
Line
Count
Source
902
2
    auto loop_done = [&index_keys, this]() -> int {
903
2
        if (index_keys.empty()) return 0;
904
1
        std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01,
905
1
                                                              [&](int*) { index_keys.clear(); });
906
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
907
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
908
0
            return -1;
909
0
        }
910
1
        return 0;
911
1
    };
912
913
14
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
914
14
}
915
916
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
917
271
                             int64_t tablet_id) {
918
271
    std::unique_ptr<Transaction> txn;
919
271
    TxnErrorCode err = txn_kv->create_txn(&txn);
920
271
    if (err != TxnErrorCode::TXN_OK) {
921
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
922
0
                     << " tablet_id=" << tablet_id << " err=" << err;
923
0
        return false;
924
0
    }
925
926
271
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
927
271
    std::string tablet_idx_val;
928
271
    err = txn->get(tablet_idx_key, &tablet_idx_val);
929
271
    if (TxnErrorCode::TXN_OK != err) {
930
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
931
0
                     << " tablet_id=" << tablet_id << " err=" << err
932
0
                     << " key=" << hex(tablet_idx_key);
933
0
        return false;
934
0
    }
935
936
271
    TabletIndexPB tablet_idx_pb;
937
271
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
938
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
939
0
                     << " tablet_id=" << tablet_id;
940
0
        return false;
941
0
    }
942
943
271
    if (!tablet_idx_pb.has_db_id()) {
944
        // In the previous version, the db_id was not set in the index_pb.
945
        // If updating to the version which enable txn lazy commit, the db_id will be set.
946
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
947
0
                  << " instance_id=" << instance_id
948
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
949
0
        return true;
950
0
    }
951
952
271
    std::string ver_val;
953
271
    std::string ver_key =
954
271
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
955
271
                                   tablet_idx_pb.partition_id()});
956
271
    err = txn->get(ver_key, &ver_val);
957
958
271
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
959
0
        LOG(INFO) << ""
960
0
                     "partition version not found, instance_id="
961
0
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
962
0
                  << " table_id=" << tablet_idx_pb.table_id()
963
0
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
964
0
                  << " key=" << hex(ver_key);
965
0
        return true;
966
0
    }
967
968
271
    if (TxnErrorCode::TXN_OK != err) {
969
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
970
0
                     << " db_id=" << tablet_idx_pb.db_id()
971
0
                     << " table_id=" << tablet_idx_pb.table_id()
972
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
973
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
974
0
        return false;
975
0
    }
976
977
271
    VersionPB version_pb;
978
271
    if (!version_pb.ParseFromString(ver_val)) {
979
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
980
0
                     << " db_id=" << tablet_idx_pb.db_id()
981
0
                     << " table_id=" << tablet_idx_pb.table_id()
982
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
983
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
984
0
        return false;
985
0
    }
986
987
271
    if (version_pb.pending_txn_ids_size() > 0) {
988
20
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
989
20
        DCHECK(version_pb.pending_txn_ids_size() == 1);
990
20
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
991
20
                     << " db_id=" << tablet_idx_pb.db_id()
992
20
                     << " table_id=" << tablet_idx_pb.table_id()
993
20
                     << " partition_id=" << tablet_idx_pb.partition_id()
994
20
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
995
20
                     << " key=" << hex(ver_key);
996
20
        return false;
997
20
    }
998
251
    return true;
999
271
}
1000
1001
14
int InstanceRecycler::recycle_partitions() {
1002
14
    const std::string task_name = "recycle_partitions";
1003
14
    int64_t num_scanned = 0;
1004
14
    int64_t num_expired = 0;
1005
14
    int64_t num_recycled = 0;
1006
1007
14
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
1008
14
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
1009
14
    std::string part_key0;
1010
14
    std::string part_key1;
1011
14
    recycle_partition_key(part_key_info0, &part_key0);
1012
14
    recycle_partition_key(part_key_info1, &part_key1);
1013
1014
14
    LOG_INFO("begin to recycle partitions").tag("instance_id", instance_id_);
1015
1016
14
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
1017
14
    register_recycle_task(task_name, start_time);
1018
1019
14
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
1020
14
        unregister_recycle_task(task_name);
1021
14
        int64_t cost =
1022
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
1023
14
        LOG_INFO("recycle partitions finished, cost={}s", cost)
1024
14
                .tag("instance_id", instance_id_)
1025
14
                .tag("num_scanned", num_scanned)
1026
14
                .tag("num_expired", num_expired)
1027
14
                .tag("num_recycled", num_recycled);
1028
14
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEPi
Line
Count
Source
1019
12
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
1020
12
        unregister_recycle_task(task_name);
1021
12
        int64_t cost =
1022
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
1023
12
        LOG_INFO("recycle partitions finished, cost={}s", cost)
1024
12
                .tag("instance_id", instance_id_)
1025
12
                .tag("num_scanned", num_scanned)
1026
12
                .tag("num_expired", num_expired)
1027
12
                .tag("num_recycled", num_recycled);
1028
12
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEPi
Line
Count
Source
1019
2
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
1020
2
        unregister_recycle_task(task_name);
1021
2
        int64_t cost =
1022
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
1023
2
        LOG_INFO("recycle partitions finished, cost={}s", cost)
1024
2
                .tag("instance_id", instance_id_)
1025
2
                .tag("num_scanned", num_scanned)
1026
2
                .tag("num_expired", num_expired)
1027
2
                .tag("num_recycled", num_recycled);
1028
2
    });
1029
1030
14
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
1031
1032
14
    auto calc_expiration = [&earlest_ts, this](const RecyclePartitionPB& partition) {
1033
8
        if (config::force_immediate_recycle) {
1034
2
            return 0L;
1035
2
        }
1036
6
        int64_t expiration =
1037
6
                partition.expiration() > 0 ? partition.expiration() : partition.creation_time();
1038
6
        int64_t retention_seconds = config::retention_seconds;
1039
6
        if (partition.state() == RecyclePartitionPB::DROPPED) {
1040
6
            retention_seconds =
1041
6
                    std::min(config::dropped_partition_retention_seconds, retention_seconds);
1042
6
        }
1043
6
        int64_t final_expiration = expiration + retention_seconds;
1044
6
        if (earlest_ts > final_expiration) {
1045
2
            earlest_ts = final_expiration;
1046
2
            g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, earlest_ts);
1047
2
        }
1048
6
        return final_expiration;
1049
8
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_3clERKNS0_18RecyclePartitionPBE
Line
Count
Source
1032
6
    auto calc_expiration = [&earlest_ts, this](const RecyclePartitionPB& partition) {
1033
6
        if (config::force_immediate_recycle) {
1034
0
            return 0L;
1035
0
        }
1036
6
        int64_t expiration =
1037
6
                partition.expiration() > 0 ? partition.expiration() : partition.creation_time();
1038
6
        int64_t retention_seconds = config::retention_seconds;
1039
6
        if (partition.state() == RecyclePartitionPB::DROPPED) {
1040
6
            retention_seconds =
1041
6
                    std::min(config::dropped_partition_retention_seconds, retention_seconds);
1042
6
        }
1043
6
        int64_t final_expiration = expiration + retention_seconds;
1044
6
        if (earlest_ts > final_expiration) {
1045
2
            earlest_ts = final_expiration;
1046
2
            g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, earlest_ts);
1047
2
        }
1048
6
        return final_expiration;
1049
6
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_3clERKNS0_18RecyclePartitionPBE
Line
Count
Source
1032
2
    auto calc_expiration = [&earlest_ts, this](const RecyclePartitionPB& partition) {
1033
2
        if (config::force_immediate_recycle) {
1034
2
            return 0L;
1035
2
        }
1036
0
        int64_t expiration =
1037
0
                partition.expiration() > 0 ? partition.expiration() : partition.creation_time();
1038
0
        int64_t retention_seconds = config::retention_seconds;
1039
0
        if (partition.state() == RecyclePartitionPB::DROPPED) {
1040
0
            retention_seconds =
1041
0
                    std::min(config::dropped_partition_retention_seconds, retention_seconds);
1042
0
        }
1043
0
        int64_t final_expiration = expiration + retention_seconds;
1044
0
        if (earlest_ts > final_expiration) {
1045
0
            earlest_ts = final_expiration;
1046
0
            g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, earlest_ts);
1047
0
        }
1048
0
        return final_expiration;
1049
2
    };
1050
1051
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
1052
14
    std::vector<std::string_view> partition_keys;
1053
14
    std::vector<std::string> partition_version_keys;
1054
14
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
1055
8
        ++num_scanned;
1056
8
        RecyclePartitionPB part_pb;
1057
8
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
1058
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
1059
0
            return -1;
1060
0
        }
1061
8
        int64_t current_time = ::time(nullptr);
1062
8
        if (current_time < calc_expiration(part_pb)) { // not expired
1063
0
            return 0;
1064
0
        }
1065
8
        ++num_expired;
1066
        // decode partition_id
1067
8
        auto k1 = k;
1068
8
        k1.remove_prefix(1);
1069
8
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1070
8
        decode_key(&k1, &out);
1071
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
1072
8
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
1073
8
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
1074
8
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
1075
8
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
1076
        // Change state to RECYCLING
1077
8
        std::unique_ptr<Transaction> txn;
1078
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1079
8
        if (err != TxnErrorCode::TXN_OK) {
1080
0
            LOG_WARNING("failed to create txn").tag("err", err);
1081
0
            return -1;
1082
0
        }
1083
8
        std::string val;
1084
8
        err = txn->get(k, &val);
1085
8
        if (err ==
1086
8
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
1087
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
1088
0
            return 0;
1089
0
        }
1090
8
        if (err != TxnErrorCode::TXN_OK) {
1091
0
            LOG_WARNING("failed to get kv");
1092
0
            return -1;
1093
0
        }
1094
8
        part_pb.Clear();
1095
8
        if (!part_pb.ParseFromString(val)) {
1096
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
1097
0
            return -1;
1098
0
        }
1099
        // Partitions with PREPARED state MUST have no data
1100
8
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
1101
8
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
1102
7
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
1103
7
            txn->put(k, part_pb.SerializeAsString());
1104
7
            err = txn->commit();
1105
7
            if (err != TxnErrorCode::TXN_OK) {
1106
0
                LOG_WARNING("failed to commit txn: {}", err);
1107
0
                return -1;
1108
0
            }
1109
7
        }
1110
1111
8
        int ret = 0;
1112
32
        for (int64_t index_id : part_pb.index_id()) {
1113
32
            if (recycle_tablets(part_pb.table_id(), index_id, partition_id, is_empty_tablet) != 0) {
1114
1
                LOG_WARNING("failed to recycle tablets under partition")
1115
1
                        .tag("table_id", part_pb.table_id())
1116
1
                        .tag("instance_id", instance_id_)
1117
1
                        .tag("index_id", index_id)
1118
1
                        .tag("partition_id", partition_id);
1119
1
                ret = -1;
1120
1
            }
1121
32
        }
1122
8
        if (ret == 0) {
1123
7
            ++num_recycled;
1124
7
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
1125
7
            partition_keys.push_back(k);
1126
7
            if (part_pb.db_id() > 0) {
1127
7
                partition_version_keys.push_back(partition_version_key(
1128
7
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
1129
7
            }
1130
7
        }
1131
8
        return ret;
1132
8
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
1054
6
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
1055
6
        ++num_scanned;
1056
6
        RecyclePartitionPB part_pb;
1057
6
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
1058
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
1059
0
            return -1;
1060
0
        }
1061
6
        int64_t current_time = ::time(nullptr);
1062
6
        if (current_time < calc_expiration(part_pb)) { // not expired
1063
0
            return 0;
1064
0
        }
1065
6
        ++num_expired;
1066
        // decode partition_id
1067
6
        auto k1 = k;
1068
6
        k1.remove_prefix(1);
1069
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1070
6
        decode_key(&k1, &out);
1071
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
1072
6
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
1073
6
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
1074
6
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
1075
6
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
1076
        // Change state to RECYCLING
1077
6
        std::unique_ptr<Transaction> txn;
1078
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1079
6
        if (err != TxnErrorCode::TXN_OK) {
1080
0
            LOG_WARNING("failed to create txn").tag("err", err);
1081
0
            return -1;
1082
0
        }
1083
6
        std::string val;
1084
6
        err = txn->get(k, &val);
1085
6
        if (err ==
1086
6
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
1087
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
1088
0
            return 0;
1089
0
        }
1090
6
        if (err != TxnErrorCode::TXN_OK) {
1091
0
            LOG_WARNING("failed to get kv");
1092
0
            return -1;
1093
0
        }
1094
6
        part_pb.Clear();
1095
6
        if (!part_pb.ParseFromString(val)) {
1096
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
1097
0
            return -1;
1098
0
        }
1099
        // Partitions with PREPARED state MUST have no data
1100
6
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
1101
6
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
1102
6
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
1103
6
            txn->put(k, part_pb.SerializeAsString());
1104
6
            err = txn->commit();
1105
6
            if (err != TxnErrorCode::TXN_OK) {
1106
0
                LOG_WARNING("failed to commit txn: {}", err);
1107
0
                return -1;
1108
0
            }
1109
6
        }
1110
1111
6
        int ret = 0;
1112
30
        for (int64_t index_id : part_pb.index_id()) {
1113
30
            if (recycle_tablets(part_pb.table_id(), index_id, partition_id, is_empty_tablet) != 0) {
1114
0
                LOG_WARNING("failed to recycle tablets under partition")
1115
0
                        .tag("table_id", part_pb.table_id())
1116
0
                        .tag("instance_id", instance_id_)
1117
0
                        .tag("index_id", index_id)
1118
0
                        .tag("partition_id", partition_id);
1119
0
                ret = -1;
1120
0
            }
1121
30
        }
1122
6
        if (ret == 0) {
1123
6
            ++num_recycled;
1124
6
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
1125
6
            partition_keys.push_back(k);
1126
6
            if (part_pb.db_id() > 0) {
1127
6
                partition_version_keys.push_back(partition_version_key(
1128
6
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
1129
6
            }
1130
6
        }
1131
6
        return ret;
1132
6
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
1054
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
1055
2
        ++num_scanned;
1056
2
        RecyclePartitionPB part_pb;
1057
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
1058
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
1059
0
            return -1;
1060
0
        }
1061
2
        int64_t current_time = ::time(nullptr);
1062
2
        if (current_time < calc_expiration(part_pb)) { // not expired
1063
0
            return 0;
1064
0
        }
1065
2
        ++num_expired;
1066
        // decode partition_id
1067
2
        auto k1 = k;
1068
2
        k1.remove_prefix(1);
1069
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1070
2
        decode_key(&k1, &out);
1071
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
1072
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
1073
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
1074
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
1075
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
1076
        // Change state to RECYCLING
1077
2
        std::unique_ptr<Transaction> txn;
1078
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1079
2
        if (err != TxnErrorCode::TXN_OK) {
1080
0
            LOG_WARNING("failed to create txn").tag("err", err);
1081
0
            return -1;
1082
0
        }
1083
2
        std::string val;
1084
2
        err = txn->get(k, &val);
1085
2
        if (err ==
1086
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
1087
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
1088
0
            return 0;
1089
0
        }
1090
2
        if (err != TxnErrorCode::TXN_OK) {
1091
0
            LOG_WARNING("failed to get kv");
1092
0
            return -1;
1093
0
        }
1094
2
        part_pb.Clear();
1095
2
        if (!part_pb.ParseFromString(val)) {
1096
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
1097
0
            return -1;
1098
0
        }
1099
        // Partitions with PREPARED state MUST have no data
1100
2
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
1101
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
1102
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
1103
1
            txn->put(k, part_pb.SerializeAsString());
1104
1
            err = txn->commit();
1105
1
            if (err != TxnErrorCode::TXN_OK) {
1106
0
                LOG_WARNING("failed to commit txn: {}", err);
1107
0
                return -1;
1108
0
            }
1109
1
        }
1110
1111
2
        int ret = 0;
1112
2
        for (int64_t index_id : part_pb.index_id()) {
1113
2
            if (recycle_tablets(part_pb.table_id(), index_id, partition_id, is_empty_tablet) != 0) {
1114
1
                LOG_WARNING("failed to recycle tablets under partition")
1115
1
                        .tag("table_id", part_pb.table_id())
1116
1
                        .tag("instance_id", instance_id_)
1117
1
                        .tag("index_id", index_id)
1118
1
                        .tag("partition_id", partition_id);
1119
1
                ret = -1;
1120
1
            }
1121
2
        }
1122
2
        if (ret == 0) {
1123
1
            ++num_recycled;
1124
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
1125
1
            partition_keys.push_back(k);
1126
1
            if (part_pb.db_id() > 0) {
1127
1
                partition_version_keys.push_back(partition_version_key(
1128
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
1129
1
            }
1130
1
        }
1131
2
        return ret;
1132
2
    };
1133
1134
14
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
1135
4
        if (partition_keys.empty()) return 0;
1136
3
        std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01, [&](int*) {
1137
3
            partition_keys.clear();
1138
3
            partition_version_keys.clear();
1139
3
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clEvENKUlPiE_clES3_
Line
Count
Source
1136
2
        std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01, [&](int*) {
1137
2
            partition_keys.clear();
1138
2
            partition_version_keys.clear();
1139
2
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clEvENKUlPiE_clES3_
Line
Count
Source
1136
1
        std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01, [&](int*) {
1137
1
            partition_keys.clear();
1138
1
            partition_version_keys.clear();
1139
1
        });
1140
3
        std::unique_ptr<Transaction> txn;
1141
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1142
3
        if (err != TxnErrorCode::TXN_OK) {
1143
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
1144
0
            return -1;
1145
0
        }
1146
7
        for (auto& k : partition_keys) {
1147
7
            txn->remove(k);
1148
7
        }
1149
7
        for (auto& k : partition_version_keys) {
1150
7
            txn->remove(k);
1151
7
        }
1152
3
        err = txn->commit();
1153
3
        if (err != TxnErrorCode::TXN_OK) {
1154
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
1155
0
                         << " err=" << err;
1156
0
            return -1;
1157
0
        }
1158
3
        return 0;
1159
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clEv
Line
Count
Source
1134
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
1135
2
        if (partition_keys.empty()) return 0;
1136
2
        std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01, [&](int*) {
1137
2
            partition_keys.clear();
1138
2
            partition_version_keys.clear();
1139
2
        });
1140
2
        std::unique_ptr<Transaction> txn;
1141
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1142
2
        if (err != TxnErrorCode::TXN_OK) {
1143
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
1144
0
            return -1;
1145
0
        }
1146
6
        for (auto& k : partition_keys) {
1147
6
            txn->remove(k);
1148
6
        }
1149
6
        for (auto& k : partition_version_keys) {
1150
6
            txn->remove(k);
1151
6
        }
1152
2
        err = txn->commit();
1153
2
        if (err != TxnErrorCode::TXN_OK) {
1154
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
1155
0
                         << " err=" << err;
1156
0
            return -1;
1157
0
        }
1158
2
        return 0;
1159
2
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clEv
Line
Count
Source
1134
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
1135
2
        if (partition_keys.empty()) return 0;
1136
1
        std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01, [&](int*) {
1137
1
            partition_keys.clear();
1138
1
            partition_version_keys.clear();
1139
1
        });
1140
1
        std::unique_ptr<Transaction> txn;
1141
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1142
1
        if (err != TxnErrorCode::TXN_OK) {
1143
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
1144
0
            return -1;
1145
0
        }
1146
1
        for (auto& k : partition_keys) {
1147
1
            txn->remove(k);
1148
1
        }
1149
1
        for (auto& k : partition_version_keys) {
1150
1
            txn->remove(k);
1151
1
        }
1152
1
        err = txn->commit();
1153
1
        if (err != TxnErrorCode::TXN_OK) {
1154
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
1155
0
                         << " err=" << err;
1156
0
            return -1;
1157
0
        }
1158
1
        return 0;
1159
1
    };
1160
1161
14
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
1162
14
}
1163
1164
12
int InstanceRecycler::recycle_versions() {
1165
12
    int64_t num_scanned = 0;
1166
12
    int64_t num_recycled = 0;
1167
1168
12
    LOG_INFO("begin to recycle table and partition versions").tag("instance_id", instance_id_);
1169
1170
12
    auto start_time = steady_clock::now();
1171
1172
12
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
1173
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
1174
12
        LOG_INFO("recycle table and partition versions finished, cost={}s", cost)
1175
12
                .tag("instance_id", instance_id_)
1176
12
                .tag("num_scanned", num_scanned)
1177
12
                .tag("num_recycled", num_recycled);
1178
12
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEPi
Line
Count
Source
1172
12
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
1173
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
1174
12
        LOG_INFO("recycle table and partition versions finished, cost={}s", cost)
1175
12
                .tag("instance_id", instance_id_)
1176
12
                .tag("num_scanned", num_scanned)
1177
12
                .tag("num_recycled", num_recycled);
1178
12
    });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEPi
1179
1180
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
1181
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
1182
12
    int64_t last_scanned_table_id = 0;
1183
12
    bool is_recycled = false; // Is last scanned kv recycled
1184
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled, this](
1185
12
                                std::string_view k, std::string_view) {
1186
2
        ++num_scanned;
1187
2
        auto k1 = k;
1188
2
        k1.remove_prefix(1);
1189
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
1190
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1191
2
        decode_key(&k1, &out);
1192
2
        DCHECK_EQ(out.size(), 6) << k;
1193
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
1194
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
1195
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
1196
0
            return 0;
1197
0
        }
1198
2
        last_scanned_table_id = table_id;
1199
2
        is_recycled = false;
1200
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
1201
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
1202
2
        std::unique_ptr<Transaction> txn;
1203
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1204
2
        if (err != TxnErrorCode::TXN_OK) {
1205
0
            return -1;
1206
0
        }
1207
2
        std::unique_ptr<RangeGetIterator> iter;
1208
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
1209
2
        if (err != TxnErrorCode::TXN_OK) {
1210
0
            return -1;
1211
0
        }
1212
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
1213
1
            return 0;
1214
1
        }
1215
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
1216
        // 1. Remove all partition version kvs of this table
1217
1
        auto partition_version_key_begin =
1218
1
                partition_version_key({instance_id_, db_id, table_id, 0});
1219
1
        auto partition_version_key_end =
1220
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
1221
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
1222
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
1223
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
1224
1
                     << " table_id=" << table_id;
1225
        // 2. Remove the table version kv of this table
1226
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
1227
1
        txn->remove(tbl_version_key);
1228
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
1229
        // 3. Remove mow delete bitmap update lock and tablet compaction lock
1230
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
1231
1
        txn->remove(lock_key);
1232
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
1233
1
        std::string tablet_compaction_key_begin =
1234
1
                mow_tablet_compaction_key({instance_id_, table_id, 0});
1235
1
        std::string tablet_compaction_key_end =
1236
1
                mow_tablet_compaction_key({instance_id_, table_id, INT64_MAX});
1237
1
        txn->remove(tablet_compaction_key_begin, tablet_compaction_key_end);
1238
1
        LOG(WARNING) << "remove mow tablet compaction kv, begin="
1239
1
                     << hex(tablet_compaction_key_begin)
1240
1
                     << " end=" << hex(tablet_compaction_key_end) << " db_id=" << db_id
1241
1
                     << " table_id=" << table_id;
1242
1
        err = txn->commit();
1243
1
        if (err != TxnErrorCode::TXN_OK) {
1244
0
            return -1;
1245
0
        }
1246
1
        ++num_recycled;
1247
1
        is_recycled = true;
1248
1
        return 0;
1249
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
1185
2
                                std::string_view k, std::string_view) {
1186
2
        ++num_scanned;
1187
2
        auto k1 = k;
1188
2
        k1.remove_prefix(1);
1189
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
1190
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1191
2
        decode_key(&k1, &out);
1192
2
        DCHECK_EQ(out.size(), 6) << k;
1193
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
1194
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
1195
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
1196
0
            return 0;
1197
0
        }
1198
2
        last_scanned_table_id = table_id;
1199
2
        is_recycled = false;
1200
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
1201
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
1202
2
        std::unique_ptr<Transaction> txn;
1203
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1204
2
        if (err != TxnErrorCode::TXN_OK) {
1205
0
            return -1;
1206
0
        }
1207
2
        std::unique_ptr<RangeGetIterator> iter;
1208
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
1209
2
        if (err != TxnErrorCode::TXN_OK) {
1210
0
            return -1;
1211
0
        }
1212
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
1213
1
            return 0;
1214
1
        }
1215
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
1216
        // 1. Remove all partition version kvs of this table
1217
1
        auto partition_version_key_begin =
1218
1
                partition_version_key({instance_id_, db_id, table_id, 0});
1219
1
        auto partition_version_key_end =
1220
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
1221
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
1222
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
1223
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
1224
1
                     << " table_id=" << table_id;
1225
        // 2. Remove the table version kv of this table
1226
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
1227
1
        txn->remove(tbl_version_key);
1228
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
1229
        // 3. Remove mow delete bitmap update lock and tablet compaction lock
1230
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
1231
1
        txn->remove(lock_key);
1232
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
1233
1
        std::string tablet_compaction_key_begin =
1234
1
                mow_tablet_compaction_key({instance_id_, table_id, 0});
1235
1
        std::string tablet_compaction_key_end =
1236
1
                mow_tablet_compaction_key({instance_id_, table_id, INT64_MAX});
1237
1
        txn->remove(tablet_compaction_key_begin, tablet_compaction_key_end);
1238
1
        LOG(WARNING) << "remove mow tablet compaction kv, begin="
1239
1
                     << hex(tablet_compaction_key_begin)
1240
1
                     << " end=" << hex(tablet_compaction_key_end) << " db_id=" << db_id
1241
1
                     << " table_id=" << table_id;
1242
1
        err = txn->commit();
1243
1
        if (err != TxnErrorCode::TXN_OK) {
1244
0
            return -1;
1245
0
        }
1246
1
        ++num_recycled;
1247
1
        is_recycled = true;
1248
1
        return 0;
1249
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
1250
1251
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
1252
12
}
1253
1254
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id, int64_t partition_id,
1255
41
                                      bool is_empty_tablet) {
1256
41
    int64_t num_scanned = 0;
1257
41
    std::atomic_long num_recycled = 0;
1258
1259
41
    std::string tablet_key_begin, tablet_key_end;
1260
41
    std::string stats_key_begin, stats_key_end;
1261
41
    std::string job_key_begin, job_key_end;
1262
1263
41
    std::string tablet_belongs;
1264
41
    if (partition_id > 0) {
1265
        // recycle tablets in a partition belonging to the index
1266
32
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
1267
32
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
1268
32
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
1269
32
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
1270
32
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
1271
32
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
1272
32
        tablet_belongs = "partition";
1273
32
    } else {
1274
        // recycle tablets in the index
1275
9
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
1276
9
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
1277
9
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
1278
9
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
1279
9
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
1280
9
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
1281
9
        tablet_belongs = "index";
1282
9
    }
1283
1284
41
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
1285
41
            .tag("table_id", table_id)
1286
41
            .tag("index_id", index_id)
1287
41
            .tag("partition_id", partition_id);
1288
1289
41
    auto start_time = steady_clock::now();
1290
1291
41
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
1292
41
        auto cost = duration<float>(steady_clock::now() - start_time).count();
1293
41
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
1294
41
                .tag("instance_id", instance_id_)
1295
41
                .tag("table_id", table_id)
1296
41
                .tag("index_id", index_id)
1297
41
                .tag("partition_id", partition_id)
1298
41
                .tag("num_scanned", num_scanned)
1299
41
                .tag("num_recycled", num_recycled);
1300
41
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsElllbENK3$_1clEPi
Line
Count
Source
1291
37
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
1292
37
        auto cost = duration<float>(steady_clock::now() - start_time).count();
1293
37
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
1294
37
                .tag("instance_id", instance_id_)
1295
37
                .tag("table_id", table_id)
1296
37
                .tag("index_id", index_id)
1297
37
                .tag("partition_id", partition_id)
1298
37
                .tag("num_scanned", num_scanned)
1299
37
                .tag("num_recycled", num_recycled);
1300
37
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsElllbENK3$_1clEPi
Line
Count
Source
1291
4
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
1292
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
1293
4
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
1294
4
                .tag("instance_id", instance_id_)
1295
4
                .tag("table_id", table_id)
1296
4
                .tag("index_id", index_id)
1297
4
                .tag("partition_id", partition_id)
1298
4
                .tag("num_scanned", num_scanned)
1299
4
                .tag("num_recycled", num_recycled);
1300
4
    });
1301
1302
    // The first string_view represents the tablet key which has been recycled
1303
    // The second bool represents whether the following fdb's tablet key deletion could be done using range move or not
1304
41
    using TabletKeyPair = std::pair<std::string_view, bool>;
1305
41
    SyncExecutor<TabletKeyPair> sync_executor(
1306
41
            _thread_pool_group.recycle_tablet_pool,
1307
41
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
1308
41
                        index_id, partition_id),
1309
251
            [](const TabletKeyPair& k) { return k.first.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsElllbENK3$_2clERKSt4pairISt17basic_string_viewIcSt11char_traitsIcEEbE
Line
Count
Source
1309
231
            [](const TabletKeyPair& k) { return k.first.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsElllbENK3$_2clERKSt4pairISt17basic_string_viewIcSt11char_traitsIcEEbE
Line
Count
Source
1309
20
            [](const TabletKeyPair& k) { return k.first.empty(); });
1310
1311
    // Elements in `tablet_keys` has the same lifetime as `it` in `scan_and_recycle`
1312
41
    std::vector<std::string> tablet_idx_keys;
1313
41
    std::vector<std::string> init_rs_keys;
1314
271
    auto recycle_func = [&, is_empty_tablet, this](std::string_view k, std::string_view v) -> int {
1315
271
        bool use_range_remove = true;
1316
271
        ++num_scanned;
1317
271
        doris::TabletMetaCloudPB tablet_meta_pb;
1318
271
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
1319
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
1320
0
            use_range_remove = false;
1321
0
            return -1;
1322
0
        }
1323
271
        int64_t tablet_id = tablet_meta_pb.tablet_id();
1324
1325
271
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
1326
20
            LOG(WARNING) << "lazy txn not finished tablet_meta_pb=" << tablet_meta_pb.tablet_id();
1327
20
            return -1;
1328
20
        }
1329
1330
251
        tablet_idx_keys.push_back(meta_tablet_idx_key({instance_id_, tablet_id}));
1331
251
        if (!is_empty_tablet) {
1332
251
            sync_executor.add([this, &num_recycled, tid = tablet_id, range_move = use_range_remove,
1333
251
                               k]() mutable -> TabletKeyPair {
1334
251
                if (recycle_tablet(tid) != 0) {
1335
0
                    LOG_WARNING("failed to recycle tablet")
1336
0
                            .tag("instance_id", instance_id_)
1337
0
                            .tag("tablet_id", tid);
1338
0
                    range_move = false;
1339
0
                    return {std::string_view(), range_move};
1340
0
                }
1341
251
                ++num_recycled;
1342
251
                LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
1343
251
                return {k, range_move};
1344
251
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsElllbENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_ENUlvE_clEv
Line
Count
Source
1333
231
                               k]() mutable -> TabletKeyPair {
1334
231
                if (recycle_tablet(tid) != 0) {
1335
0
                    LOG_WARNING("failed to recycle tablet")
1336
0
                            .tag("instance_id", instance_id_)
1337
0
                            .tag("tablet_id", tid);
1338
0
                    range_move = false;
1339
0
                    return {std::string_view(), range_move};
1340
0
                }
1341
231
                ++num_recycled;
1342
231
                LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
1343
231
                return {k, range_move};
1344
231
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsElllbENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_ENUlvE_clEv
Line
Count
Source
1333
20
                               k]() mutable -> TabletKeyPair {
1334
20
                if (recycle_tablet(tid) != 0) {
1335
0
                    LOG_WARNING("failed to recycle tablet")
1336
0
                            .tag("instance_id", instance_id_)
1337
0
                            .tag("tablet_id", tid);
1338
0
                    range_move = false;
1339
0
                    return {std::string_view(), range_move};
1340
0
                }
1341
20
                ++num_recycled;
1342
20
                LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
1343
20
                return {k, range_move};
1344
20
            });
1345
251
        } else {
1346
            // Empty tablet only has a [0-1] init rowset
1347
0
            init_rs_keys.push_back(meta_rowset_key({instance_id_, tablet_id, 1}));
1348
0
            DCHECK([&]() {
1349
0
                std::unique_ptr<Transaction> txn;
1350
0
                if (TxnErrorCode err = txn_kv_->create_txn(&txn); err != TxnErrorCode::TXN_OK) {
1351
0
                    LOG_ERROR("failed to create txn").tag("err", err);
1352
0
                    return false;
1353
0
                }
1354
0
                auto rs_key_begin = meta_rowset_key({instance_id_, tablet_id, 2});
1355
0
                auto rs_key_end = meta_rowset_key({instance_id_, tablet_id, INT64_MAX});
1356
0
                std::unique_ptr<RangeGetIterator> iter;
1357
0
                if (TxnErrorCode err = txn->get(rs_key_begin, rs_key_end, &iter, true, 1);
1358
0
                    err != TxnErrorCode::TXN_OK) {
1359
0
                    LOG_ERROR("failed to get kv").tag("err", err);
1360
0
                    return false;
1361
0
                }
1362
0
                if (iter->has_next()) {
1363
0
                    LOG_ERROR("tablet is not empty").tag("tablet_id", tablet_id);
1364
0
                    return false;
1365
0
                }
1366
0
                return true;
1367
0
            }());
1368
0
            sync_executor.add([k]() mutable -> TabletKeyPair {
1369
0
                LOG_INFO("k is {}, is empty {}", k, k.empty());
1370
0
                return {k, true};
1371
0
            });
Unexecuted instantiation: recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsElllbENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_ENUlvE1_clEv
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsElllbENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_ENUlvE1_clEv
1372
0
            ++num_recycled;
1373
0
        }
1374
251
        return 0;
1375
271
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsElllbENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
1314
231
    auto recycle_func = [&, is_empty_tablet, this](std::string_view k, std::string_view v) -> int {
1315
231
        bool use_range_remove = true;
1316
231
        ++num_scanned;
1317
231
        doris::TabletMetaCloudPB tablet_meta_pb;
1318
231
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
1319
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
1320
0
            use_range_remove = false;
1321
0
            return -1;
1322
0
        }
1323
231
        int64_t tablet_id = tablet_meta_pb.tablet_id();
1324
1325
231
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
1326
0
            LOG(WARNING) << "lazy txn not finished tablet_meta_pb=" << tablet_meta_pb.tablet_id();
1327
0
            return -1;
1328
0
        }
1329
1330
231
        tablet_idx_keys.push_back(meta_tablet_idx_key({instance_id_, tablet_id}));
1331
231
        if (!is_empty_tablet) {
1332
231
            sync_executor.add([this, &num_recycled, tid = tablet_id, range_move = use_range_remove,
1333
231
                               k]() mutable -> TabletKeyPair {
1334
231
                if (recycle_tablet(tid) != 0) {
1335
231
                    LOG_WARNING("failed to recycle tablet")
1336
231
                            .tag("instance_id", instance_id_)
1337
231
                            .tag("tablet_id", tid);
1338
231
                    range_move = false;
1339
231
                    return {std::string_view(), range_move};
1340
231
                }
1341
231
                ++num_recycled;
1342
231
                LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
1343
231
                return {k, range_move};
1344
231
            });
1345
231
        } else {
1346
            // Empty tablet only has a [0-1] init rowset
1347
0
            init_rs_keys.push_back(meta_rowset_key({instance_id_, tablet_id, 1}));
1348
0
            DCHECK([&]() {
1349
0
                std::unique_ptr<Transaction> txn;
1350
0
                if (TxnErrorCode err = txn_kv_->create_txn(&txn); err != TxnErrorCode::TXN_OK) {
1351
0
                    LOG_ERROR("failed to create txn").tag("err", err);
1352
0
                    return false;
1353
0
                }
1354
0
                auto rs_key_begin = meta_rowset_key({instance_id_, tablet_id, 2});
1355
0
                auto rs_key_end = meta_rowset_key({instance_id_, tablet_id, INT64_MAX});
1356
0
                std::unique_ptr<RangeGetIterator> iter;
1357
0
                if (TxnErrorCode err = txn->get(rs_key_begin, rs_key_end, &iter, true, 1);
1358
0
                    err != TxnErrorCode::TXN_OK) {
1359
0
                    LOG_ERROR("failed to get kv").tag("err", err);
1360
0
                    return false;
1361
0
                }
1362
0
                if (iter->has_next()) {
1363
0
                    LOG_ERROR("tablet is not empty").tag("tablet_id", tablet_id);
1364
0
                    return false;
1365
0
                }
1366
0
                return true;
1367
0
            }());
1368
0
            sync_executor.add([k]() mutable -> TabletKeyPair {
1369
0
                LOG_INFO("k is {}, is empty {}", k, k.empty());
1370
0
                return {k, true};
1371
0
            });
1372
0
            ++num_recycled;
1373
0
        }
1374
231
        return 0;
1375
231
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsElllbENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
1314
40
    auto recycle_func = [&, is_empty_tablet, this](std::string_view k, std::string_view v) -> int {
1315
40
        bool use_range_remove = true;
1316
40
        ++num_scanned;
1317
40
        doris::TabletMetaCloudPB tablet_meta_pb;
1318
40
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
1319
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
1320
0
            use_range_remove = false;
1321
0
            return -1;
1322
0
        }
1323
40
        int64_t tablet_id = tablet_meta_pb.tablet_id();
1324
1325
40
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
1326
20
            LOG(WARNING) << "lazy txn not finished tablet_meta_pb=" << tablet_meta_pb.tablet_id();
1327
20
            return -1;
1328
20
        }
1329
1330
20
        tablet_idx_keys.push_back(meta_tablet_idx_key({instance_id_, tablet_id}));
1331
20
        if (!is_empty_tablet) {
1332
20
            sync_executor.add([this, &num_recycled, tid = tablet_id, range_move = use_range_remove,
1333
20
                               k]() mutable -> TabletKeyPair {
1334
20
                if (recycle_tablet(tid) != 0) {
1335
20
                    LOG_WARNING("failed to recycle tablet")
1336
20
                            .tag("instance_id", instance_id_)
1337
20
                            .tag("tablet_id", tid);
1338
20
                    range_move = false;
1339
20
                    return {std::string_view(), range_move};
1340
20
                }
1341
20
                ++num_recycled;
1342
20
                LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
1343
20
                return {k, range_move};
1344
20
            });
1345
20
        } else {
1346
            // Empty tablet only has a [0-1] init rowset
1347
0
            init_rs_keys.push_back(meta_rowset_key({instance_id_, tablet_id, 1}));
1348
0
            DCHECK([&]() {
1349
0
                std::unique_ptr<Transaction> txn;
1350
0
                if (TxnErrorCode err = txn_kv_->create_txn(&txn); err != TxnErrorCode::TXN_OK) {
1351
0
                    LOG_ERROR("failed to create txn").tag("err", err);
1352
0
                    return false;
1353
0
                }
1354
0
                auto rs_key_begin = meta_rowset_key({instance_id_, tablet_id, 2});
1355
0
                auto rs_key_end = meta_rowset_key({instance_id_, tablet_id, INT64_MAX});
1356
0
                std::unique_ptr<RangeGetIterator> iter;
1357
0
                if (TxnErrorCode err = txn->get(rs_key_begin, rs_key_end, &iter, true, 1);
1358
0
                    err != TxnErrorCode::TXN_OK) {
1359
0
                    LOG_ERROR("failed to get kv").tag("err", err);
1360
0
                    return false;
1361
0
                }
1362
0
                if (iter->has_next()) {
1363
0
                    LOG_ERROR("tablet is not empty").tag("tablet_id", tablet_id);
1364
0
                    return false;
1365
0
                }
1366
0
                return true;
1367
0
            }());
1368
0
            sync_executor.add([k]() mutable -> TabletKeyPair {
1369
0
                LOG_INFO("k is {}, is empty {}", k, k.empty());
1370
0
                return {k, true};
1371
0
            });
1372
0
            ++num_recycled;
1373
0
        }
1374
20
        return 0;
1375
40
    };
1376
1377
    // TODO(AlexYue): Add one ut to cover use_range_remove = false
1378
41
    auto loop_done = [&, this]() -> int {
1379
41
        bool finished = true;
1380
41
        auto tablet_keys = sync_executor.when_all(&finished);
1381
41
        if (!finished) {
1382
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
1383
0
            return -1;
1384
0
        }
1385
41
        if (tablet_keys.empty() && tablet_idx_keys.empty()) return 0;
1386
        // sort the vector using key's order
1387
39
        std::sort(tablet_keys.begin(), tablet_keys.end(),
1388
980
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsElllbENK3$_0clEvENKUlRKT_RKT0_E_clISt4pairISt17basic_string_viewIcSt11char_traitsIcEEbESG_EEDaS5_S8_
Line
Count
Source
1388
944
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsElllbENK3$_0clEvENKUlRKT_RKT0_E_clISt4pairISt17basic_string_viewIcSt11char_traitsIcEEbESG_EEDaS5_S8_
Line
Count
Source
1388
36
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
1389
39
        bool use_range_remove = true;
1390
251
        for (auto& [_, remove] : tablet_keys) {
1391
251
            if (!remove) {
1392
0
                use_range_remove = remove;
1393
0
                break;
1394
0
            }
1395
251
        }
1396
39
        std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01, [&](int*) {
1397
39
            tablet_idx_keys.clear();
1398
39
            init_rs_keys.clear();
1399
39
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsElllbENK3$_0clEvENKUlPiE_clES3_
Line
Count
Source
1396
37
        std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01, [&](int*) {
1397
37
            tablet_idx_keys.clear();
1398
37
            init_rs_keys.clear();
1399
37
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsElllbENK3$_0clEvENKUlPiE_clES3_
Line
Count
Source
1396
2
        std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01, [&](int*) {
1397
2
            tablet_idx_keys.clear();
1398
2
            init_rs_keys.clear();
1399
2
        });
1400
39
        std::unique_ptr<Transaction> txn;
1401
39
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
1402
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
1403
0
            return -1;
1404
0
        }
1405
39
        std::string tablet_key_end;
1406
39
        if (!tablet_keys.empty()) {
1407
39
            if (use_range_remove) {
1408
39
                tablet_key_end = std::string(tablet_keys.back().first) + '\x00';
1409
39
                txn->remove(tablet_keys.front().first, tablet_key_end);
1410
39
            } else {
1411
0
                for (auto& [k, _] : tablet_keys) {
1412
0
                    txn->remove(k);
1413
0
                }
1414
0
            }
1415
39
        }
1416
251
        for (auto& k : tablet_idx_keys) {
1417
251
            txn->remove(k);
1418
251
        }
1419
39
        for (auto& k : init_rs_keys) {
1420
0
            txn->remove(k);
1421
0
        }
1422
39
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
1423
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
1424
0
                         << ", err=" << err;
1425
0
            return -1;
1426
0
        }
1427
39
        return 0;
1428
39
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsElllbENK3$_0clEv
Line
Count
Source
1378
37
    auto loop_done = [&, this]() -> int {
1379
37
        bool finished = true;
1380
37
        auto tablet_keys = sync_executor.when_all(&finished);
1381
37
        if (!finished) {
1382
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
1383
0
            return -1;
1384
0
        }
1385
37
        if (tablet_keys.empty() && tablet_idx_keys.empty()) return 0;
1386
        // sort the vector using key's order
1387
37
        std::sort(tablet_keys.begin(), tablet_keys.end(),
1388
37
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
1389
37
        bool use_range_remove = true;
1390
231
        for (auto& [_, remove] : tablet_keys) {
1391
231
            if (!remove) {
1392
0
                use_range_remove = remove;
1393
0
                break;
1394
0
            }
1395
231
        }
1396
37
        std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01, [&](int*) {
1397
37
            tablet_idx_keys.clear();
1398
37
            init_rs_keys.clear();
1399
37
        });
1400
37
        std::unique_ptr<Transaction> txn;
1401
37
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
1402
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
1403
0
            return -1;
1404
0
        }
1405
37
        std::string tablet_key_end;
1406
37
        if (!tablet_keys.empty()) {
1407
37
            if (use_range_remove) {
1408
37
                tablet_key_end = std::string(tablet_keys.back().first) + '\x00';
1409
37
                txn->remove(tablet_keys.front().first, tablet_key_end);
1410
37
            } else {
1411
0
                for (auto& [k, _] : tablet_keys) {
1412
0
                    txn->remove(k);
1413
0
                }
1414
0
            }
1415
37
        }
1416
231
        for (auto& k : tablet_idx_keys) {
1417
231
            txn->remove(k);
1418
231
        }
1419
37
        for (auto& k : init_rs_keys) {
1420
0
            txn->remove(k);
1421
0
        }
1422
37
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
1423
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
1424
0
                         << ", err=" << err;
1425
0
            return -1;
1426
0
        }
1427
37
        return 0;
1428
37
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsElllbENK3$_0clEv
Line
Count
Source
1378
4
    auto loop_done = [&, this]() -> int {
1379
4
        bool finished = true;
1380
4
        auto tablet_keys = sync_executor.when_all(&finished);
1381
4
        if (!finished) {
1382
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
1383
0
            return -1;
1384
0
        }
1385
4
        if (tablet_keys.empty() && tablet_idx_keys.empty()) return 0;
1386
        // sort the vector using key's order
1387
2
        std::sort(tablet_keys.begin(), tablet_keys.end(),
1388
2
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
1389
2
        bool use_range_remove = true;
1390
20
        for (auto& [_, remove] : tablet_keys) {
1391
20
            if (!remove) {
1392
0
                use_range_remove = remove;
1393
0
                break;
1394
0
            }
1395
20
        }
1396
2
        std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01, [&](int*) {
1397
2
            tablet_idx_keys.clear();
1398
2
            init_rs_keys.clear();
1399
2
        });
1400
2
        std::unique_ptr<Transaction> txn;
1401
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
1402
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
1403
0
            return -1;
1404
0
        }
1405
2
        std::string tablet_key_end;
1406
2
        if (!tablet_keys.empty()) {
1407
2
            if (use_range_remove) {
1408
2
                tablet_key_end = std::string(tablet_keys.back().first) + '\x00';
1409
2
                txn->remove(tablet_keys.front().first, tablet_key_end);
1410
2
            } else {
1411
0
                for (auto& [k, _] : tablet_keys) {
1412
0
                    txn->remove(k);
1413
0
                }
1414
0
            }
1415
2
        }
1416
20
        for (auto& k : tablet_idx_keys) {
1417
20
            txn->remove(k);
1418
20
        }
1419
2
        for (auto& k : init_rs_keys) {
1420
0
            txn->remove(k);
1421
0
        }
1422
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
1423
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
1424
0
                         << ", err=" << err;
1425
0
            return -1;
1426
0
        }
1427
2
        return 0;
1428
2
    };
1429
1430
41
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
1431
41
                               std::move(loop_done));
1432
41
    if (ret != 0) {
1433
2
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
1434
2
        return ret;
1435
2
    }
1436
1437
    // directly remove tablet stats and tablet jobs of these dropped index or partition
1438
39
    std::unique_ptr<Transaction> txn;
1439
39
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
1440
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
1441
0
        return -1;
1442
0
    }
1443
39
    txn->remove(stats_key_begin, stats_key_end);
1444
39
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
1445
39
                 << " end=" << hex(stats_key_end);
1446
39
    txn->remove(job_key_begin, job_key_end);
1447
39
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
1448
39
    std::string schema_key_begin, schema_key_end;
1449
39
    std::string schema_dict_key;
1450
39
    if (partition_id <= 0) {
1451
        // Delete schema kv of this index
1452
8
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
1453
8
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
1454
8
        txn->remove(schema_key_begin, schema_key_end);
1455
8
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
1456
8
                     << " end=" << hex(schema_key_end);
1457
8
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
1458
8
        txn->remove(schema_dict_key);
1459
8
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
1460
8
    }
1461
1462
39
    TxnErrorCode err = txn->commit();
1463
39
    if (err != TxnErrorCode::TXN_OK) {
1464
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
1465
0
                     << " err=" << err;
1466
0
        return -1;
1467
0
    }
1468
1469
39
    return ret;
1470
39
}
1471
1472
4.00k
int InstanceRecycler::delete_rowset_data(const doris::RowsetMetaCloudPB& rs_meta_pb) {
1473
4.00k
    int64_t num_segments = rs_meta_pb.num_segments();
1474
4.00k
    if (num_segments <= 0) return 0;
1475
4.00k
    if (!rs_meta_pb.has_tablet_schema()) {
1476
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
1477
0
                                  rs_meta_pb.rowset_id_v2());
1478
0
    }
1479
4.00k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
1480
4.00k
    if (it == accessor_map_.end()) {
1481
0
        LOG_WARNING("instance has no such resource id")
1482
0
                .tag("instance_id", instance_id_)
1483
0
                .tag("resource_id", rs_meta_pb.resource_id());
1484
0
        return -1;
1485
0
    }
1486
4.00k
    auto& accessor = it->second;
1487
4.00k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
1488
4.00k
    int64_t tablet_id = rs_meta_pb.tablet_id();
1489
    // process inverted indexes
1490
4.00k
    std::vector<std::pair<int64_t, std::string>> index_ids;
1491
4.00k
    index_ids.reserve(rs_meta_pb.tablet_schema().index_size());
1492
8.00k
    for (auto& i : rs_meta_pb.tablet_schema().index()) {
1493
8.00k
        if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
1494
8.00k
            index_ids.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
1495
8.00k
        }
1496
8.00k
    }
1497
4.00k
    std::vector<std::string> file_paths;
1498
4.00k
    auto tablet_schema = rs_meta_pb.tablet_schema();
1499
4.00k
    auto index_storage_format = InvertedIndexStorageFormatPB::V1;
1500
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
1501
20.0k
        file_paths.push_back(segment_path(tablet_id, rowset_id, i));
1502
20.0k
        if (tablet_schema.has_inverted_index_storage_format()) {
1503
10.0k
            index_storage_format = tablet_schema.inverted_index_storage_format();
1504
10.0k
        }
1505
20.0k
        if (index_storage_format == InvertedIndexStorageFormatPB::V1) {
1506
40.0k
            for (const auto& index_id : index_ids) {
1507
40.0k
                file_paths.push_back(inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
1508
40.0k
                                                            index_id.second));
1509
40.0k
            }
1510
20.0k
        } else if (!index_ids.empty()) {
1511
0
            file_paths.push_back(inverted_index_path_v2(tablet_id, rowset_id, i));
1512
0
        }
1513
20.0k
    }
1514
    // TODO(AlexYue): seems could do do batch
1515
4.00k
    return accessor->delete_files(file_paths);
1516
4.00k
}
1517
1518
int InstanceRecycler::delete_rowset_data(const std::vector<doris::RowsetMetaCloudPB>& rowsets,
1519
32
                                         RowsetRecyclingState type) {
1520
32
    int ret = 0;
1521
    // resource_id -> file_paths
1522
32
    std::map<std::string, std::vector<std::string>> resource_file_paths;
1523
    // (resource_id, tablet_id, rowset_id)
1524
32
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
1525
1526
6.14k
    for (const auto& rs : rowsets) {
1527
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
1528
        // due to aborted schema change.
1529
6.14k
        if (type == RowsetRecyclingState::FORMAL_ROWSET) {
1530
3.12k
            std::lock_guard lock(recycled_tablets_mtx_);
1531
3.12k
            if (recycled_tablets_.count(rs.tablet_id())) {
1532
0
                continue; // Rowset data has already been deleted
1533
0
            }
1534
3.12k
        }
1535
1536
6.14k
        auto it = accessor_map_.find(rs.resource_id());
1537
        // possible if the accessor is not initilized correctly
1538
6.14k
        if (it == accessor_map_.end()) [[unlikely]] {
1539
1
            LOG_WARNING("instance has no such resource id")
1540
1
                    .tag("instance_id", instance_id_)
1541
1
                    .tag("resource_id", rs.resource_id());
1542
1
            ret = -1;
1543
1
            continue;
1544
1
        }
1545
1546
6.14k
        auto& file_paths = resource_file_paths[rs.resource_id()];
1547
6.14k
        const auto& rowset_id = rs.rowset_id_v2();
1548
6.14k
        int64_t tablet_id = rs.tablet_id();
1549
6.14k
        int64_t num_segments = rs.num_segments();
1550
6.14k
        if (num_segments <= 0) continue;
1551
1552
        // Process inverted indexes
1553
6.14k
        std::vector<std::pair<int64_t, std::string>> index_ids;
1554
        // default format as v1.
1555
6.14k
        InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
1556
6.14k
        int inverted_index_get_ret = 0;
1557
6.14k
        if (rs.has_tablet_schema()) {
1558
5.54k
            for (const auto& index : rs.tablet_schema().index()) {
1559
5.54k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
1560
5.54k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
1561
5.54k
                }
1562
5.54k
            }
1563
2.59k
            if (rs.tablet_schema().has_inverted_index_storage_format()) {
1564
2.56k
                index_format = rs.tablet_schema().inverted_index_storage_format();
1565
2.56k
            }
1566
3.55k
        } else {
1567
3.55k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
1568
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
1569
0
                                "instance_id="
1570
0
                             << instance_id_ << " tablet_id=" << tablet_id
1571
0
                             << " rowset_id=" << rowset_id;
1572
0
                ret = -1;
1573
0
                continue;
1574
0
            }
1575
3.55k
            InvertedIndexInfo index_info;
1576
3.55k
            inverted_index_get_ret =
1577
3.55k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
1578
3.55k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
1579
3.55k
                                     &inverted_index_get_ret);
1580
3.55k
            if (inverted_index_get_ret == 0) {
1581
3.05k
                index_format = index_info.first;
1582
3.05k
                index_ids = index_info.second;
1583
3.05k
            } else if (inverted_index_get_ret == 1) {
1584
                // 1. Schema kv not found means tablet has been recycled
1585
                // Maybe some tablet recycle failed by some bugs
1586
                // We need to delete again to double check
1587
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
1588
                // because we are uncertain about the inverted index information.
1589
                // If there are inverted indexes, some data might not be deleted,
1590
                // but this is acceptable as we have made our best effort to delete the data.
1591
503
                LOG_INFO(
1592
503
                        "delete rowset data schema kv not found, need to delete again to double "
1593
503
                        "check")
1594
503
                        .tag("instance_id", instance_id_)
1595
503
                        .tag("tablet_id", tablet_id)
1596
503
                        .tag("rowset", rs.ShortDebugString());
1597
                // Currently index_ids is guaranteed to be empty,
1598
                // but we clear it again here as a safeguard against future code changes
1599
                // that might cause index_ids to no longer be empty
1600
503
                index_format = InvertedIndexStorageFormatPB::V2;
1601
503
                index_ids.clear();
1602
503
            } else {
1603
0
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
1604
0
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
1605
0
                ret = -1;
1606
0
                continue;
1607
0
            }
1608
3.55k
        }
1609
6.14k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
1610
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
1611
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
1612
5
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
1613
5
            continue;
1614
5
        }
1615
36.8k
        for (int64_t i = 0; i < num_segments; ++i) {
1616
30.6k
            file_paths.push_back(segment_path(tablet_id, rowset_id, i));
1617
30.6k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
1618
59.2k
                for (const auto& index_id : index_ids) {
1619
59.2k
                    file_paths.push_back(inverted_index_path_v1(tablet_id, rowset_id, i,
1620
59.2k
                                                                index_id.first, index_id.second));
1621
59.2k
                }
1622
28.1k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
1623
                // try to recycle inverted index v2 when get_ret == 1
1624
                // we treat schema not found as if it has a v2 format inverted index
1625
                // to reduce chance of data leakage
1626
2.50k
                if (inverted_index_get_ret == 1) {
1627
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
1628
2.50k
                            .tag("instance_id", instance_id_)
1629
2.50k
                            .tag("inverted index v2 path",
1630
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, i));
1631
2.50k
                }
1632
2.50k
                file_paths.push_back(inverted_index_path_v2(tablet_id, rowset_id, i));
1633
2.50k
            }
1634
30.6k
        }
1635
6.13k
    }
1636
1637
32
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
1638
32
                                                 "delete_rowset_data",
1639
34
                                                 [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt6vectorINS_17RowsetMetaCloudPBESaIS3_EENS0_20RowsetRecyclingStateEENK3$_0clERKi
Line
Count
Source
1639
34
                                                 [](const int& ret) { return ret != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt6vectorINS_17RowsetMetaCloudPBESaIS3_EENS0_20RowsetRecyclingStateEENK3$_0clERKi
1640
32
    for (auto& [resource_id, file_paths] : resource_file_paths) {
1641
29
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
1642
29
            DCHECK(accessor_map_.count(*rid))
1643
0
                    << "uninitilized accessor, instance_id=" << instance_id_
1644
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
1645
29
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
1646
29
                                     &accessor_map_);
1647
29
            if (!accessor_map_.contains(*rid)) {
1648
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
1649
0
                        .tag("resource_id", resource_id)
1650
0
                        .tag("instance_id", instance_id_);
1651
0
                return -1;
1652
0
            }
1653
29
            auto& accessor = accessor_map_[*rid];
1654
29
            return accessor->delete_files(*paths);
1655
29
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt6vectorINS_17RowsetMetaCloudPBESaIS3_EENS0_20RowsetRecyclingStateEENK3$_1clEv
Line
Count
Source
1641
29
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
1642
29
            DCHECK(accessor_map_.count(*rid))
1643
0
                    << "uninitilized accessor, instance_id=" << instance_id_
1644
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
1645
29
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
1646
29
                                     &accessor_map_);
1647
29
            if (!accessor_map_.contains(*rid)) {
1648
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
1649
0
                        .tag("resource_id", resource_id)
1650
0
                        .tag("instance_id", instance_id_);
1651
0
                return -1;
1652
0
            }
1653
29
            auto& accessor = accessor_map_[*rid];
1654
29
            return accessor->delete_files(*paths);
1655
29
        });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt6vectorINS_17RowsetMetaCloudPBESaIS3_EENS0_20RowsetRecyclingStateEENK3$_1clEv
1656
29
    }
1657
32
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
1658
5
        LOG_INFO(
1659
5
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
1660
5
                "resource_id={}, tablet_id={}, instance_id={}",
1661
5
                rowset_id, resource_id, tablet_id, instance_id_);
1662
5
        concurrent_delete_executor.add(
1663
5
                [&]() -> int { return delete_rowset_data(resource_id, tablet_id, rowset_id); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt6vectorINS_17RowsetMetaCloudPBESaIS3_EENS0_20RowsetRecyclingStateEENK3$_2clEv
Line
Count
Source
1663
5
                [&]() -> int { return delete_rowset_data(resource_id, tablet_id, rowset_id); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt6vectorINS_17RowsetMetaCloudPBESaIS3_EENS0_20RowsetRecyclingStateEENK3$_2clEv
1664
5
    }
1665
32
    bool finished = true;
1666
32
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
1667
34
    for (int r : rets) {
1668
34
        if (r != 0) {
1669
0
            ret = -1;
1670
0
            break;
1671
0
        }
1672
34
    }
1673
32
    ret = finished ? ret : -1;
1674
32
    return ret;
1675
32
}
1676
1677
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
1678
2.90k
                                         const std::string& rowset_id) {
1679
2.90k
    auto it = accessor_map_.find(resource_id);
1680
2.90k
    if (it == accessor_map_.end()) {
1681
0
        LOG_WARNING("instance has no such resource id")
1682
0
                .tag("instance_id", instance_id_)
1683
0
                .tag("resource_id", resource_id)
1684
0
                .tag("tablet_id", tablet_id)
1685
0
                .tag("rowset_id", rowset_id);
1686
0
        return -1;
1687
0
    }
1688
2.90k
    auto& accessor = it->second;
1689
2.90k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
1690
2.90k
}
1691
1692
254
int InstanceRecycler::recycle_tablet(int64_t tablet_id) {
1693
254
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
1694
254
            .tag("instance_id", instance_id_)
1695
254
            .tag("tablet_id", tablet_id);
1696
1697
254
    int ret = 0;
1698
254
    auto start_time = steady_clock::now();
1699
1700
254
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
1701
1702
    // collect resource ids
1703
234
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
1704
234
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1705
234
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
1706
234
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
1707
1708
234
    std::set<std::string> resource_ids;
1709
234
    int64_t recycle_rowsets_number = 0;
1710
234
    int64_t recycle_segments_number = 0;
1711
234
    int64_t recycle_rowsets_data_size = 0;
1712
234
    int64_t recycle_rowsets_index_size = 0;
1713
234
    int64_t max_rowset_version = 0;
1714
234
    int64_t min_rowset_creation_time = INT64_MAX;
1715
234
    int64_t max_rowset_creation_time = 0;
1716
234
    int64_t min_rowset_expiration_time = INT64_MAX;
1717
234
    int64_t max_rowset_expiration_time = 0;
1718
1719
234
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
1720
234
        auto cost = duration<float>(steady_clock::now() - start_time).count();
1721
234
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
1722
234
                .tag("instance_id", instance_id_)
1723
234
                .tag("tablet_id", tablet_id)
1724
234
                .tag("recycle rowsets number", recycle_rowsets_number)
1725
234
                .tag("recycle segments number", recycle_segments_number)
1726
234
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
1727
234
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
1728
234
                .tag("max rowset version", max_rowset_version)
1729
234
                .tag("min rowset creation time", min_rowset_creation_time)
1730
234
                .tag("max rowset creation time", max_rowset_creation_time)
1731
234
                .tag("min rowset expiration time", min_rowset_expiration_time)
1732
234
                .tag("max rowset expiration time", max_rowset_expiration_time)
1733
234
                .tag("ret", ret);
1734
234
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElENK3$_1clEPi
Line
Count
Source
1719
234
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
1720
234
        auto cost = duration<float>(steady_clock::now() - start_time).count();
1721
234
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
1722
234
                .tag("instance_id", instance_id_)
1723
234
                .tag("tablet_id", tablet_id)
1724
234
                .tag("recycle rowsets number", recycle_rowsets_number)
1725
234
                .tag("recycle segments number", recycle_segments_number)
1726
234
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
1727
234
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
1728
234
                .tag("max rowset version", max_rowset_version)
1729
234
                .tag("min rowset creation time", min_rowset_creation_time)
1730
234
                .tag("max rowset creation time", max_rowset_creation_time)
1731
234
                .tag("min rowset expiration time", min_rowset_expiration_time)
1732
234
                .tag("max rowset expiration time", max_rowset_expiration_time)
1733
234
                .tag("ret", ret);
1734
234
    });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElENK3$_1clEPi
1735
1736
234
    std::unique_ptr<Transaction> txn;
1737
234
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
1738
0
        LOG_WARNING("failed to recycle tablet ")
1739
0
                .tag("tablet id", tablet_id)
1740
0
                .tag("instance_id", instance_id_)
1741
0
                .tag("reason", "failed to create txn");
1742
0
        ret = -1;
1743
0
    }
1744
234
    GetRowsetResponse resp;
1745
234
    std::string msg;
1746
234
    MetaServiceCode code = MetaServiceCode::OK;
1747
    // get rowsets in tablet
1748
234
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
1749
234
                        tablet_id, code, msg, &resp);
1750
234
    if (code != MetaServiceCode::OK) {
1751
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
1752
0
                .tag("tablet id", tablet_id)
1753
0
                .tag("msg", msg)
1754
0
                .tag("code", code)
1755
0
                .tag("instance id", instance_id_);
1756
0
        ret = -1;
1757
0
    }
1758
234
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
1759
1760
2.50k
    for (const auto& rs_meta : resp.rowset_meta()) {
1761
        /*
1762
        * For compatibility, we skip the loop for [0-1] here. 
1763
        * The purpose of this loop is to delete object files,
1764
        * and since [0-1] only has meta and doesn't have object files, 
1765
        * skipping it doesn't affect system correctness. 
1766
        *
1767
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below 
1768
        * would return error -1 directly, causing the recycle operation to fail.
1769
        *
1770
        * [0-1] doesn't have resource id is a bug.
1771
        * In the future, we will fix this problem, after that,
1772
        * we can remove this if statement.
1773
        *
1774
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
1775
        */
1776
1777
2.50k
        if (rs_meta.end_version() == 1) {
1778
            // Assert that [0-1] has no resource_id to make sure
1779
            // this if statement will not be forgetted to remove
1780
            // when the resource id bug is fixed
1781
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
1782
0
            recycle_rowsets_number += 1;
1783
0
            continue;
1784
0
        }
1785
2.50k
        if (!rs_meta.has_resource_id()) {
1786
1
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
1787
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
1788
1
                    .tag("instance_id", instance_id_)
1789
1
                    .tag("tablet_id", tablet_id);
1790
1
            return -1;
1791
1
        }
1792
2.50k
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
1793
2.50k
        auto it = accessor_map_.find(rs_meta.resource_id());
1794
        // possible if the accessor is not initilized correctly
1795
2.50k
        if (it == accessor_map_.end()) [[unlikely]] {
1796
1
            LOG_WARNING(
1797
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
1798
1
                    "recycle process")
1799
1
                    .tag("tablet id", tablet_id)
1800
1
                    .tag("instance_id", instance_id_)
1801
1
                    .tag("resource_id", rs_meta.resource_id())
1802
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
1803
1
            return -1;
1804
1
        }
1805
2.50k
        recycle_rowsets_number += 1;
1806
2.50k
        recycle_segments_number += rs_meta.num_segments();
1807
2.50k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
1808
2.50k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
1809
2.50k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
1810
2.50k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
1811
2.50k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
1812
2.50k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
1813
2.50k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
1814
2.50k
        resource_ids.emplace(rs_meta.resource_id());
1815
2.50k
    }
1816
1817
232
    LOG_INFO("recycle tablet start to delete object")
1818
232
            .tag("instance id", instance_id_)
1819
232
            .tag("tablet id", tablet_id)
1820
232
            .tag("recycle tablet resource ids are",
1821
232
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
1822
232
                                 [](const std::string& a, const std::string& b) {
1823
203
                                     return a.empty() ? b : a + "," + b;
1824
203
                                 }));
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElENK3$_0clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESA_
Line
Count
Source
1822
203
                                 [](const std::string& a, const std::string& b) {
1823
203
                                     return a.empty() ? b : a + "," + b;
1824
203
                                 }));
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElENK3$_0clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESA_
1825
1826
232
    SyncExecutor<int> concurrent_delete_executor(
1827
232
            _thread_pool_group.s3_producer_pool,
1828
232
            fmt::format("delete tablet {} s3 rowset", tablet_id),
1829
232
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElENK3$_2clERKi
Line
Count
Source
1829
203
            [](const int& ret) { return ret != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElENK3$_2clERKi
1830
1831
    // delete all rowset data in this tablet
1832
    // ATTN: there may be data leak if not all accessor initilized successfully
1833
    //       partial data deleted if the tablet is stored cross-storage vault
1834
    //       vault id is not attached to TabletMeta...
1835
232
    for (const auto& resource_id : resource_ids) {
1836
203
        concurrent_delete_executor.add([&, accessor_ptr = accessor_map_[resource_id]]() {
1837
203
            if (accessor_ptr->delete_directory(tablet_path_prefix(tablet_id)) != 0) {
1838
1
                LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
1839
1
                             << " path=" << accessor_ptr->uri();
1840
1
                return -1;
1841
1
            }
1842
202
            return 0;
1843
203
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElENK3$_3clEv
Line
Count
Source
1836
203
        concurrent_delete_executor.add([&, accessor_ptr = accessor_map_[resource_id]]() {
1837
203
            if (accessor_ptr->delete_directory(tablet_path_prefix(tablet_id)) != 0) {
1838
1
                LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
1839
1
                             << " path=" << accessor_ptr->uri();
1840
1
                return -1;
1841
1
            }
1842
202
            return 0;
1843
203
        });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElENK3$_3clEv
1844
203
    }
1845
1846
232
    bool finished = true;
1847
232
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
1848
232
    for (int r : rets) {
1849
203
        if (r != 0) {
1850
1
            ret = -1;
1851
1
        }
1852
203
    }
1853
1854
232
    ret = finished ? ret : -1;
1855
1856
232
    if (ret != 0) { // failed recycle tablet data
1857
1
        LOG_WARNING("ret!=0")
1858
1
                .tag("finished", finished)
1859
1
                .tag("ret", ret)
1860
1
                .tag("instance_id", instance_id_)
1861
1
                .tag("tablet_id", tablet_id);
1862
1
        return ret;
1863
1
    }
1864
1865
231
    txn.reset();
1866
231
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
1867
0
        LOG_WARNING("failed to recycle tablet ")
1868
0
                .tag("tablet id", tablet_id)
1869
0
                .tag("instance_id", instance_id_)
1870
0
                .tag("reason", "failed to create txn");
1871
0
        ret = -1;
1872
0
    }
1873
    // delete all rowset kv in this tablet
1874
231
    txn->remove(rs_key0, rs_key1);
1875
231
    txn->remove(recyc_rs_key0, recyc_rs_key1);
1876
1877
    // remove delete bitmap for MoW table
1878
231
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
1879
231
    txn->remove(pending_key);
1880
231
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
1881
231
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
1882
231
    txn->remove(delete_bitmap_start, delete_bitmap_end);
1883
1884
231
    TxnErrorCode err = txn->commit();
1885
231
    if (err != TxnErrorCode::TXN_OK) {
1886
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
1887
0
        ret = -1;
1888
0
    }
1889
1890
231
    if (ret == 0) {
1891
        // All object files under tablet have been deleted
1892
231
        std::lock_guard lock(recycled_tablets_mtx_);
1893
231
        recycled_tablets_.insert(tablet_id);
1894
231
    }
1895
1896
231
    return ret;
1897
232
}
1898
1899
13
int InstanceRecycler::recycle_rowsets() {
1900
13
    const std::string task_name = "recycle_rowsets";
1901
13
    int64_t num_scanned = 0;
1902
13
    int64_t num_expired = 0;
1903
13
    int64_t num_prepare = 0;
1904
13
    int64_t num_compacted = 0;
1905
13
    int64_t num_empty_rowset = 0;
1906
13
    size_t total_rowset_key_size = 0;
1907
13
    size_t total_rowset_value_size = 0;
1908
13
    size_t expired_rowset_size = 0;
1909
13
    std::atomic_long num_recycled = 0;
1910
1911
13
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
1912
13
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
1913
13
    std::string recyc_rs_key0;
1914
13
    std::string recyc_rs_key1;
1915
13
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
1916
13
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
1917
1918
13
    LOG_INFO("begin to recycle rowsets").tag("instance_id", instance_id_);
1919
1920
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
1921
13
    register_recycle_task(task_name, start_time);
1922
1923
13
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
1924
13
        unregister_recycle_task(task_name);
1925
13
        int64_t cost =
1926
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
1927
13
        LOG_INFO("recycle rowsets finished, cost={}s", cost)
1928
13
                .tag("instance_id", instance_id_)
1929
13
                .tag("num_scanned", num_scanned)
1930
13
                .tag("num_expired", num_expired)
1931
13
                .tag("num_recycled", num_recycled)
1932
13
                .tag("num_recycled.prepare", num_prepare)
1933
13
                .tag("num_recycled.compacted", num_compacted)
1934
13
                .tag("num_recycled.empty_rowset", num_empty_rowset)
1935
13
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
1936
13
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
1937
13
                .tag("expired_rowset_meta_size", expired_rowset_size);
1938
13
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEPi
Line
Count
Source
1923
13
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
1924
13
        unregister_recycle_task(task_name);
1925
13
        int64_t cost =
1926
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
1927
13
        LOG_INFO("recycle rowsets finished, cost={}s", cost)
1928
13
                .tag("instance_id", instance_id_)
1929
13
                .tag("num_scanned", num_scanned)
1930
13
                .tag("num_expired", num_expired)
1931
13
                .tag("num_recycled", num_recycled)
1932
13
                .tag("num_recycled.prepare", num_prepare)
1933
13
                .tag("num_recycled.compacted", num_compacted)
1934
13
                .tag("num_recycled.empty_rowset", num_empty_rowset)
1935
13
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
1936
13
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
1937
13
                .tag("expired_rowset_meta_size", expired_rowset_size);
1938
13
    });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEPi
1939
1940
13
    std::vector<std::string> rowset_keys;
1941
13
    std::vector<doris::RowsetMetaCloudPB> rowsets;
1942
1943
    // Store keys of rowset recycled by background workers
1944
13
    std::mutex async_recycled_rowset_keys_mutex;
1945
13
    std::vector<std::string> async_recycled_rowset_keys;
1946
13
    auto worker_pool = std::make_unique<SimpleThreadPool>(
1947
13
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
1948
13
    worker_pool->start();
1949
13
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
1950
900
                                            int64_t tablet_id, const std::string& rowset_id) {
1951
        // Try to delete rowset data in background thread
1952
900
        int ret = worker_pool->submit_with_timeout(
1953
900
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
1954
780
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
1955
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
1956
0
                        return;
1957
0
                    }
1958
780
                    std::vector<std::string> keys;
1959
780
                    {
1960
780
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
1961
780
                        async_recycled_rowset_keys.push_back(std::move(key));
1962
780
                        if (async_recycled_rowset_keys.size() > 100) {
1963
7
                            keys.swap(async_recycled_rowset_keys);
1964
7
                        }
1965
780
                    }
1966
780
                    if (keys.empty()) return;
1967
7
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
1968
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
1969
0
                                     << instance_id_;
1970
7
                    } else {
1971
7
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
1972
7
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
1973
7
                                           num_recycled, start_time);
1974
7
                    }
1975
7
                },
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
1953
780
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
1954
780
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
1955
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
1956
0
                        return;
1957
0
                    }
1958
780
                    std::vector<std::string> keys;
1959
780
                    {
1960
780
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
1961
780
                        async_recycled_rowset_keys.push_back(std::move(key));
1962
780
                        if (async_recycled_rowset_keys.size() > 100) {
1963
7
                            keys.swap(async_recycled_rowset_keys);
1964
7
                        }
1965
780
                    }
1966
780
                    if (keys.empty()) return;
1967
7
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
1968
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
1969
0
                                     << instance_id_;
1970
7
                    } else {
1971
7
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
1972
7
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
1973
7
                                           num_recycled, start_time);
1974
7
                    }
1975
7
                },
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
1976
900
                0);
1977
900
        if (ret == 0) return 0;
1978
        // Submit task failed, delete rowset data in current thread
1979
120
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
1980
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
1981
0
            return -1;
1982
0
        }
1983
120
        rowset_keys.push_back(std::move(key));
1984
120
        return 0;
1985
120
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
1950
900
                                            int64_t tablet_id, const std::string& rowset_id) {
1951
        // Try to delete rowset data in background thread
1952
900
        int ret = worker_pool->submit_with_timeout(
1953
900
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
1954
900
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
1955
900
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
1956
900
                        return;
1957
900
                    }
1958
900
                    std::vector<std::string> keys;
1959
900
                    {
1960
900
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
1961
900
                        async_recycled_rowset_keys.push_back(std::move(key));
1962
900
                        if (async_recycled_rowset_keys.size() > 100) {
1963
900
                            keys.swap(async_recycled_rowset_keys);
1964
900
                        }
1965
900
                    }
1966
900
                    if (keys.empty()) return;
1967
900
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
1968
900
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
1969
900
                                     << instance_id_;
1970
900
                    } else {
1971
900
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
1972
900
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
1973
900
                                           num_recycled, start_time);
1974
900
                    }
1975
900
                },
1976
900
                0);
1977
900
        if (ret == 0) return 0;
1978
        // Submit task failed, delete rowset data in current thread
1979
120
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
1980
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
1981
0
            return -1;
1982
0
        }
1983
120
        rowset_keys.push_back(std::move(key));
1984
120
        return 0;
1985
120
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
1986
1987
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
1988
1989
4.00k
    auto calc_expiration = [&earlest_ts, this](const RecycleRowsetPB& rs) {
1990
4.00k
        if (config::force_immediate_recycle) {
1991
0
            return 0L;
1992
0
        }
1993
        // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1994
4.00k
        int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1995
4.00k
        int64_t retention_seconds = config::retention_seconds;
1996
4.00k
        if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1997
3.10k
            retention_seconds =
1998
3.10k
                    std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1999
3.10k
        }
2000
4.00k
        int64_t final_expiration = expiration + retention_seconds;
2001
4.00k
        if (earlest_ts > final_expiration) {
2002
2
            earlest_ts = final_expiration;
2003
2
            g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, earlest_ts);
2004
2
        }
2005
4.00k
        return final_expiration;
2006
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clERKNS0_15RecycleRowsetPBE
Line
Count
Source
1989
4.00k
    auto calc_expiration = [&earlest_ts, this](const RecycleRowsetPB& rs) {
1990
4.00k
        if (config::force_immediate_recycle) {
1991
0
            return 0L;
1992
0
        }
1993
        // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1994
4.00k
        int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1995
4.00k
        int64_t retention_seconds = config::retention_seconds;
1996
4.00k
        if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1997
3.10k
            retention_seconds =
1998
3.10k
                    std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1999
3.10k
        }
2000
4.00k
        int64_t final_expiration = expiration + retention_seconds;
2001
4.00k
        if (earlest_ts > final_expiration) {
2002
2
            earlest_ts = final_expiration;
2003
2
            g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, earlest_ts);
2004
2
        }
2005
4.00k
        return final_expiration;
2006
4.00k
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clERKNS0_15RecycleRowsetPBE
2007
2008
4.00k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
2009
4.00k
        ++num_scanned;
2010
4.00k
        total_rowset_key_size += k.size();
2011
4.00k
        total_rowset_value_size += v.size();
2012
4.00k
        RecycleRowsetPB rowset;
2013
4.00k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
2014
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
2015
0
            return -1;
2016
0
        }
2017
2018
4.00k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
2019
0
                   << " num_expired=" << num_expired << " expiration=" << calc_expiration(rowset)
2020
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
2021
4.00k
        int64_t current_time = ::time(nullptr);
2022
4.00k
        if (current_time < calc_expiration(rowset)) { // not expired
2023
0
            return 0;
2024
0
        }
2025
4.00k
        ++num_expired;
2026
4.00k
        expired_rowset_size += v.size();
2027
4.00k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
2028
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
2029
                // in old version, keep this key-value pair and it needs to be checked manually
2030
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
2031
0
                return -1;
2032
0
            }
2033
250
            if (rowset.resource_id().empty()) [[unlikely]] {
2034
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
2035
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
2036
0
                          << hex(k) << " value=" << proto_to_json(rowset);
2037
0
                rowset_keys.emplace_back(k);
2038
0
                return -1;
2039
0
            }
2040
            // decode rowset_id
2041
250
            auto k1 = k;
2042
250
            k1.remove_prefix(1);
2043
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2044
250
            decode_key(&k1, &out);
2045
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
2046
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
2047
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
2048
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
2049
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
2050
250
                                             rowset.tablet_id(), rowset_id) != 0) {
2051
0
                return -1;
2052
0
            }
2053
250
            return 0;
2054
250
        }
2055
        // TODO(plat1ko): check rowset not referenced
2056
3.75k
        auto rowset_meta = rowset.mutable_rowset_meta();
2057
3.75k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
2058
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
2059
0
                LOG_INFO("recycle rowset that has empty resource id");
2060
0
            } else {
2061
                // other situations, keep this key-value pair and it needs to be checked manually
2062
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
2063
0
                return -1;
2064
0
            }
2065
0
        }
2066
3.75k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
2067
3.75k
                  << " tablet_id=" << rowset_meta->tablet_id()
2068
3.75k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
2069
3.75k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
2070
3.75k
                  << "] txn_id=" << rowset_meta->txn_id()
2071
3.75k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
2072
3.75k
                  << " rowset_meta_size=" << v.size()
2073
3.75k
                  << " creation_time=" << rowset_meta->creation_time();
2074
3.75k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
2075
            // unable to calculate file path, can only be deleted by rowset id prefix
2076
650
            num_prepare += 1;
2077
650
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
2078
650
                                             rowset_meta->tablet_id(),
2079
650
                                             rowset_meta->rowset_id_v2()) != 0) {
2080
0
                return -1;
2081
0
            }
2082
3.10k
        } else {
2083
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
2084
3.10k
            rowset_keys.emplace_back(k);
2085
3.10k
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
2086
3.10k
                rowsets.push_back(std::move(*rowset_meta));
2087
3.10k
            } else {
2088
0
                ++num_empty_rowset;
2089
0
            }
2090
3.10k
        }
2091
3.75k
        return 0;
2092
3.75k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2008
4.00k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
2009
4.00k
        ++num_scanned;
2010
4.00k
        total_rowset_key_size += k.size();
2011
4.00k
        total_rowset_value_size += v.size();
2012
4.00k
        RecycleRowsetPB rowset;
2013
4.00k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
2014
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
2015
0
            return -1;
2016
0
        }
2017
2018
4.00k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
2019
0
                   << " num_expired=" << num_expired << " expiration=" << calc_expiration(rowset)
2020
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
2021
4.00k
        int64_t current_time = ::time(nullptr);
2022
4.00k
        if (current_time < calc_expiration(rowset)) { // not expired
2023
0
            return 0;
2024
0
        }
2025
4.00k
        ++num_expired;
2026
4.00k
        expired_rowset_size += v.size();
2027
4.00k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
2028
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
2029
                // in old version, keep this key-value pair and it needs to be checked manually
2030
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
2031
0
                return -1;
2032
0
            }
2033
250
            if (rowset.resource_id().empty()) [[unlikely]] {
2034
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
2035
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
2036
0
                          << hex(k) << " value=" << proto_to_json(rowset);
2037
0
                rowset_keys.emplace_back(k);
2038
0
                return -1;
2039
0
            }
2040
            // decode rowset_id
2041
250
            auto k1 = k;
2042
250
            k1.remove_prefix(1);
2043
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2044
250
            decode_key(&k1, &out);
2045
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
2046
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
2047
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
2048
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
2049
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
2050
250
                                             rowset.tablet_id(), rowset_id) != 0) {
2051
0
                return -1;
2052
0
            }
2053
250
            return 0;
2054
250
        }
2055
        // TODO(plat1ko): check rowset not referenced
2056
3.75k
        auto rowset_meta = rowset.mutable_rowset_meta();
2057
3.75k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
2058
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
2059
0
                LOG_INFO("recycle rowset that has empty resource id");
2060
0
            } else {
2061
                // other situations, keep this key-value pair and it needs to be checked manually
2062
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
2063
0
                return -1;
2064
0
            }
2065
0
        }
2066
3.75k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
2067
3.75k
                  << " tablet_id=" << rowset_meta->tablet_id()
2068
3.75k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
2069
3.75k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
2070
3.75k
                  << "] txn_id=" << rowset_meta->txn_id()
2071
3.75k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
2072
3.75k
                  << " rowset_meta_size=" << v.size()
2073
3.75k
                  << " creation_time=" << rowset_meta->creation_time();
2074
3.75k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
2075
            // unable to calculate file path, can only be deleted by rowset id prefix
2076
650
            num_prepare += 1;
2077
650
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
2078
650
                                             rowset_meta->tablet_id(),
2079
650
                                             rowset_meta->rowset_id_v2()) != 0) {
2080
0
                return -1;
2081
0
            }
2082
3.10k
        } else {
2083
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
2084
3.10k
            rowset_keys.emplace_back(k);
2085
3.10k
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
2086
3.10k
                rowsets.push_back(std::move(*rowset_meta));
2087
3.10k
            } else {
2088
0
                ++num_empty_rowset;
2089
0
            }
2090
3.10k
        }
2091
3.75k
        return 0;
2092
3.75k
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
2093
2094
21
    auto loop_done = [&]() -> int {
2095
21
        std::vector<std::string> rowset_keys_to_delete;
2096
21
        std::vector<doris::RowsetMetaCloudPB> rowsets_to_delete;
2097
21
        rowset_keys_to_delete.swap(rowset_keys);
2098
21
        rowsets_to_delete.swap(rowsets);
2099
21
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
2100
21
                             rowsets_to_delete = std::move(rowsets_to_delete)]() {
2101
21
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET) != 0) {
2102
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
2103
0
                return;
2104
0
            }
2105
21
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
2106
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2107
0
                return;
2108
0
            }
2109
21
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
2110
21
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
2100
21
                             rowsets_to_delete = std::move(rowsets_to_delete)]() {
2101
21
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET) != 0) {
2102
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
2103
0
                return;
2104
0
            }
2105
21
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
2106
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2107
0
                return;
2108
0
            }
2109
21
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
2110
21
        });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENKUlvE_clEv
2111
21
        return 0;
2112
21
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
2094
21
    auto loop_done = [&]() -> int {
2095
21
        std::vector<std::string> rowset_keys_to_delete;
2096
21
        std::vector<doris::RowsetMetaCloudPB> rowsets_to_delete;
2097
21
        rowset_keys_to_delete.swap(rowset_keys);
2098
21
        rowsets_to_delete.swap(rowsets);
2099
21
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
2100
21
                             rowsets_to_delete = std::move(rowsets_to_delete)]() {
2101
21
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET) != 0) {
2102
21
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
2103
21
                return;
2104
21
            }
2105
21
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
2106
21
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2107
21
                return;
2108
21
            }
2109
21
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
2110
21
        });
2111
21
        return 0;
2112
21
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
2113
2114
13
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
2115
13
                               std::move(loop_done));
2116
13
    worker_pool->stop();
2117
2118
13
    if (!async_recycled_rowset_keys.empty()) {
2119
2
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
2120
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2121
0
            return -1;
2122
2
        } else {
2123
2
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
2124
2
        }
2125
2
    }
2126
13
    return ret;
2127
13
}
2128
2129
bool is_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string& instance_id,
2130
3.05k
                     int64_t txn_id) {
2131
3.05k
    std::unique_ptr<Transaction> txn;
2132
3.05k
    TxnErrorCode err = txn_kv->create_txn(&txn);
2133
3.05k
    if (err != TxnErrorCode::TXN_OK) {
2134
0
        LOG(WARNING) << "failed to create txn, txn_id=" << txn_id << " instance_id=" << instance_id;
2135
0
        return false;
2136
0
    }
2137
2138
3.05k
    std::string index_val;
2139
3.05k
    const std::string index_key = txn_index_key({instance_id, txn_id});
2140
3.05k
    err = txn->get(index_key, &index_val);
2141
3.05k
    if (err != TxnErrorCode::TXN_OK) {
2142
3.03k
        if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
2143
3.03k
            TEST_SYNC_POINT_CALLBACK("is_txn_finished::txn_has_been_recycled");
2144
            // txn has been recycled;
2145
3.03k
            LOG(INFO) << "txn index key has been recycled, txn_id=" << txn_id
2146
3.03k
                      << " instance_id=" << instance_id;
2147
3.03k
            return true;
2148
3.03k
        }
2149
0
        LOG(WARNING) << "failed to get txn index key, txn_id=" << txn_id
2150
0
                     << " instance_id=" << instance_id << " key=" << hex(index_key)
2151
0
                     << " err=" << err;
2152
0
        return false;
2153
3.03k
    }
2154
2155
20
    TxnIndexPB index_pb;
2156
20
    if (!index_pb.ParseFromString(index_val)) {
2157
0
        LOG(WARNING) << "failed to parse txn_index_pb, txn_id=" << txn_id
2158
0
                     << " instance_id=" << instance_id;
2159
0
        return false;
2160
0
    }
2161
2162
20
    DCHECK(index_pb.has_tablet_index() == true);
2163
20
    if (!index_pb.tablet_index().has_db_id()) {
2164
        // In the previous version, the db_id was not set in the index_pb.
2165
        // If updating to the version which enable txn lazy commit, the db_id will be set.
2166
0
        LOG(INFO) << "txn index has no db_id, txn_id=" << txn_id << " instance_id=" << instance_id
2167
0
                  << " index=" << index_pb.ShortDebugString();
2168
0
        return true;
2169
0
    }
2170
2171
20
    int64_t db_id = index_pb.tablet_index().db_id();
2172
20
    DCHECK_GT(db_id, 0) << "db_id=" << db_id << " txn_id=" << txn_id
2173
0
                        << " instance_id=" << instance_id;
2174
2175
20
    std::string info_val;
2176
20
    const std::string info_key = txn_info_key({instance_id, db_id, txn_id});
2177
20
    err = txn->get(info_key, &info_val);
2178
20
    if (err != TxnErrorCode::TXN_OK) {
2179
0
        if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
2180
            // txn info has been recycled;
2181
0
            LOG(INFO) << "txn info key has been recycled, db_id=" << db_id << " txn_id=" << txn_id
2182
0
                      << " instance_id=" << instance_id;
2183
0
            return true;
2184
0
        }
2185
2186
0
        DCHECK(err != TxnErrorCode::TXN_KEY_NOT_FOUND);
2187
0
        LOG(WARNING) << "failed to get txn info key, txn_id=" << txn_id
2188
0
                     << " instance_id=" << instance_id << " key=" << hex(info_key)
2189
0
                     << " err=" << err;
2190
0
        return false;
2191
0
    }
2192
2193
20
    TxnInfoPB txn_info;
2194
20
    if (!txn_info.ParseFromString(info_val)) {
2195
0
        LOG(WARNING) << "failed to parse txn_info, txn_id=" << txn_id
2196
0
                     << " instance_id=" << instance_id;
2197
0
        return false;
2198
0
    }
2199
2200
20
    DCHECK(txn_info.txn_id() == txn_id) << "txn_id=" << txn_id << " instance_id=" << instance_id
2201
0
                                        << " txn_info=" << txn_info.ShortDebugString();
2202
2203
20
    if (TxnStatusPB::TXN_STATUS_ABORTED == txn_info.status() ||
2204
20
        TxnStatusPB::TXN_STATUS_VISIBLE == txn_info.status()) {
2205
10
        TEST_SYNC_POINT_CALLBACK("is_txn_finished::txn_has_been_aborted", &txn_info);
2206
10
        return true;
2207
10
    }
2208
2209
10
    TEST_SYNC_POINT_CALLBACK("is_txn_finished::txn_not_finished", &txn_info);
2210
10
    return false;
2211
20
}
2212
2213
17
int InstanceRecycler::recycle_tmp_rowsets() {
2214
17
    const std::string task_name = "recycle_tmp_rowsets";
2215
17
    int64_t num_scanned = 0;
2216
17
    int64_t num_expired = 0;
2217
17
    int64_t num_recycled = 0;
2218
17
    size_t expired_rowset_size = 0;
2219
17
    size_t total_rowset_key_size = 0;
2220
17
    size_t total_rowset_value_size = 0;
2221
2222
17
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
2223
17
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
2224
17
    std::string tmp_rs_key0;
2225
17
    std::string tmp_rs_key1;
2226
17
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
2227
17
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
2228
2229
17
    LOG_INFO("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
2230
2231
17
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2232
17
    register_recycle_task(task_name, start_time);
2233
2234
17
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
2235
17
        unregister_recycle_task(task_name);
2236
17
        int64_t cost =
2237
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2238
17
        LOG_INFO("recycle tmp rowsets finished, cost={}s", cost)
2239
17
                .tag("instance_id", instance_id_)
2240
17
                .tag("num_scanned", num_scanned)
2241
17
                .tag("num_expired", num_expired)
2242
17
                .tag("num_recycled", num_recycled)
2243
17
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
2244
17
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
2245
17
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
2246
17
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEPi
Line
Count
Source
2234
13
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
2235
13
        unregister_recycle_task(task_name);
2236
13
        int64_t cost =
2237
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2238
13
        LOG_INFO("recycle tmp rowsets finished, cost={}s", cost)
2239
13
                .tag("instance_id", instance_id_)
2240
13
                .tag("num_scanned", num_scanned)
2241
13
                .tag("num_expired", num_expired)
2242
13
                .tag("num_recycled", num_recycled)
2243
13
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
2244
13
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
2245
13
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
2246
13
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEPi
Line
Count
Source
2234
4
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
2235
4
        unregister_recycle_task(task_name);
2236
4
        int64_t cost =
2237
4
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2238
4
        LOG_INFO("recycle tmp rowsets finished, cost={}s", cost)
2239
4
                .tag("instance_id", instance_id_)
2240
4
                .tag("num_scanned", num_scanned)
2241
4
                .tag("num_expired", num_expired)
2242
4
                .tag("num_recycled", num_recycled)
2243
4
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
2244
4
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
2245
4
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
2246
4
    });
2247
2248
    // Elements in `tmp_rowset_keys` has the same lifetime as `it`
2249
17
    std::vector<std::string_view> tmp_rowset_keys;
2250
17
    std::vector<doris::RowsetMetaCloudPB> tmp_rowsets;
2251
2252
17
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2253
3.05k
    auto calc_expiration = [&earlest_ts, this](const doris::RowsetMetaCloudPB& rowset) {
2254
        // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
2255
        //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
2256
        //  duration or timeout always < `retention_time` in practice.
2257
3.05k
        int64_t expiration =
2258
3.05k
                rowset.txn_expiration() > 0 ? rowset.txn_expiration() : rowset.creation_time();
2259
3.05k
        expiration = config::force_immediate_recycle ? 0 : expiration;
2260
3.05k
        int64_t final_expiration = expiration + config::retention_seconds;
2261
3.05k
        if (earlest_ts > final_expiration) {
2262
6
            earlest_ts = final_expiration;
2263
6
            g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, earlest_ts);
2264
6
        }
2265
3.05k
        return final_expiration;
2266
3.05k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
2253
3.02k
    auto calc_expiration = [&earlest_ts, this](const doris::RowsetMetaCloudPB& rowset) {
2254
        // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
2255
        //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
2256
        //  duration or timeout always < `retention_time` in practice.
2257
3.02k
        int64_t expiration =
2258
3.02k
                rowset.txn_expiration() > 0 ? rowset.txn_expiration() : rowset.creation_time();
2259
3.02k
        expiration = config::force_immediate_recycle ? 0 : expiration;
2260
3.02k
        int64_t final_expiration = expiration + config::retention_seconds;
2261
3.02k
        if (earlest_ts > final_expiration) {
2262
3
            earlest_ts = final_expiration;
2263
3
            g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, earlest_ts);
2264
3
        }
2265
3.02k
        return final_expiration;
2266
3.02k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
2253
30
    auto calc_expiration = [&earlest_ts, this](const doris::RowsetMetaCloudPB& rowset) {
2254
        // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
2255
        //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
2256
        //  duration or timeout always < `retention_time` in practice.
2257
30
        int64_t expiration =
2258
30
                rowset.txn_expiration() > 0 ? rowset.txn_expiration() : rowset.creation_time();
2259
30
        expiration = config::force_immediate_recycle ? 0 : expiration;
2260
30
        int64_t final_expiration = expiration + config::retention_seconds;
2261
30
        if (earlest_ts > final_expiration) {
2262
3
            earlest_ts = final_expiration;
2263
3
            g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, earlest_ts);
2264
3
        }
2265
30
        return final_expiration;
2266
30
    };
2267
2268
17
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &tmp_rowsets,
2269
17
                             &expired_rowset_size, &total_rowset_key_size, &total_rowset_value_size,
2270
17
                             &calc_expiration,
2271
3.05k
                             this](std::string_view k, std::string_view v) -> int {
2272
3.05k
        ++num_scanned;
2273
3.05k
        total_rowset_key_size += k.size();
2274
3.05k
        total_rowset_value_size += v.size();
2275
3.05k
        doris::RowsetMetaCloudPB rowset;
2276
3.05k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
2277
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
2278
0
            return -1;
2279
0
        }
2280
3.05k
        int64_t expiration = calc_expiration(rowset);
2281
3.05k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
2282
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
2283
0
                   << " txn_expiration=" << rowset.txn_expiration()
2284
0
                   << " rowset_creation_time=" << rowset.creation_time();
2285
3.05k
        int64_t current_time = ::time(nullptr);
2286
3.05k
        if (current_time < expiration) { // not expired
2287
0
            return 0;
2288
0
        }
2289
2290
3.05k
        DCHECK_GT(rowset.txn_id(), 0)
2291
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
2292
3.05k
        if (!is_txn_finished(txn_kv_, instance_id_, rowset.txn_id())) {
2293
10
            LOG(INFO) << "txn is not finished, skip recycle tmp rowset, instance_id="
2294
10
                      << instance_id_ << " tablet_id=" << rowset.tablet_id()
2295
10
                      << " rowset_id=" << rowset.rowset_id_v2() << " version=["
2296
10
                      << rowset.start_version() << '-' << rowset.end_version()
2297
10
                      << "] txn_id=" << rowset.txn_id()
2298
10
                      << " creation_time=" << rowset.creation_time() << " expiration=" << expiration
2299
10
                      << " txn_expiration=" << rowset.txn_expiration();
2300
10
            return 0;
2301
10
        }
2302
2303
3.04k
        ++num_expired;
2304
3.04k
        expired_rowset_size += v.size();
2305
3.04k
        if (!rowset.has_resource_id()) {
2306
20
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
2307
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
2308
0
                return -1;
2309
0
            }
2310
            // might be a delete pred rowset
2311
20
            tmp_rowset_keys.push_back(k);
2312
20
            return 0;
2313
20
        }
2314
        // TODO(plat1ko): check rowset not referenced
2315
3.02k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
2316
3.02k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
2317
3.02k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
2318
3.02k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
2319
3.02k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
2320
3.02k
                  << " num_expired=" << num_expired;
2321
2322
3.02k
        tmp_rowset_keys.push_back(k);
2323
3.02k
        if (rowset.num_segments() > 0) { // Skip empty rowset
2324
3.02k
            tmp_rowsets.push_back(std::move(rowset));
2325
3.02k
        }
2326
3.02k
        return 0;
2327
3.04k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2271
3.02k
                             this](std::string_view k, std::string_view v) -> int {
2272
3.02k
        ++num_scanned;
2273
3.02k
        total_rowset_key_size += k.size();
2274
3.02k
        total_rowset_value_size += v.size();
2275
3.02k
        doris::RowsetMetaCloudPB rowset;
2276
3.02k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
2277
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
2278
0
            return -1;
2279
0
        }
2280
3.02k
        int64_t expiration = calc_expiration(rowset);
2281
3.02k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
2282
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
2283
0
                   << " txn_expiration=" << rowset.txn_expiration()
2284
0
                   << " rowset_creation_time=" << rowset.creation_time();
2285
3.02k
        int64_t current_time = ::time(nullptr);
2286
3.02k
        if (current_time < expiration) { // not expired
2287
0
            return 0;
2288
0
        }
2289
2290
3.02k
        DCHECK_GT(rowset.txn_id(), 0)
2291
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
2292
3.02k
        if (!is_txn_finished(txn_kv_, instance_id_, rowset.txn_id())) {
2293
0
            LOG(INFO) << "txn is not finished, skip recycle tmp rowset, instance_id="
2294
0
                      << instance_id_ << " tablet_id=" << rowset.tablet_id()
2295
0
                      << " rowset_id=" << rowset.rowset_id_v2() << " version=["
2296
0
                      << rowset.start_version() << '-' << rowset.end_version()
2297
0
                      << "] txn_id=" << rowset.txn_id()
2298
0
                      << " creation_time=" << rowset.creation_time() << " expiration=" << expiration
2299
0
                      << " txn_expiration=" << rowset.txn_expiration();
2300
0
            return 0;
2301
0
        }
2302
2303
3.02k
        ++num_expired;
2304
3.02k
        expired_rowset_size += v.size();
2305
3.02k
        if (!rowset.has_resource_id()) {
2306
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
2307
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
2308
0
                return -1;
2309
0
            }
2310
            // might be a delete pred rowset
2311
0
            tmp_rowset_keys.push_back(k);
2312
0
            return 0;
2313
0
        }
2314
        // TODO(plat1ko): check rowset not referenced
2315
3.02k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
2316
3.02k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
2317
3.02k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
2318
3.02k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
2319
3.02k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
2320
3.02k
                  << " num_expired=" << num_expired;
2321
2322
3.02k
        tmp_rowset_keys.push_back(k);
2323
3.02k
        if (rowset.num_segments() > 0) { // Skip empty rowset
2324
3.02k
            tmp_rowsets.push_back(std::move(rowset));
2325
3.02k
        }
2326
3.02k
        return 0;
2327
3.02k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2271
30
                             this](std::string_view k, std::string_view v) -> int {
2272
30
        ++num_scanned;
2273
30
        total_rowset_key_size += k.size();
2274
30
        total_rowset_value_size += v.size();
2275
30
        doris::RowsetMetaCloudPB rowset;
2276
30
        if (!rowset.ParseFromArray(v.data(), v.size())) {
2277
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
2278
0
            return -1;
2279
0
        }
2280
30
        int64_t expiration = calc_expiration(rowset);
2281
30
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
2282
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
2283
0
                   << " txn_expiration=" << rowset.txn_expiration()
2284
0
                   << " rowset_creation_time=" << rowset.creation_time();
2285
30
        int64_t current_time = ::time(nullptr);
2286
30
        if (current_time < expiration) { // not expired
2287
0
            return 0;
2288
0
        }
2289
2290
30
        DCHECK_GT(rowset.txn_id(), 0)
2291
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
2292
30
        if (!is_txn_finished(txn_kv_, instance_id_, rowset.txn_id())) {
2293
10
            LOG(INFO) << "txn is not finished, skip recycle tmp rowset, instance_id="
2294
10
                      << instance_id_ << " tablet_id=" << rowset.tablet_id()
2295
10
                      << " rowset_id=" << rowset.rowset_id_v2() << " version=["
2296
10
                      << rowset.start_version() << '-' << rowset.end_version()
2297
10
                      << "] txn_id=" << rowset.txn_id()
2298
10
                      << " creation_time=" << rowset.creation_time() << " expiration=" << expiration
2299
10
                      << " txn_expiration=" << rowset.txn_expiration();
2300
10
            return 0;
2301
10
        }
2302
2303
20
        ++num_expired;
2304
20
        expired_rowset_size += v.size();
2305
20
        if (!rowset.has_resource_id()) {
2306
20
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
2307
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
2308
0
                return -1;
2309
0
            }
2310
            // might be a delete pred rowset
2311
20
            tmp_rowset_keys.push_back(k);
2312
20
            return 0;
2313
20
        }
2314
        // TODO(plat1ko): check rowset not referenced
2315
0
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
2316
0
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
2317
0
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
2318
0
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
2319
0
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
2320
0
                  << " num_expired=" << num_expired;
2321
2322
0
        tmp_rowset_keys.push_back(k);
2323
0
        if (rowset.num_segments() > 0) { // Skip empty rowset
2324
0
            tmp_rowsets.push_back(std::move(rowset));
2325
0
        }
2326
0
        return 0;
2327
20
    };
2328
2329
17
    auto loop_done = [&tmp_rowset_keys, &tmp_rowsets, &num_recycled, this]() -> int {
2330
6
        std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01, [&](int*) {
2331
6
            tmp_rowset_keys.clear();
2332
6
            tmp_rowsets.clear();
2333
6
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEvENKUlPiE_clES3_
Line
Count
Source
2330
3
        std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01, [&](int*) {
2331
3
            tmp_rowset_keys.clear();
2332
3
            tmp_rowsets.clear();
2333
3
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEvENKUlPiE_clES3_
Line
Count
Source
2330
3
        std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01, [&](int*) {
2331
3
            tmp_rowset_keys.clear();
2332
3
            tmp_rowsets.clear();
2333
3
        });
2334
6
        if (delete_rowset_data(tmp_rowsets, RowsetRecyclingState::TMP_ROWSET) != 0) {
2335
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2336
0
            return -1;
2337
0
        }
2338
6
        if (txn_remove(txn_kv_.get(), tmp_rowset_keys) != 0) {
2339
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2340
0
            return -1;
2341
0
        }
2342
6
        num_recycled += tmp_rowset_keys.size();
2343
6
        return 0;
2344
6
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEv
Line
Count
Source
2329
3
    auto loop_done = [&tmp_rowset_keys, &tmp_rowsets, &num_recycled, this]() -> int {
2330
3
        std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01, [&](int*) {
2331
3
            tmp_rowset_keys.clear();
2332
3
            tmp_rowsets.clear();
2333
3
        });
2334
3
        if (delete_rowset_data(tmp_rowsets, RowsetRecyclingState::TMP_ROWSET) != 0) {
2335
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2336
0
            return -1;
2337
0
        }
2338
3
        if (txn_remove(txn_kv_.get(), tmp_rowset_keys) != 0) {
2339
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2340
0
            return -1;
2341
0
        }
2342
3
        num_recycled += tmp_rowset_keys.size();
2343
3
        return 0;
2344
3
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEv
Line
Count
Source
2329
3
    auto loop_done = [&tmp_rowset_keys, &tmp_rowsets, &num_recycled, this]() -> int {
2330
3
        std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01, [&](int*) {
2331
3
            tmp_rowset_keys.clear();
2332
3
            tmp_rowsets.clear();
2333
3
        });
2334
3
        if (delete_rowset_data(tmp_rowsets, RowsetRecyclingState::TMP_ROWSET) != 0) {
2335
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2336
0
            return -1;
2337
0
        }
2338
3
        if (txn_remove(txn_kv_.get(), tmp_rowset_keys) != 0) {
2339
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2340
0
            return -1;
2341
0
        }
2342
3
        num_recycled += tmp_rowset_keys.size();
2343
3
        return 0;
2344
3
    };
2345
2346
17
    return scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
2347
17
                            std::move(loop_done));
2348
17
}
2349
2350
int InstanceRecycler::scan_and_recycle(
2351
        std::string begin, std::string_view end,
2352
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
2353
174
        std::function<int()> loop_done) {
2354
174
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
2355
174
    int ret = 0;
2356
174
    int64_t cnt = 0;
2357
174
    int get_range_retried = 0;
2358
174
    std::string err;
2359
174
    std::unique_ptr<int, std::function<void(int*)>> defer_log(
2360
174
            (int*)0x01, [begin, end, &err, &ret, &cnt, &get_range_retried](int*) {
2361
174
                LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
2362
174
                          << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
2363
174
                          << " ret=" << ret << " err=" << err;
2364
174
            });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEPi
Line
Count
Source
2360
155
            (int*)0x01, [begin, end, &err, &ret, &cnt, &get_range_retried](int*) {
2361
155
                LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
2362
155
                          << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
2363
155
                          << " ret=" << ret << " err=" << err;
2364
155
            });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEPi
Line
Count
Source
2360
19
            (int*)0x01, [begin, end, &err, &ret, &cnt, &get_range_retried](int*) {
2361
19
                LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
2362
19
                          << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
2363
19
                          << " ret=" << ret << " err=" << err;
2364
19
            });
2365
2366
174
    std::unique_ptr<RangeGetIterator> it;
2367
194
    do {
2368
194
        if (get_range_retried > 1000) {
2369
0
            err = "txn_get exceeds max retry, may not scan all keys";
2370
0
            ret = -1;
2371
0
            return -1;
2372
0
        }
2373
194
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
2374
194
        if (get_ret != 0) { // txn kv may complain "Request for future version"
2375
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
2376
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
2377
0
                         << " get_range_retried=" << get_range_retried;
2378
0
            ++get_range_retried;
2379
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
2380
0
            continue; // try again
2381
0
        }
2382
194
        if (!it->has_next()) {
2383
92
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
2384
92
            break; // scan finished
2385
92
        }
2386
37.4k
        while (it->has_next()) {
2387
37.3k
            ++cnt;
2388
            // recycle corresponding resources
2389
37.3k
            auto [k, v] = it->next();
2390
37.3k
            if (!it->has_next()) {
2391
102
                begin = k;
2392
102
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
2393
102
            }
2394
            // if we want to continue scanning, the recycle_func should not return non-zero
2395
37.3k
            if (recycle_func(k, v) != 0) {
2396
22
                err = "recycle_func error";
2397
22
                ret = -1;
2398
22
            }
2399
37.3k
        }
2400
102
        begin.push_back('\x00'); // Update to next smallest key for iteration
2401
        // if we want to continue scanning, the recycle_func should not return non-zero
2402
102
        if (loop_done && loop_done() != 0) {
2403
2
            err = "loop_done error";
2404
2
            ret = -1;
2405
2
        }
2406
102
    } while (it->more() && !stopped());
2407
174
    return ret;
2408
174
}
2409
2410
20
int InstanceRecycler::abort_timeout_txn() {
2411
20
    const std::string task_name = "abort_timeout_txn";
2412
20
    int64_t num_scanned = 0;
2413
20
    int64_t num_timeout = 0;
2414
20
    int64_t num_abort = 0;
2415
20
    int64_t num_advance = 0;
2416
2417
20
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
2418
20
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
2419
20
    std::string begin_txn_running_key;
2420
20
    std::string end_txn_running_key;
2421
20
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
2422
20
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
2423
2424
20
    LOG_INFO("begin to abort timeout txn").tag("instance_id", instance_id_);
2425
2426
20
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2427
20
    register_recycle_task(task_name, start_time);
2428
2429
20
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
2430
20
        unregister_recycle_task(task_name);
2431
20
        int64_t cost =
2432
20
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2433
20
        LOG_INFO("end to abort timeout txn, cost={}s", cost)
2434
20
                .tag("instance_id", instance_id_)
2435
20
                .tag("num_scanned", num_scanned)
2436
20
                .tag("num_timeout", num_timeout)
2437
20
                .tag("num_abort", num_abort)
2438
20
                .tag("num_advance", num_advance);
2439
20
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEPi
Line
Count
Source
2429
16
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
2430
16
        unregister_recycle_task(task_name);
2431
16
        int64_t cost =
2432
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2433
16
        LOG_INFO("end to abort timeout txn, cost={}s", cost)
2434
16
                .tag("instance_id", instance_id_)
2435
16
                .tag("num_scanned", num_scanned)
2436
16
                .tag("num_timeout", num_timeout)
2437
16
                .tag("num_abort", num_abort)
2438
16
                .tag("num_advance", num_advance);
2439
16
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEPi
Line
Count
Source
2429
4
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
2430
4
        unregister_recycle_task(task_name);
2431
4
        int64_t cost =
2432
4
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2433
4
        LOG_INFO("end to abort timeout txn, cost={}s", cost)
2434
4
                .tag("instance_id", instance_id_)
2435
4
                .tag("num_scanned", num_scanned)
2436
4
                .tag("num_timeout", num_timeout)
2437
4
                .tag("num_abort", num_abort)
2438
4
                .tag("num_advance", num_advance);
2439
4
    });
2440
2441
20
    int64_t current_time =
2442
20
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
2443
2444
20
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
2445
20
                                  &current_time,
2446
20
                                  this](std::string_view k, std::string_view v) -> int {
2447
10
        ++num_scanned;
2448
2449
10
        std::unique_ptr<Transaction> txn;
2450
10
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2451
10
        if (err != TxnErrorCode::TXN_OK) {
2452
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
2453
0
            return -1;
2454
0
        }
2455
10
        std::string_view k1 = k;
2456
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
2457
10
        k1.remove_prefix(1); // Remove key space
2458
10
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2459
10
        if (decode_key(&k1, &out) != 0) {
2460
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
2461
0
            return -1;
2462
0
        }
2463
10
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
2464
10
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
2465
10
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
2466
        // Update txn_info
2467
10
        std::string txn_inf_key, txn_inf_val;
2468
10
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
2469
10
        err = txn->get(txn_inf_key, &txn_inf_val);
2470
10
        if (err != TxnErrorCode::TXN_OK) {
2471
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
2472
0
            return -1;
2473
0
        }
2474
10
        TxnInfoPB txn_info;
2475
10
        if (!txn_info.ParseFromString(txn_inf_val)) {
2476
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
2477
0
            return -1;
2478
0
        }
2479
2480
10
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
2481
4
            txn.reset();
2482
4
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
2483
4
            std::shared_ptr<TxnLazyCommitTask> task =
2484
4
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
2485
4
            std::pair<MetaServiceCode, std::string> ret = task->wait();
2486
4
            if (ret.first != MetaServiceCode::OK) {
2487
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
2488
0
                             << "msg=" << ret.second;
2489
0
                return -1;
2490
0
            }
2491
4
            ++num_advance;
2492
4
            return 0;
2493
6
        } else {
2494
6
            TxnRunningPB txn_running_pb;
2495
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
2496
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
2497
0
                return -1;
2498
0
            }
2499
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
2500
4
                return 0;
2501
4
            }
2502
2
            ++num_timeout;
2503
2504
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
2505
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
2506
2
            txn_info.set_finish_time(current_time);
2507
2
            txn_info.set_reason("timeout");
2508
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
2509
2
            txn_inf_val.clear();
2510
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
2511
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
2512
0
                return -1;
2513
0
            }
2514
2
            txn->put(txn_inf_key, txn_inf_val);
2515
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
2516
            // Put recycle txn key
2517
2
            std::string recyc_txn_key, recyc_txn_val;
2518
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
2519
2
            RecycleTxnPB recycle_txn_pb;
2520
2
            recycle_txn_pb.set_creation_time(current_time);
2521
2
            recycle_txn_pb.set_label(txn_info.label());
2522
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
2523
0
                LOG_WARNING("failed to serialize txn recycle info")
2524
0
                        .tag("key", hex(k))
2525
0
                        .tag("db_id", db_id)
2526
0
                        .tag("txn_id", txn_id);
2527
0
                return -1;
2528
0
            }
2529
2
            txn->put(recyc_txn_key, recyc_txn_val);
2530
            // Remove txn running key
2531
2
            txn->remove(k);
2532
2
            err = txn->commit();
2533
2
            if (err != TxnErrorCode::TXN_OK) {
2534
0
                LOG_WARNING("failed to commit txn err={}", err)
2535
0
                        .tag("key", hex(k))
2536
0
                        .tag("db_id", db_id)
2537
0
                        .tag("txn_id", txn_id);
2538
0
                return -1;
2539
0
            }
2540
2
            ++num_abort;
2541
2
        }
2542
2543
2
        return 0;
2544
10
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2446
6
                                  this](std::string_view k, std::string_view v) -> int {
2447
6
        ++num_scanned;
2448
2449
6
        std::unique_ptr<Transaction> txn;
2450
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2451
6
        if (err != TxnErrorCode::TXN_OK) {
2452
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
2453
0
            return -1;
2454
0
        }
2455
6
        std::string_view k1 = k;
2456
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
2457
6
        k1.remove_prefix(1); // Remove key space
2458
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2459
6
        if (decode_key(&k1, &out) != 0) {
2460
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
2461
0
            return -1;
2462
0
        }
2463
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
2464
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
2465
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
2466
        // Update txn_info
2467
6
        std::string txn_inf_key, txn_inf_val;
2468
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
2469
6
        err = txn->get(txn_inf_key, &txn_inf_val);
2470
6
        if (err != TxnErrorCode::TXN_OK) {
2471
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
2472
0
            return -1;
2473
0
        }
2474
6
        TxnInfoPB txn_info;
2475
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
2476
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
2477
0
            return -1;
2478
0
        }
2479
2480
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
2481
0
            txn.reset();
2482
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
2483
0
            std::shared_ptr<TxnLazyCommitTask> task =
2484
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
2485
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
2486
0
            if (ret.first != MetaServiceCode::OK) {
2487
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
2488
0
                             << "msg=" << ret.second;
2489
0
                return -1;
2490
0
            }
2491
0
            ++num_advance;
2492
0
            return 0;
2493
6
        } else {
2494
6
            TxnRunningPB txn_running_pb;
2495
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
2496
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
2497
0
                return -1;
2498
0
            }
2499
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
2500
4
                return 0;
2501
4
            }
2502
2
            ++num_timeout;
2503
2504
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
2505
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
2506
2
            txn_info.set_finish_time(current_time);
2507
2
            txn_info.set_reason("timeout");
2508
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
2509
2
            txn_inf_val.clear();
2510
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
2511
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
2512
0
                return -1;
2513
0
            }
2514
2
            txn->put(txn_inf_key, txn_inf_val);
2515
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
2516
            // Put recycle txn key
2517
2
            std::string recyc_txn_key, recyc_txn_val;
2518
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
2519
2
            RecycleTxnPB recycle_txn_pb;
2520
2
            recycle_txn_pb.set_creation_time(current_time);
2521
2
            recycle_txn_pb.set_label(txn_info.label());
2522
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
2523
0
                LOG_WARNING("failed to serialize txn recycle info")
2524
0
                        .tag("key", hex(k))
2525
0
                        .tag("db_id", db_id)
2526
0
                        .tag("txn_id", txn_id);
2527
0
                return -1;
2528
0
            }
2529
2
            txn->put(recyc_txn_key, recyc_txn_val);
2530
            // Remove txn running key
2531
2
            txn->remove(k);
2532
2
            err = txn->commit();
2533
2
            if (err != TxnErrorCode::TXN_OK) {
2534
0
                LOG_WARNING("failed to commit txn err={}", err)
2535
0
                        .tag("key", hex(k))
2536
0
                        .tag("db_id", db_id)
2537
0
                        .tag("txn_id", txn_id);
2538
0
                return -1;
2539
0
            }
2540
2
            ++num_abort;
2541
2
        }
2542
2543
2
        return 0;
2544
6
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2446
4
                                  this](std::string_view k, std::string_view v) -> int {
2447
4
        ++num_scanned;
2448
2449
4
        std::unique_ptr<Transaction> txn;
2450
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2451
4
        if (err != TxnErrorCode::TXN_OK) {
2452
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
2453
0
            return -1;
2454
0
        }
2455
4
        std::string_view k1 = k;
2456
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
2457
4
        k1.remove_prefix(1); // Remove key space
2458
4
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2459
4
        if (decode_key(&k1, &out) != 0) {
2460
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
2461
0
            return -1;
2462
0
        }
2463
4
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
2464
4
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
2465
4
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
2466
        // Update txn_info
2467
4
        std::string txn_inf_key, txn_inf_val;
2468
4
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
2469
4
        err = txn->get(txn_inf_key, &txn_inf_val);
2470
4
        if (err != TxnErrorCode::TXN_OK) {
2471
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
2472
0
            return -1;
2473
0
        }
2474
4
        TxnInfoPB txn_info;
2475
4
        if (!txn_info.ParseFromString(txn_inf_val)) {
2476
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
2477
0
            return -1;
2478
0
        }
2479
2480
4
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
2481
4
            txn.reset();
2482
4
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
2483
4
            std::shared_ptr<TxnLazyCommitTask> task =
2484
4
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
2485
4
            std::pair<MetaServiceCode, std::string> ret = task->wait();
2486
4
            if (ret.first != MetaServiceCode::OK) {
2487
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
2488
0
                             << "msg=" << ret.second;
2489
0
                return -1;
2490
0
            }
2491
4
            ++num_advance;
2492
4
            return 0;
2493
4
        } else {
2494
0
            TxnRunningPB txn_running_pb;
2495
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
2496
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
2497
0
                return -1;
2498
0
            }
2499
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
2500
0
                return 0;
2501
0
            }
2502
0
            ++num_timeout;
2503
2504
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
2505
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
2506
0
            txn_info.set_finish_time(current_time);
2507
0
            txn_info.set_reason("timeout");
2508
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
2509
0
            txn_inf_val.clear();
2510
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
2511
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
2512
0
                return -1;
2513
0
            }
2514
0
            txn->put(txn_inf_key, txn_inf_val);
2515
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
2516
            // Put recycle txn key
2517
0
            std::string recyc_txn_key, recyc_txn_val;
2518
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
2519
0
            RecycleTxnPB recycle_txn_pb;
2520
0
            recycle_txn_pb.set_creation_time(current_time);
2521
0
            recycle_txn_pb.set_label(txn_info.label());
2522
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
2523
0
                LOG_WARNING("failed to serialize txn recycle info")
2524
0
                        .tag("key", hex(k))
2525
0
                        .tag("db_id", db_id)
2526
0
                        .tag("txn_id", txn_id);
2527
0
                return -1;
2528
0
            }
2529
0
            txn->put(recyc_txn_key, recyc_txn_val);
2530
            // Remove txn running key
2531
0
            txn->remove(k);
2532
0
            err = txn->commit();
2533
0
            if (err != TxnErrorCode::TXN_OK) {
2534
0
                LOG_WARNING("failed to commit txn err={}", err)
2535
0
                        .tag("key", hex(k))
2536
0
                        .tag("db_id", db_id)
2537
0
                        .tag("txn_id", txn_id);
2538
0
                return -1;
2539
0
            }
2540
0
            ++num_abort;
2541
0
        }
2542
2543
0
        return 0;
2544
4
    };
2545
2546
20
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
2547
20
                            std::move(handle_txn_running_kv));
2548
20
}
2549
2550
19
int InstanceRecycler::recycle_expired_txn_label() {
2551
19
    const std::string task_name = "recycle_expired_txn_label";
2552
19
    int64_t num_scanned = 0;
2553
19
    int64_t num_expired = 0;
2554
19
    int64_t num_recycled = 0;
2555
19
    int ret = 0;
2556
2557
19
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
2558
19
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
2559
19
    std::string begin_recycle_txn_key;
2560
19
    std::string end_recycle_txn_key;
2561
19
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
2562
19
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
2563
19
    std::vector<std::string> recycle_txn_info_keys;
2564
2565
19
    LOG_INFO("begin to recycle expired txn").tag("instance_id", instance_id_);
2566
2567
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2568
19
    register_recycle_task(task_name, start_time);
2569
19
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
2570
19
        unregister_recycle_task(task_name);
2571
19
        int64_t cost =
2572
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2573
19
        LOG_INFO("end to recycle expired txn, cost={}s", cost)
2574
19
                .tag("instance_id", instance_id_)
2575
19
                .tag("num_scanned", num_scanned)
2576
19
                .tag("num_expired", num_expired)
2577
19
                .tag("num_recycled", num_recycled);
2578
19
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEPi
Line
Count
Source
2569
16
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
2570
16
        unregister_recycle_task(task_name);
2571
16
        int64_t cost =
2572
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2573
16
        LOG_INFO("end to recycle expired txn, cost={}s", cost)
2574
16
                .tag("instance_id", instance_id_)
2575
16
                .tag("num_scanned", num_scanned)
2576
16
                .tag("num_expired", num_expired)
2577
16
                .tag("num_recycled", num_recycled);
2578
16
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEPi
Line
Count
Source
2569
3
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
2570
3
        unregister_recycle_task(task_name);
2571
3
        int64_t cost =
2572
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2573
3
        LOG_INFO("end to recycle expired txn, cost={}s", cost)
2574
3
                .tag("instance_id", instance_id_)
2575
3
                .tag("num_scanned", num_scanned)
2576
3
                .tag("num_expired", num_expired)
2577
3
                .tag("num_recycled", num_recycled);
2578
3
    });
2579
2580
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2581
30.0k
    auto calc_expiration = [&earlest_ts, this](const RecycleTxnPB& recycle_txn_pb) {
2582
30.0k
        int64_t final_expiration =
2583
30.0k
                recycle_txn_pb.creation_time() + config::label_keep_max_second * 1000L;
2584
30.0k
        if (earlest_ts > final_expiration / 1000) {
2585
6
            earlest_ts = final_expiration / 1000;
2586
6
            g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, earlest_ts);
2587
6
        }
2588
30.0k
        return final_expiration;
2589
30.0k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNS0_12RecycleTxnPBE
Line
Count
Source
2581
30.0k
    auto calc_expiration = [&earlest_ts, this](const RecycleTxnPB& recycle_txn_pb) {
2582
30.0k
        int64_t final_expiration =
2583
30.0k
                recycle_txn_pb.creation_time() + config::label_keep_max_second * 1000L;
2584
30.0k
        if (earlest_ts > final_expiration / 1000) {
2585
6
            earlest_ts = final_expiration / 1000;
2586
6
            g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, earlest_ts);
2587
6
        }
2588
30.0k
        return final_expiration;
2589
30.0k
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNS0_12RecycleTxnPBE
2590
2591
19
    SyncExecutor<int> concurrent_delete_executor(
2592
19
            _thread_pool_group.s3_producer_pool,
2593
19
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
2594
23.0k
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
2594
23.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
2594
3
            [](const int& ret) { return ret != 0; });
2595
2596
19
    int64_t current_time_ms =
2597
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
2598
2599
30.0k
    auto handle_recycle_txn_kv = [&](std::string_view k, std::string_view v) -> int {
2600
30.0k
        ++num_scanned;
2601
30.0k
        RecycleTxnPB recycle_txn_pb;
2602
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
2603
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
2604
0
            return -1;
2605
0
        }
2606
30.0k
        if ((config::force_immediate_recycle) ||
2607
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
2608
30.0k
            (calc_expiration(recycle_txn_pb) <= current_time_ms)) {
2609
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
2610
23.0k
            num_expired++;
2611
23.0k
            recycle_txn_info_keys.emplace_back(k);
2612
23.0k
        }
2613
30.0k
        return 0;
2614
30.0k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2599
30.0k
    auto handle_recycle_txn_kv = [&](std::string_view k, std::string_view v) -> int {
2600
30.0k
        ++num_scanned;
2601
30.0k
        RecycleTxnPB recycle_txn_pb;
2602
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
2603
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
2604
0
            return -1;
2605
0
        }
2606
30.0k
        if ((config::force_immediate_recycle) ||
2607
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
2608
30.0k
            (calc_expiration(recycle_txn_pb) <= current_time_ms)) {
2609
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
2610
23.0k
            num_expired++;
2611
23.0k
            recycle_txn_info_keys.emplace_back(k);
2612
23.0k
        }
2613
30.0k
        return 0;
2614
30.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2599
3
    auto handle_recycle_txn_kv = [&](std::string_view k, std::string_view v) -> int {
2600
3
        ++num_scanned;
2601
3
        RecycleTxnPB recycle_txn_pb;
2602
3
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
2603
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
2604
0
            return -1;
2605
0
        }
2606
3
        if ((config::force_immediate_recycle) ||
2607
3
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
2608
3
            (calc_expiration(recycle_txn_pb) <= current_time_ms)) {
2609
3
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
2610
3
            num_expired++;
2611
3
            recycle_txn_info_keys.emplace_back(k);
2612
3
        }
2613
3
        return 0;
2614
3
    };
2615
2616
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
2617
23.0k
        std::string_view k1 = k;
2618
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
2619
23.0k
        k1.remove_prefix(1); // Remove key space
2620
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2621
23.0k
        int ret = decode_key(&k1, &out);
2622
23.0k
        if (ret != 0) {
2623
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
2624
0
            return -1;
2625
0
        }
2626
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
2627
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
2628
18.4E
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
2629
23.0k
        std::unique_ptr<Transaction> txn;
2630
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2631
23.0k
        if (err != TxnErrorCode::TXN_OK) {
2632
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
2633
0
            return -1;
2634
0
        }
2635
        // Remove txn index kv
2636
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
2637
23.0k
        txn->remove(index_key);
2638
        // Remove txn info kv
2639
23.0k
        std::string info_key, info_val;
2640
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
2641
23.0k
        err = txn->get(info_key, &info_val);
2642
23.0k
        if (err != TxnErrorCode::TXN_OK) {
2643
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
2644
0
            return -1;
2645
0
        }
2646
23.0k
        TxnInfoPB txn_info;
2647
23.0k
        if (!txn_info.ParseFromString(info_val)) {
2648
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
2649
0
            return -1;
2650
0
        }
2651
23.0k
        txn->remove(info_key);
2652
        // Remove sub txn index kvs
2653
23.0k
        std::vector<std::string> sub_txn_index_keys;
2654
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
2655
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
2656
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
2657
22.9k
        }
2658
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
2659
22.9k
            txn->remove(sub_txn_index_key);
2660
22.9k
        }
2661
        // Update txn label
2662
23.0k
        std::string label_key, label_val;
2663
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
2664
23.0k
        err = txn->get(label_key, &label_val);
2665
23.0k
        if (err != TxnErrorCode::TXN_OK) {
2666
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
2667
0
                         << " err=" << err;
2668
0
            return -1;
2669
0
        }
2670
23.0k
        TxnLabelPB txn_label;
2671
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
2672
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
2673
0
            return -1;
2674
0
        }
2675
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
2676
23.0k
        if (it != txn_label.txn_ids().end()) {
2677
23.0k
            txn_label.mutable_txn_ids()->erase(it);
2678
23.0k
        }
2679
23.0k
        if (txn_label.txn_ids().empty()) {
2680
23.0k
            txn->remove(label_key);
2681
18.4E
        } else {
2682
18.4E
            if (!txn_label.SerializeToString(&label_val)) {
2683
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
2684
0
                return -1;
2685
0
            }
2686
18.4E
            txn->atomic_set_ver_value(label_key, label_val);
2687
18.4E
        }
2688
        // Remove recycle txn kv
2689
23.0k
        txn->remove(k);
2690
23.0k
        err = txn->commit();
2691
23.0k
        if (err != TxnErrorCode::TXN_OK) {
2692
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
2693
0
            return -1;
2694
0
        }
2695
23.0k
        ++num_recycled;
2696
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
2697
23.0k
        return 0;
2698
23.0k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_5clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
2616
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
2617
23.0k
        std::string_view k1 = k;
2618
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
2619
23.0k
        k1.remove_prefix(1); // Remove key space
2620
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2621
23.0k
        int ret = decode_key(&k1, &out);
2622
23.0k
        if (ret != 0) {
2623
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
2624
0
            return -1;
2625
0
        }
2626
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
2627
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
2628
18.4E
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
2629
23.0k
        std::unique_ptr<Transaction> txn;
2630
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2631
23.0k
        if (err != TxnErrorCode::TXN_OK) {
2632
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
2633
0
            return -1;
2634
0
        }
2635
        // Remove txn index kv
2636
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
2637
23.0k
        txn->remove(index_key);
2638
        // Remove txn info kv
2639
23.0k
        std::string info_key, info_val;
2640
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
2641
23.0k
        err = txn->get(info_key, &info_val);
2642
23.0k
        if (err != TxnErrorCode::TXN_OK) {
2643
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
2644
0
            return -1;
2645
0
        }
2646
23.0k
        TxnInfoPB txn_info;
2647
23.0k
        if (!txn_info.ParseFromString(info_val)) {
2648
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
2649
0
            return -1;
2650
0
        }
2651
23.0k
        txn->remove(info_key);
2652
        // Remove sub txn index kvs
2653
23.0k
        std::vector<std::string> sub_txn_index_keys;
2654
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
2655
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
2656
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
2657
22.9k
        }
2658
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
2659
22.9k
            txn->remove(sub_txn_index_key);
2660
22.9k
        }
2661
        // Update txn label
2662
23.0k
        std::string label_key, label_val;
2663
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
2664
23.0k
        err = txn->get(label_key, &label_val);
2665
23.0k
        if (err != TxnErrorCode::TXN_OK) {
2666
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
2667
0
                         << " err=" << err;
2668
0
            return -1;
2669
0
        }
2670
23.0k
        TxnLabelPB txn_label;
2671
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
2672
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
2673
0
            return -1;
2674
0
        }
2675
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
2676
23.0k
        if (it != txn_label.txn_ids().end()) {
2677
23.0k
            txn_label.mutable_txn_ids()->erase(it);
2678
23.0k
        }
2679
23.0k
        if (txn_label.txn_ids().empty()) {
2680
23.0k
            txn->remove(label_key);
2681
18.4E
        } else {
2682
18.4E
            if (!txn_label.SerializeToString(&label_val)) {
2683
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
2684
0
                return -1;
2685
0
            }
2686
18.4E
            txn->atomic_set_ver_value(label_key, label_val);
2687
18.4E
        }
2688
        // Remove recycle txn kv
2689
23.0k
        txn->remove(k);
2690
23.0k
        err = txn->commit();
2691
23.0k
        if (err != TxnErrorCode::TXN_OK) {
2692
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
2693
0
            return -1;
2694
0
        }
2695
23.0k
        ++num_recycled;
2696
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
2697
23.0k
        return 0;
2698
23.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_5clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
2616
3
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
2617
3
        std::string_view k1 = k;
2618
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
2619
3
        k1.remove_prefix(1); // Remove key space
2620
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2621
3
        int ret = decode_key(&k1, &out);
2622
3
        if (ret != 0) {
2623
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
2624
0
            return -1;
2625
0
        }
2626
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
2627
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
2628
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
2629
3
        std::unique_ptr<Transaction> txn;
2630
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2631
3
        if (err != TxnErrorCode::TXN_OK) {
2632
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
2633
0
            return -1;
2634
0
        }
2635
        // Remove txn index kv
2636
3
        auto index_key = txn_index_key({instance_id_, txn_id});
2637
3
        txn->remove(index_key);
2638
        // Remove txn info kv
2639
3
        std::string info_key, info_val;
2640
3
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
2641
3
        err = txn->get(info_key, &info_val);
2642
3
        if (err != TxnErrorCode::TXN_OK) {
2643
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
2644
0
            return -1;
2645
0
        }
2646
3
        TxnInfoPB txn_info;
2647
3
        if (!txn_info.ParseFromString(info_val)) {
2648
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
2649
0
            return -1;
2650
0
        }
2651
3
        txn->remove(info_key);
2652
        // Remove sub txn index kvs
2653
3
        std::vector<std::string> sub_txn_index_keys;
2654
3
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
2655
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
2656
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
2657
0
        }
2658
3
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
2659
0
            txn->remove(sub_txn_index_key);
2660
0
        }
2661
        // Update txn label
2662
3
        std::string label_key, label_val;
2663
3
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
2664
3
        err = txn->get(label_key, &label_val);
2665
3
        if (err != TxnErrorCode::TXN_OK) {
2666
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
2667
0
                         << " err=" << err;
2668
0
            return -1;
2669
0
        }
2670
3
        TxnLabelPB txn_label;
2671
3
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
2672
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
2673
0
            return -1;
2674
0
        }
2675
3
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
2676
3
        if (it != txn_label.txn_ids().end()) {
2677
3
            txn_label.mutable_txn_ids()->erase(it);
2678
3
        }
2679
3
        if (txn_label.txn_ids().empty()) {
2680
3
            txn->remove(label_key);
2681
3
        } else {
2682
0
            if (!txn_label.SerializeToString(&label_val)) {
2683
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
2684
0
                return -1;
2685
0
            }
2686
0
            txn->atomic_set_ver_value(label_key, label_val);
2687
0
        }
2688
        // Remove recycle txn kv
2689
3
        txn->remove(k);
2690
3
        err = txn->commit();
2691
3
        if (err != TxnErrorCode::TXN_OK) {
2692
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
2693
0
            return -1;
2694
0
        }
2695
3
        ++num_recycled;
2696
3
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
2697
3
        return 0;
2698
3
    };
2699
2700
19
    auto loop_done = [&]() -> int {
2701
10
        std::unique_ptr<int, std::function<void(int*)>> defer(
2702
10
                (int*)0x01, [&](int*) { recycle_txn_info_keys.clear(); });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clEvENKUlPiE_clES3_
Line
Count
Source
2702
7
                (int*)0x01, [&](int*) { recycle_txn_info_keys.clear(); });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clEvENKUlPiE_clES3_
Line
Count
Source
2702
3
                (int*)0x01, [&](int*) { recycle_txn_info_keys.clear(); });
2703
10
        TEST_SYNC_POINT_CALLBACK(
2704
10
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
2705
10
                &recycle_txn_info_keys);
2706
23.0k
        for (const auto& k : recycle_txn_info_keys) {
2707
23.0k
            concurrent_delete_executor.add([&]() {
2708
23.0k
                if (delete_recycle_txn_kv(k) != 0) {
2709
0
                    LOG_WARNING("failed to delete recycle txn kv")
2710
0
                            .tag("instance id", instance_id_)
2711
0
                            .tag("key", hex(k));
2712
0
                    return -1;
2713
0
                }
2714
23.0k
                return 0;
2715
23.0k
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clEvENKUlvE_clEv
Line
Count
Source
2707
23.0k
            concurrent_delete_executor.add([&]() {
2708
23.0k
                if (delete_recycle_txn_kv(k) != 0) {
2709
0
                    LOG_WARNING("failed to delete recycle txn kv")
2710
0
                            .tag("instance id", instance_id_)
2711
0
                            .tag("key", hex(k));
2712
0
                    return -1;
2713
0
                }
2714
23.0k
                return 0;
2715
23.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clEvENKUlvE_clEv
Line
Count
Source
2707
3
            concurrent_delete_executor.add([&]() {
2708
3
                if (delete_recycle_txn_kv(k) != 0) {
2709
0
                    LOG_WARNING("failed to delete recycle txn kv")
2710
0
                            .tag("instance id", instance_id_)
2711
0
                            .tag("key", hex(k));
2712
0
                    return -1;
2713
0
                }
2714
3
                return 0;
2715
3
            });
2716
23.0k
        }
2717
10
        bool finished = true;
2718
10
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
2719
23.0k
        for (int r : rets) {
2720
23.0k
            if (r != 0) {
2721
0
                ret = -1;
2722
0
            }
2723
23.0k
        }
2724
2725
10
        ret = finished ? ret : -1;
2726
2727
10
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
2728
2729
10
        if (ret != 0) {
2730
2
            LOG_WARNING("recycle txn kv ret!=0")
2731
2
                    .tag("finished", finished)
2732
2
                    .tag("ret", ret)
2733
2
                    .tag("instance_id", instance_id_);
2734
2
            return ret;
2735
2
        }
2736
8
        return ret;
2737
10
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clEv
Line
Count
Source
2700
7
    auto loop_done = [&]() -> int {
2701
7
        std::unique_ptr<int, std::function<void(int*)>> defer(
2702
7
                (int*)0x01, [&](int*) { recycle_txn_info_keys.clear(); });
2703
7
        TEST_SYNC_POINT_CALLBACK(
2704
7
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
2705
7
                &recycle_txn_info_keys);
2706
23.0k
        for (const auto& k : recycle_txn_info_keys) {
2707
23.0k
            concurrent_delete_executor.add([&]() {
2708
23.0k
                if (delete_recycle_txn_kv(k) != 0) {
2709
23.0k
                    LOG_WARNING("failed to delete recycle txn kv")
2710
23.0k
                            .tag("instance id", instance_id_)
2711
23.0k
                            .tag("key", hex(k));
2712
23.0k
                    return -1;
2713
23.0k
                }
2714
23.0k
                return 0;
2715
23.0k
            });
2716
23.0k
        }
2717
7
        bool finished = true;
2718
7
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
2719
23.0k
        for (int r : rets) {
2720
23.0k
            if (r != 0) {
2721
0
                ret = -1;
2722
0
            }
2723
23.0k
        }
2724
2725
7
        ret = finished ? ret : -1;
2726
2727
7
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
2728
2729
7
        if (ret != 0) {
2730
2
            LOG_WARNING("recycle txn kv ret!=0")
2731
2
                    .tag("finished", finished)
2732
2
                    .tag("ret", ret)
2733
2
                    .tag("instance_id", instance_id_);
2734
2
            return ret;
2735
2
        }
2736
5
        return ret;
2737
7
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clEv
Line
Count
Source
2700
3
    auto loop_done = [&]() -> int {
2701
3
        std::unique_ptr<int, std::function<void(int*)>> defer(
2702
3
                (int*)0x01, [&](int*) { recycle_txn_info_keys.clear(); });
2703
3
        TEST_SYNC_POINT_CALLBACK(
2704
3
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
2705
3
                &recycle_txn_info_keys);
2706
3
        for (const auto& k : recycle_txn_info_keys) {
2707
3
            concurrent_delete_executor.add([&]() {
2708
3
                if (delete_recycle_txn_kv(k) != 0) {
2709
3
                    LOG_WARNING("failed to delete recycle txn kv")
2710
3
                            .tag("instance id", instance_id_)
2711
3
                            .tag("key", hex(k));
2712
3
                    return -1;
2713
3
                }
2714
3
                return 0;
2715
3
            });
2716
3
        }
2717
3
        bool finished = true;
2718
3
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
2719
3
        for (int r : rets) {
2720
3
            if (r != 0) {
2721
0
                ret = -1;
2722
0
            }
2723
3
        }
2724
2725
3
        ret = finished ? ret : -1;
2726
2727
3
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
2728
2729
3
        if (ret != 0) {
2730
0
            LOG_WARNING("recycle txn kv ret!=0")
2731
0
                    .tag("finished", finished)
2732
0
                    .tag("ret", ret)
2733
0
                    .tag("instance_id", instance_id_);
2734
0
            return ret;
2735
0
        }
2736
3
        return ret;
2737
3
    };
2738
2739
19
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
2740
19
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
2741
19
}
2742
2743
struct CopyJobIdTuple {
2744
    std::string instance_id;
2745
    std::string stage_id;
2746
    long table_id;
2747
    std::string copy_id;
2748
    std::string stage_path;
2749
};
2750
struct BatchObjStoreAccessor {
2751
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
2752
                          TxnKv* txn_kv)
2753
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
2754
3
    ~BatchObjStoreAccessor() {
2755
3
        if (!paths_.empty()) {
2756
3
            consume();
2757
3
        }
2758
3
    }
2759
2760
    /**
2761
    * To implicitely do batch work and submit the batch delete task to s3
2762
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
2763
    *
2764
    * @param copy_job The protubuf struct consists of the copy job files.
2765
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
2766
    *            it would last until we finish the delete task, here we need pass one string value
2767
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
2768
    */
2769
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
2770
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
2771
5
        auto& file_keys = copy_file_keys_[key];
2772
5
        file_keys.log_trace =
2773
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
2774
5
                            instance_id, stage_id, table_id, copy_id, path);
2775
5
        std::string_view log_trace = file_keys.log_trace;
2776
2.03k
        for (const auto& file : copy_job.object_files()) {
2777
2.03k
            auto relative_path = file.relative_path();
2778
2.03k
            paths_.push_back(relative_path);
2779
2.03k
            file_keys.keys.push_back(copy_file_key(
2780
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
2781
2.03k
            LOG_INFO(log_trace)
2782
2.03k
                    .tag("relative_path", relative_path)
2783
2.03k
                    .tag("batch_count", batch_count_);
2784
2.03k
        }
2785
5
        LOG_INFO(log_trace)
2786
5
                .tag("objects_num", copy_job.object_files().size())
2787
5
                .tag("batch_count", batch_count_);
2788
        // 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
2789
        // recommend using delete objects when objects num is less than 10)
2790
5
        if (paths_.size() < 1000) {
2791
3
            return;
2792
3
        }
2793
2
        consume();
2794
2
    }
2795
2796
private:
2797
5
    void consume() {
2798
5
        std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01, [this](int*) {
2799
5
            paths_.clear();
2800
5
            copy_file_keys_.clear();
2801
5
            batch_count_++;
2802
5
        });
2803
5
        LOG_INFO("begin to delete {} internal stage objects in batch {}", paths_.size(),
2804
5
                 batch_count_);
2805
5
        StopWatch sw;
2806
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
2807
5
        if (0 != accessor_->delete_files(paths_)) {
2808
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
2809
2
                        paths_.size(), batch_count_, sw.elapsed_us());
2810
2
            return;
2811
2
        }
2812
3
        LOG_INFO("succeed to delete {} internal stage objects in batch {} and it takes {} us",
2813
3
                 paths_.size(), batch_count_, sw.elapsed_us());
2814
        // delete fdb's keys
2815
3
        for (auto& file_keys : copy_file_keys_) {
2816
3
            auto& [log_trace, keys] = file_keys.second;
2817
3
            std::unique_ptr<Transaction> txn;
2818
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
2819
0
                LOG(WARNING) << "failed to create txn";
2820
0
                continue;
2821
0
            }
2822
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
2823
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
2824
            // limited, should not cause the txn commit failed.
2825
1.02k
            for (const auto& key : keys) {
2826
1.02k
                txn->remove(key);
2827
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
2828
1.02k
            }
2829
3
            txn->remove(file_keys.first);
2830
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
2831
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
2832
0
                continue;
2833
0
            }
2834
3
        }
2835
3
    }
2836
    std::shared_ptr<StorageVaultAccessor> accessor_;
2837
    // the path of the s3 files to be deleted
2838
    std::vector<std::string> paths_;
2839
    struct CopyFiles {
2840
        std::string log_trace;
2841
        std::vector<std::string> keys;
2842
    };
2843
    // pair<std::string, std::vector<std::string>>
2844
    // first: instance_id_ stage_id table_id query_id
2845
    // second: keys to be deleted
2846
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
2847
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
2848
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
2849
    // which can together uniquely identifies different tasks for tracing log
2850
    uint64_t& batch_count_;
2851
    TxnKv* txn_kv_;
2852
};
2853
2854
13
int InstanceRecycler::recycle_copy_jobs() {
2855
13
    int64_t num_scanned = 0;
2856
13
    int64_t num_finished = 0;
2857
13
    int64_t num_expired = 0;
2858
13
    int64_t num_recycled = 0;
2859
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
2860
13
    uint64_t batch_count = 0;
2861
13
    const std::string task_name = "recycle_copy_jobs";
2862
2863
13
    LOG_INFO("begin to recycle copy jobs").tag("instance_id", instance_id_);
2864
2865
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2866
13
    register_recycle_task(task_name, start_time);
2867
2868
13
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
2869
13
        unregister_recycle_task(task_name);
2870
13
        int64_t cost =
2871
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2872
13
        LOG_INFO("recycle copy jobs finished, cost={}s", cost)
2873
13
                .tag("instance_id", instance_id_)
2874
13
                .tag("num_scanned", num_scanned)
2875
13
                .tag("num_finished", num_finished)
2876
13
                .tag("num_expired", num_expired)
2877
13
                .tag("num_recycled", num_recycled);
2878
13
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEPi
Line
Count
Source
2868
13
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
2869
13
        unregister_recycle_task(task_name);
2870
13
        int64_t cost =
2871
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2872
13
        LOG_INFO("recycle copy jobs finished, cost={}s", cost)
2873
13
                .tag("instance_id", instance_id_)
2874
13
                .tag("num_scanned", num_scanned)
2875
13
                .tag("num_finished", num_finished)
2876
13
                .tag("num_expired", num_expired)
2877
13
                .tag("num_recycled", num_recycled);
2878
13
    });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEPi
2879
2880
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
2881
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
2882
13
    std::string key0;
2883
13
    std::string key1;
2884
13
    copy_job_key(key_info0, &key0);
2885
13
    copy_job_key(key_info1, &key1);
2886
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
2887
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
2888
13
                         &batch_count, &stage_accessor_map, &task_name,
2889
16
                         this](std::string_view k, std::string_view v) -> int {
2890
16
        ++num_scanned;
2891
16
        CopyJobPB copy_job;
2892
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
2893
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
2894
0
            return -1;
2895
0
        }
2896
2897
        // decode copy job key
2898
16
        auto k1 = k;
2899
16
        k1.remove_prefix(1);
2900
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2901
16
        decode_key(&k1, &out);
2902
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
2903
        // -> CopyJobPB
2904
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
2905
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
2906
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
2907
2908
16
        bool check_storage = true;
2909
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
2910
12
            ++num_finished;
2911
2912
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
2913
7
                auto it = stage_accessor_map.find(stage_id);
2914
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
2915
7
                std::string_view path;
2916
7
                if (it != stage_accessor_map.end()) {
2917
2
                    accessor = it->second;
2918
5
                } else {
2919
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
2920
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
2921
5
                                                      &inner_accessor);
2922
5
                    if (ret < 0) { // error
2923
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
2924
0
                        return -1;
2925
5
                    } else if (ret == 0) {
2926
3
                        path = inner_accessor->uri();
2927
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
2928
3
                                inner_accessor, batch_count, txn_kv_.get());
2929
3
                        stage_accessor_map.emplace(stage_id, accessor);
2930
3
                    } else { // stage not found, skip check storage
2931
2
                        check_storage = false;
2932
2
                    }
2933
5
                }
2934
7
                if (check_storage) {
2935
                    // TODO delete objects with key and etag is not supported
2936
5
                    accessor->add(std::move(copy_job), std::string(k),
2937
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
2938
5
                    return 0;
2939
5
                }
2940
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
2941
5
                int64_t current_time =
2942
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
2943
5
                if (copy_job.finish_time_ms() > 0) {
2944
2
                    if (!config::force_immediate_recycle &&
2945
2
                        current_time < copy_job.finish_time_ms() +
2946
2
                                               config::copy_job_max_retention_second * 1000) {
2947
1
                        return 0;
2948
1
                    }
2949
3
                } else {
2950
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
2951
3
                    if (!config::force_immediate_recycle &&
2952
3
                        current_time < copy_job.start_time_ms() +
2953
3
                                               config::copy_job_max_retention_second * 1000) {
2954
1
                        return 0;
2955
1
                    }
2956
3
                }
2957
5
            }
2958
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
2959
4
            int64_t current_time =
2960
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
2961
            // if copy job is timeout: delete all copy file kvs and copy job kv
2962
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
2963
2
                return 0;
2964
2
            }
2965
2
            ++num_expired;
2966
2
        }
2967
2968
        // delete all copy files
2969
7
        std::vector<std::string> copy_file_keys;
2970
70
        for (auto& file : copy_job.object_files()) {
2971
70
            copy_file_keys.push_back(copy_file_key(
2972
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
2973
70
        }
2974
7
        std::unique_ptr<Transaction> txn;
2975
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2976
0
            LOG(WARNING) << "failed to create txn";
2977
0
            return -1;
2978
0
        }
2979
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
2980
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
2981
        // limited, should not cause the txn commit failed.
2982
70
        for (const auto& key : copy_file_keys) {
2983
70
            txn->remove(key);
2984
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
2985
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
2986
70
                      << ", query_id=" << copy_id;
2987
70
        }
2988
7
        txn->remove(k);
2989
7
        TxnErrorCode err = txn->commit();
2990
7
        if (err != TxnErrorCode::TXN_OK) {
2991
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
2992
0
            return -1;
2993
0
        }
2994
2995
7
        ++num_recycled;
2996
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2997
7
        return 0;
2998
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2889
16
                         this](std::string_view k, std::string_view v) -> int {
2890
16
        ++num_scanned;
2891
16
        CopyJobPB copy_job;
2892
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
2893
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
2894
0
            return -1;
2895
0
        }
2896
2897
        // decode copy job key
2898
16
        auto k1 = k;
2899
16
        k1.remove_prefix(1);
2900
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2901
16
        decode_key(&k1, &out);
2902
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
2903
        // -> CopyJobPB
2904
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
2905
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
2906
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
2907
2908
16
        bool check_storage = true;
2909
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
2910
12
            ++num_finished;
2911
2912
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
2913
7
                auto it = stage_accessor_map.find(stage_id);
2914
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
2915
7
                std::string_view path;
2916
7
                if (it != stage_accessor_map.end()) {
2917
2
                    accessor = it->second;
2918
5
                } else {
2919
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
2920
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
2921
5
                                                      &inner_accessor);
2922
5
                    if (ret < 0) { // error
2923
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
2924
0
                        return -1;
2925
5
                    } else if (ret == 0) {
2926
3
                        path = inner_accessor->uri();
2927
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
2928
3
                                inner_accessor, batch_count, txn_kv_.get());
2929
3
                        stage_accessor_map.emplace(stage_id, accessor);
2930
3
                    } else { // stage not found, skip check storage
2931
2
                        check_storage = false;
2932
2
                    }
2933
5
                }
2934
7
                if (check_storage) {
2935
                    // TODO delete objects with key and etag is not supported
2936
5
                    accessor->add(std::move(copy_job), std::string(k),
2937
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
2938
5
                    return 0;
2939
5
                }
2940
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
2941
5
                int64_t current_time =
2942
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
2943
5
                if (copy_job.finish_time_ms() > 0) {
2944
2
                    if (!config::force_immediate_recycle &&
2945
2
                        current_time < copy_job.finish_time_ms() +
2946
2
                                               config::copy_job_max_retention_second * 1000) {
2947
1
                        return 0;
2948
1
                    }
2949
3
                } else {
2950
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
2951
3
                    if (!config::force_immediate_recycle &&
2952
3
                        current_time < copy_job.start_time_ms() +
2953
3
                                               config::copy_job_max_retention_second * 1000) {
2954
1
                        return 0;
2955
1
                    }
2956
3
                }
2957
5
            }
2958
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
2959
4
            int64_t current_time =
2960
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
2961
            // if copy job is timeout: delete all copy file kvs and copy job kv
2962
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
2963
2
                return 0;
2964
2
            }
2965
2
            ++num_expired;
2966
2
        }
2967
2968
        // delete all copy files
2969
7
        std::vector<std::string> copy_file_keys;
2970
70
        for (auto& file : copy_job.object_files()) {
2971
70
            copy_file_keys.push_back(copy_file_key(
2972
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
2973
70
        }
2974
7
        std::unique_ptr<Transaction> txn;
2975
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2976
0
            LOG(WARNING) << "failed to create txn";
2977
0
            return -1;
2978
0
        }
2979
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
2980
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
2981
        // limited, should not cause the txn commit failed.
2982
70
        for (const auto& key : copy_file_keys) {
2983
70
            txn->remove(key);
2984
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
2985
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
2986
70
                      << ", query_id=" << copy_id;
2987
70
        }
2988
7
        txn->remove(k);
2989
7
        TxnErrorCode err = txn->commit();
2990
7
        if (err != TxnErrorCode::TXN_OK) {
2991
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
2992
0
            return -1;
2993
0
        }
2994
2995
7
        ++num_recycled;
2996
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2997
7
        return 0;
2998
7
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
2999
3000
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
3001
13
}
3002
3003
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
3004
                                             const StagePB::StageType& stage_type,
3005
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
3006
5
#ifdef UNIT_TEST
3007
    // In unit test, external use the same accessor as the internal stage
3008
5
    auto it = accessor_map_.find(stage_id);
3009
5
    if (it != accessor_map_.end()) {
3010
3
        *accessor = it->second;
3011
3
    } else {
3012
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
3013
2
        return 1;
3014
2
    }
3015
#else
3016
    // init s3 accessor and add to accessor map
3017
    auto stage_it =
3018
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
3019
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
3020
3021
    if (stage_it == instance_info_.stages().end()) {
3022
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
3023
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
3024
        return 1;
3025
    }
3026
3027
    const auto& object_store_info = stage_it->obj_info();
3028
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
3029
3030
    S3Conf s3_conf;
3031
    if (stage_type == StagePB::EXTERNAL) {
3032
        if (stage_access_type == StagePB::AKSK) {
3033
            auto conf = S3Conf::from_obj_store_info(object_store_info);
3034
            if (!conf) {
3035
                return -1;
3036
            }
3037
3038
            s3_conf = std::move(*conf);
3039
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
3040
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
3041
            if (!conf) {
3042
                return -1;
3043
            }
3044
3045
            s3_conf = std::move(*conf);
3046
            if (instance_info_.ram_user().has_encryption_info()) {
3047
                AkSkPair plain_ak_sk_pair;
3048
                int ret = decrypt_ak_sk_helper(
3049
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
3050
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
3051
                if (ret != 0) {
3052
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
3053
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
3054
                    return -1;
3055
                }
3056
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
3057
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
3058
            } else {
3059
                s3_conf.ak = instance_info_.ram_user().ak();
3060
                s3_conf.sk = instance_info_.ram_user().sk();
3061
            }
3062
        } else {
3063
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
3064
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
3065
            return -1;
3066
        }
3067
    } else if (stage_type == StagePB::INTERNAL) {
3068
        int idx = stoi(object_store_info.id());
3069
        if (idx > instance_info_.obj_info().size() || idx < 1) {
3070
            LOG(WARNING) << "invalid idx: " << idx;
3071
            return -1;
3072
        }
3073
3074
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
3075
        auto conf = S3Conf::from_obj_store_info(old_obj);
3076
        if (!conf) {
3077
            return -1;
3078
        }
3079
3080
        s3_conf = std::move(*conf);
3081
        s3_conf.prefix = object_store_info.prefix();
3082
    } else {
3083
        LOG(WARNING) << "unknown stage type " << stage_type;
3084
        return -1;
3085
    }
3086
3087
    std::shared_ptr<S3Accessor> s3_accessor;
3088
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
3089
    if (ret != 0) {
3090
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
3091
        return -1;
3092
    }
3093
3094
    *accessor = std::move(s3_accessor);
3095
#endif
3096
3
    return 0;
3097
5
}
3098
3099
11
int InstanceRecycler::recycle_stage() {
3100
11
    int64_t num_scanned = 0;
3101
11
    int64_t num_recycled = 0;
3102
11
    const std::string task_name = "recycle_stage";
3103
3104
11
    LOG_INFO("begin to recycle stage").tag("instance_id", instance_id_);
3105
3106
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
3107
11
    register_recycle_task(task_name, start_time);
3108
3109
11
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
3110
11
        unregister_recycle_task(task_name);
3111
11
        int64_t cost =
3112
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3113
11
        LOG_INFO("recycle stage, cost={}s", cost)
3114
11
                .tag("instance_id", instance_id_)
3115
11
                .tag("num_scanned", num_scanned)
3116
11
                .tag("num_recycled", num_recycled);
3117
11
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEPi
Line
Count
Source
3109
11
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
3110
11
        unregister_recycle_task(task_name);
3111
11
        int64_t cost =
3112
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3113
11
        LOG_INFO("recycle stage, cost={}s", cost)
3114
11
                .tag("instance_id", instance_id_)
3115
11
                .tag("num_scanned", num_scanned)
3116
11
                .tag("num_recycled", num_recycled);
3117
11
    });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEPi
3118
3119
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
3120
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
3121
11
    std::string key0 = recycle_stage_key(key_info0);
3122
11
    std::string key1 = recycle_stage_key(key_info1);
3123
3124
11
    std::vector<std::string_view> stage_keys;
3125
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, this](
3126
11
                                std::string_view k, std::string_view v) -> int {
3127
1
        ++num_scanned;
3128
1
        RecycleStagePB recycle_stage;
3129
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
3130
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
3131
0
            return -1;
3132
0
        }
3133
3134
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
3135
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
3136
0
            LOG(WARNING) << "invalid idx: " << idx;
3137
0
            return -1;
3138
0
        }
3139
3140
1
        std::shared_ptr<StorageVaultAccessor> accessor;
3141
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
3142
1
                [&] {
3143
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
3144
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
3145
1
                    if (!s3_conf) {
3146
1
                        return -1;
3147
1
                    }
3148
3149
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
3150
1
                    std::shared_ptr<S3Accessor> s3_accessor;
3151
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
3152
1
                    if (ret != 0) {
3153
1
                        return -1;
3154
1
                    }
3155
3156
1
                    accessor = std::move(s3_accessor);
3157
1
                    return 0;
3158
1
                }(),
3159
1
                "recycle_stage:get_accessor", &accessor);
3160
3161
1
        if (ret != 0) {
3162
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
3163
0
            return ret;
3164
0
        }
3165
3166
1
        LOG_INFO("begin to delete objects of dropped internal stage")
3167
1
                .tag("instance_id", instance_id_)
3168
1
                .tag("stage_id", recycle_stage.stage().stage_id())
3169
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
3170
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
3171
1
                .tag("obj_info_id", idx)
3172
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
3173
1
        ret = accessor->delete_all();
3174
1
        if (ret != 0) {
3175
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
3176
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
3177
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
3178
0
                         << ", ret=" << ret;
3179
0
            return -1;
3180
0
        }
3181
1
        ++num_recycled;
3182
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
3183
1
        stage_keys.push_back(k);
3184
1
        return 0;
3185
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3126
1
                                std::string_view k, std::string_view v) -> int {
3127
1
        ++num_scanned;
3128
1
        RecycleStagePB recycle_stage;
3129
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
3130
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
3131
0
            return -1;
3132
0
        }
3133
3134
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
3135
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
3136
0
            LOG(WARNING) << "invalid idx: " << idx;
3137
0
            return -1;
3138
0
        }
3139
3140
1
        std::shared_ptr<StorageVaultAccessor> accessor;
3141
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
3142
1
                [&] {
3143
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
3144
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
3145
1
                    if (!s3_conf) {
3146
1
                        return -1;
3147
1
                    }
3148
3149
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
3150
1
                    std::shared_ptr<S3Accessor> s3_accessor;
3151
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
3152
1
                    if (ret != 0) {
3153
1
                        return -1;
3154
1
                    }
3155
3156
1
                    accessor = std::move(s3_accessor);
3157
1
                    return 0;
3158
1
                }(),
3159
1
                "recycle_stage:get_accessor", &accessor);
3160
3161
1
        if (ret != 0) {
3162
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
3163
0
            return ret;
3164
0
        }
3165
3166
1
        LOG_INFO("begin to delete objects of dropped internal stage")
3167
1
                .tag("instance_id", instance_id_)
3168
1
                .tag("stage_id", recycle_stage.stage().stage_id())
3169
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
3170
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
3171
1
                .tag("obj_info_id", idx)
3172
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
3173
1
        ret = accessor->delete_all();
3174
1
        if (ret != 0) {
3175
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
3176
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
3177
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
3178
0
                         << ", ret=" << ret;
3179
0
            return -1;
3180
0
        }
3181
1
        ++num_recycled;
3182
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
3183
1
        stage_keys.push_back(k);
3184
1
        return 0;
3185
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
3186
3187
11
    auto loop_done = [&stage_keys, this]() -> int {
3188
1
        if (stage_keys.empty()) return 0;
3189
1
        std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01,
3190
1
                                                              [&](int*) { stage_keys.clear(); });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clEvENKUlPiE_clES3_
Line
Count
Source
3190
1
                                                              [&](int*) { stage_keys.clear(); });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clEvENKUlPiE_clES3_
3191
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
3192
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3193
0
            return -1;
3194
0
        }
3195
1
        return 0;
3196
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clEv
Line
Count
Source
3187
1
    auto loop_done = [&stage_keys, this]() -> int {
3188
1
        if (stage_keys.empty()) return 0;
3189
1
        std::unique_ptr<int, std::function<void(int*)>> defer((int*)0x01,
3190
1
                                                              [&](int*) { stage_keys.clear(); });
3191
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
3192
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3193
0
            return -1;
3194
0
        }
3195
1
        return 0;
3196
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clEv
3197
3198
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
3199
11
}
3200
3201
10
int InstanceRecycler::recycle_expired_stage_objects() {
3202
10
    LOG_INFO("begin to recycle expired stage objects").tag("instance_id", instance_id_);
3203
3204
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
3205
3206
10
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
3207
10
        int64_t cost =
3208
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3209
10
        LOG_INFO("recycle expired stage objects, cost={}s", cost).tag("instance_id", instance_id_);
3210
10
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEPi
Line
Count
Source
3206
10
    std::unique_ptr<int, std::function<void(int*)>> defer_log_statistics((int*)0x01, [&](int*) {
3207
10
        int64_t cost =
3208
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3209
10
        LOG_INFO("recycle expired stage objects, cost={}s", cost).tag("instance_id", instance_id_);
3210
10
    });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEPi
3211
10
    int ret = 0;
3212
10
    for (const auto& stage : instance_info_.stages()) {
3213
0
        std::stringstream ss;
3214
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
3215
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
3216
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
3217
0
           << ", prefix=" << stage.obj_info().prefix();
3218
3219
0
        if (stopped()) break;
3220
0
        if (stage.type() == StagePB::EXTERNAL) {
3221
0
            continue;
3222
0
        }
3223
0
        int idx = stoi(stage.obj_info().id());
3224
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
3225
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
3226
0
            continue;
3227
0
        }
3228
3229
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
3230
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
3231
0
        if (!s3_conf) {
3232
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
3233
0
            continue;
3234
0
        }
3235
3236
0
        s3_conf->prefix = stage.obj_info().prefix();
3237
0
        std::shared_ptr<S3Accessor> accessor;
3238
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
3239
0
        if (ret1 != 0) {
3240
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
3241
0
            ret = -1;
3242
0
            continue;
3243
0
        }
3244
3245
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
3246
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
3247
0
            ret = -1;
3248
0
            continue;
3249
0
        }
3250
3251
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
3252
0
        int64_t expiration_time =
3253
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
3254
0
                config::internal_stage_objects_expire_time_second;
3255
0
        if (config::force_immediate_recycle) {
3256
0
            expiration_time = INT64_MAX;
3257
0
        }
3258
0
        ret1 = accessor->delete_all(expiration_time);
3259
0
        if (ret1 != 0) {
3260
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
3261
0
                         << ss.str();
3262
0
            ret = -1;
3263
0
            continue;
3264
0
        }
3265
0
    }
3266
10
    return ret;
3267
10
}
3268
3269
121
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
3270
121
    std::lock_guard lock(recycle_tasks_mutex);
3271
121
    running_recycle_tasks[task_name] = start_time;
3272
121
}
3273
3274
121
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
3275
121
    std::lock_guard lock(recycle_tasks_mutex);
3276
121
    DCHECK(running_recycle_tasks[task_name] > 0);
3277
121
    running_recycle_tasks.erase(task_name);
3278
121
}
3279
3280
21
bool InstanceRecycler::check_recycle_tasks() {
3281
21
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
3282
21
    {
3283
21
        std::lock_guard lock(recycle_tasks_mutex);
3284
21
        tmp_running_recycle_tasks = running_recycle_tasks;
3285
21
    }
3286
3287
21
    bool found = false;
3288
21
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
3289
21
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
3290
20
        int64_t cost = now - start_time;
3291
20
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
3292
20
            LOG_INFO("recycle task cost too much time cost={}s", cost)
3293
20
                    .tag("instance_id", instance_id_)
3294
20
                    .tag("task", task_name);
3295
20
            found = true;
3296
20
        }
3297
20
    }
3298
3299
21
    return found;
3300
21
}
3301
3302
} // namespace doris::cloud