Coverage Report

Created: 2026-03-10 01:00

/root/doris/cloud/src/recycler/recycler.cpp
Line
Count
Source (jump to first uncovered line)
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "recycler/recycler.h"
19
20
#include <brpc/builtin_service.pb.h>
21
#include <brpc/server.h>
22
#include <butil/endpoint.h>
23
#include <butil/strings/string_split.h>
24
#include <bvar/status.h>
25
#include <gen_cpp/cloud.pb.h>
26
#include <gen_cpp/olap_file.pb.h>
27
28
#include <algorithm>
29
#include <atomic>
30
#include <chrono>
31
#include <cstddef>
32
#include <cstdint>
33
#include <cstdlib>
34
#include <deque>
35
#include <functional>
36
#include <initializer_list>
37
#include <memory>
38
#include <numeric>
39
#include <random>
40
#include <string>
41
#include <string_view>
42
#include <thread>
43
#include <unordered_map>
44
#include <utility>
45
#include <variant>
46
47
#include "common/defer.h"
48
#include "common/stopwatch.h"
49
#include "meta-service/meta_service.h"
50
#include "meta-service/meta_service_helper.h"
51
#include "meta-service/meta_service_schema.h"
52
#include "meta-store/blob_message.h"
53
#include "meta-store/meta_reader.h"
54
#include "meta-store/txn_kv.h"
55
#include "meta-store/txn_kv_error.h"
56
#include "meta-store/versioned_value.h"
57
#include "recycler/checker.h"
58
#ifdef ENABLE_HDFS_STORAGE_VAULT
59
#include "recycler/hdfs_accessor.h"
60
#endif
61
#include "recycler/s3_accessor.h"
62
#include "recycler/storage_vault_accessor.h"
63
#ifdef UNIT_TEST
64
#include "../test/mock_accessor.h"
65
#endif
66
#include "common/bvars.h"
67
#include "common/config.h"
68
#include "common/encryption_util.h"
69
#include "common/logging.h"
70
#include "common/simple_thread_pool.h"
71
#include "common/util.h"
72
#include "cpp/sync_point.h"
73
#include "meta-store/codec.h"
74
#include "meta-store/document_message.h"
75
#include "meta-store/keys.h"
76
#include "recycler/recycler_service.h"
77
#include "recycler/sync_executor.h"
78
#include "recycler/util.h"
79
80
namespace doris::cloud {
81
82
using namespace std::chrono;
83
84
namespace {
85
86
0
int64_t packed_file_retry_sleep_ms() {
87
0
    const int64_t min_ms = std::max<int64_t>(0, config::packed_file_txn_retry_sleep_min_ms);
88
0
    const int64_t max_ms = std::max<int64_t>(min_ms, config::packed_file_txn_retry_sleep_max_ms);
89
0
    thread_local std::mt19937_64 gen(std::random_device {}());
90
0
    std::uniform_int_distribution<int64_t> dist(min_ms, max_ms);
91
0
    return dist(gen);
92
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_126packed_file_retry_sleep_msEv
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_126packed_file_retry_sleep_msEv
93
94
0
void sleep_for_packed_file_retry() {
95
0
    std::this_thread::sleep_for(std::chrono::milliseconds(packed_file_retry_sleep_ms()));
96
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_127sleep_for_packed_file_retryEv
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_127sleep_for_packed_file_retryEv
97
98
} // namespace
99
100
// return 0 for success get a key, 1 for key not found, negative for error
101
0
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
102
0
    std::unique_ptr<Transaction> txn;
103
0
    TxnErrorCode err = txn_kv->create_txn(&txn);
104
0
    if (err != TxnErrorCode::TXN_OK) {
105
0
        return -1;
106
0
    }
107
0
    switch (txn->get(key, &val, true)) {
108
0
    case TxnErrorCode::TXN_OK:
109
0
        return 0;
110
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
111
0
        return 1;
112
0
    default:
113
0
        return -1;
114
0
    };
115
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
116
117
// 0 for success, negative for error
118
static int txn_get(TxnKv* txn_kv, std::string_view begin, std::string_view end,
119
325
                   std::unique_ptr<RangeGetIterator>& it) {
120
325
    std::unique_ptr<Transaction> txn;
121
325
    TxnErrorCode err = txn_kv->create_txn(&txn);
122
325
    if (err != TxnErrorCode::TXN_OK) {
123
0
        return -1;
124
0
    }
125
325
    switch (txn->get(begin, end, &it, true)) {
126
325
    case TxnErrorCode::TXN_OK:
127
325
        return 0;
128
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
129
0
        return 1;
130
0
    default:
131
0
        return -1;
132
325
    };
133
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
119
31
                   std::unique_ptr<RangeGetIterator>& it) {
120
31
    std::unique_ptr<Transaction> txn;
121
31
    TxnErrorCode err = txn_kv->create_txn(&txn);
122
31
    if (err != TxnErrorCode::TXN_OK) {
123
0
        return -1;
124
0
    }
125
31
    switch (txn->get(begin, end, &it, true)) {
126
31
    case TxnErrorCode::TXN_OK:
127
31
        return 0;
128
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
129
0
        return 1;
130
0
    default:
131
0
        return -1;
132
31
    };
133
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
119
294
                   std::unique_ptr<RangeGetIterator>& it) {
120
294
    std::unique_ptr<Transaction> txn;
121
294
    TxnErrorCode err = txn_kv->create_txn(&txn);
122
294
    if (err != TxnErrorCode::TXN_OK) {
123
0
        return -1;
124
0
    }
125
294
    switch (txn->get(begin, end, &it, true)) {
126
294
    case TxnErrorCode::TXN_OK:
127
294
        return 0;
128
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
129
0
        return 1;
130
0
    default:
131
0
        return -1;
132
294
    };
133
0
}
134
135
// return 0 for success otherwise error
136
6
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
137
6
    std::unique_ptr<Transaction> txn;
138
6
    TxnErrorCode err = txn_kv->create_txn(&txn);
139
6
    if (err != TxnErrorCode::TXN_OK) {
140
0
        return -1;
141
0
    }
142
10
    for (auto k : keys) {
143
10
        txn->remove(k);
144
10
    }
145
6
    switch (txn->commit()) {
146
6
    case TxnErrorCode::TXN_OK:
147
6
        return 0;
148
0
    case TxnErrorCode::TXN_CONFLICT:
149
0
        return -1;
150
0
    default:
151
0
        return -1;
152
6
    }
153
6
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
136
1
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
137
1
    std::unique_ptr<Transaction> txn;
138
1
    TxnErrorCode err = txn_kv->create_txn(&txn);
139
1
    if (err != TxnErrorCode::TXN_OK) {
140
0
        return -1;
141
0
    }
142
1
    for (auto k : keys) {
143
1
        txn->remove(k);
144
1
    }
145
1
    switch (txn->commit()) {
146
1
    case TxnErrorCode::TXN_OK:
147
1
        return 0;
148
0
    case TxnErrorCode::TXN_CONFLICT:
149
0
        return -1;
150
0
    default:
151
0
        return -1;
152
1
    }
153
1
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
136
5
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
137
5
    std::unique_ptr<Transaction> txn;
138
5
    TxnErrorCode err = txn_kv->create_txn(&txn);
139
5
    if (err != TxnErrorCode::TXN_OK) {
140
0
        return -1;
141
0
    }
142
9
    for (auto k : keys) {
143
9
        txn->remove(k);
144
9
    }
145
5
    switch (txn->commit()) {
146
5
    case TxnErrorCode::TXN_OK:
147
5
        return 0;
148
0
    case TxnErrorCode::TXN_CONFLICT:
149
0
        return -1;
150
0
    default:
151
0
        return -1;
152
5
    }
153
5
}
154
155
// return 0 for success otherwise error
156
119
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
157
119
    std::unique_ptr<Transaction> txn;
158
119
    TxnErrorCode err = txn_kv->create_txn(&txn);
159
119
    if (err != TxnErrorCode::TXN_OK) {
160
0
        return -1;
161
0
    }
162
106k
    for (auto& k : keys) {
163
106k
        txn->remove(k);
164
106k
    }
165
119
    switch (txn->commit()) {
166
119
    case TxnErrorCode::TXN_OK:
167
119
        return 0;
168
0
    case TxnErrorCode::TXN_CONFLICT:
169
0
        return -1;
170
0
    default:
171
0
        return -1;
172
119
    }
173
119
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
156
33
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
157
33
    std::unique_ptr<Transaction> txn;
158
33
    TxnErrorCode err = txn_kv->create_txn(&txn);
159
33
    if (err != TxnErrorCode::TXN_OK) {
160
0
        return -1;
161
0
    }
162
33
    for (auto& k : keys) {
163
16
        txn->remove(k);
164
16
    }
165
33
    switch (txn->commit()) {
166
33
    case TxnErrorCode::TXN_OK:
167
33
        return 0;
168
0
    case TxnErrorCode::TXN_CONFLICT:
169
0
        return -1;
170
0
    default:
171
0
        return -1;
172
33
    }
173
33
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
156
86
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
157
86
    std::unique_ptr<Transaction> txn;
158
86
    TxnErrorCode err = txn_kv->create_txn(&txn);
159
86
    if (err != TxnErrorCode::TXN_OK) {
160
0
        return -1;
161
0
    }
162
106k
    for (auto& k : keys) {
163
106k
        txn->remove(k);
164
106k
    }
165
86
    switch (txn->commit()) {
166
86
    case TxnErrorCode::TXN_OK:
167
86
        return 0;
168
0
    case TxnErrorCode::TXN_CONFLICT:
169
0
        return -1;
170
0
    default:
171
0
        return -1;
172
86
    }
173
86
}
174
175
// return 0 for success otherwise error
176
[[maybe_unused]] static int txn_remove(TxnKv* txn_kv, std::string_view begin,
177
106k
                                       std::string_view end) {
178
106k
    std::unique_ptr<Transaction> txn;
179
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
180
106k
    if (err != TxnErrorCode::TXN_OK) {
181
0
        return -1;
182
0
    }
183
106k
    txn->remove(begin, end);
184
106k
    switch (txn->commit()) {
185
106k
    case TxnErrorCode::TXN_OK:
186
106k
        return 0;
187
0
    case TxnErrorCode::TXN_CONFLICT:
188
0
        return -1;
189
0
    default:
190
0
        return -1;
191
106k
    }
192
106k
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
177
16
                                       std::string_view end) {
178
16
    std::unique_ptr<Transaction> txn;
179
16
    TxnErrorCode err = txn_kv->create_txn(&txn);
180
16
    if (err != TxnErrorCode::TXN_OK) {
181
0
        return -1;
182
0
    }
183
16
    txn->remove(begin, end);
184
16
    switch (txn->commit()) {
185
16
    case TxnErrorCode::TXN_OK:
186
16
        return 0;
187
0
    case TxnErrorCode::TXN_CONFLICT:
188
0
        return -1;
189
0
    default:
190
0
        return -1;
191
16
    }
192
16
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
177
106k
                                       std::string_view end) {
178
106k
    std::unique_ptr<Transaction> txn;
179
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
180
106k
    if (err != TxnErrorCode::TXN_OK) {
181
0
        return -1;
182
0
    }
183
106k
    txn->remove(begin, end);
184
106k
    switch (txn->commit()) {
185
106k
    case TxnErrorCode::TXN_OK:
186
106k
        return 0;
187
0
    case TxnErrorCode::TXN_CONFLICT:
188
0
        return -1;
189
0
    default:
190
0
        return -1;
191
106k
    }
192
106k
}
193
194
void scan_restore_job_rowset(
195
        Transaction* txn, const std::string& instance_id, int64_t tablet_id, MetaServiceCode& code,
196
        std::string& msg,
197
        std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>* restore_job_rs_metas);
198
199
static inline void check_recycle_task(const std::string& instance_id, const std::string& task_name,
200
                                      int64_t num_scanned, int64_t num_recycled,
201
52
                                      int64_t start_time) {
202
52
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
203
0
        int64_t cost =
204
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
205
0
        if (cost > config::recycle_task_threshold_seconds) {
206
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
207
0
                    .tag("instance_id", instance_id)
208
0
                    .tag("task", task_name)
209
0
                    .tag("num_scanned", num_scanned)
210
0
                    .tag("num_recycled", num_recycled);
211
0
        }
212
0
    }
213
52
    return;
214
52
}
recycler.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
201
2
                                      int64_t start_time) {
202
2
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
203
0
        int64_t cost =
204
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
205
0
        if (cost > config::recycle_task_threshold_seconds) {
206
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
207
0
                    .tag("instance_id", instance_id)
208
0
                    .tag("task", task_name)
209
0
                    .tag("num_scanned", num_scanned)
210
0
                    .tag("num_recycled", num_recycled);
211
0
        }
212
0
    }
213
2
    return;
214
2
}
recycler_test.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
201
50
                                      int64_t start_time) {
202
50
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
203
0
        int64_t cost =
204
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
205
0
        if (cost > config::recycle_task_threshold_seconds) {
206
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
207
0
                    .tag("instance_id", instance_id)
208
0
                    .tag("task", task_name)
209
0
                    .tag("num_scanned", num_scanned)
210
0
                    .tag("num_recycled", num_recycled);
211
0
        }
212
0
    }
213
50
    return;
214
50
}
215
216
4
Recycler::Recycler(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
217
4
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
218
219
4
    auto s3_producer_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
220
4
                                                               "s3_producer_pool");
221
4
    s3_producer_pool->start();
222
4
    auto recycle_tablet_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
223
4
                                                                  "recycle_tablet_pool");
224
4
    recycle_tablet_pool->start();
225
4
    auto group_recycle_function_pool = std::make_shared<SimpleThreadPool>(
226
4
            config::recycle_pool_parallelism, "group_recycle_function_pool");
227
4
    group_recycle_function_pool->start();
228
4
    _thread_pool_group =
229
4
            RecyclerThreadPoolGroup(std::move(s3_producer_pool), std::move(recycle_tablet_pool),
230
4
                                    std::move(group_recycle_function_pool));
231
232
4
    auto resource_mgr = std::make_shared<ResourceManager>(txn_kv_);
233
4
    txn_lazy_committer_ = std::make_shared<TxnLazyCommitter>(txn_kv_, std::move(resource_mgr));
234
4
    snapshot_manager_ = std::make_shared<SnapshotManager>(txn_kv_);
235
4
}
236
237
4
Recycler::~Recycler() {
238
4
    if (!stopped()) {
239
0
        stop();
240
0
    }
241
4
}
242
243
4
void Recycler::instance_scanner_callback() {
244
    // sleep 60 seconds before scheduling for the launch procedure to complete:
245
    // some bad hdfs connection may cause some log to stdout stderr
246
    // which may pollute .out file and affect the script to check success
247
4
    std::this_thread::sleep_for(
248
4
            std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
249
7
    while (!stopped()) {
250
3
        std::vector<InstanceInfoPB> instances;
251
3
        get_all_instances(txn_kv_.get(), instances);
252
        // TODO(plat1ko): delete job recycle kv of non-existent instances
253
3
        LOG(INFO) << "Recycler get instances: " << [&instances] {
254
3
            std::stringstream ss;
255
30
            for (auto& i : instances) ss << ' ' << i.instance_id();
256
3
            return ss.str();
257
3
        }();
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
Line
Count
Source
253
3
        LOG(INFO) << "Recycler get instances: " << [&instances] {
254
3
            std::stringstream ss;
255
30
            for (auto& i : instances) ss << ' ' << i.instance_id();
256
3
            return ss.str();
257
3
        }();
258
3
        if (!instances.empty()) {
259
            // enqueue instances
260
3
            std::lock_guard lock(mtx_);
261
30
            for (auto& instance : instances) {
262
30
                if (instance_filter_.filter_out(instance.instance_id())) continue;
263
30
                auto [_, success] = pending_instance_set_.insert(instance.instance_id());
264
                // skip instance already in pending queue
265
30
                if (success) {
266
30
                    pending_instance_queue_.push_back(std::move(instance));
267
30
                }
268
30
            }
269
3
            pending_instance_cond_.notify_all();
270
3
        }
271
3
        {
272
3
            std::unique_lock lock(mtx_);
273
3
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
274
6
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
274
6
                               [&]() { return stopped(); });
275
3
        }
276
3
    }
277
4
}
278
279
8
void Recycler::recycle_callback() {
280
38
    while (!stopped()) {
281
36
        InstanceInfoPB instance;
282
36
        {
283
36
            std::unique_lock lock(mtx_);
284
36
            pending_instance_cond_.wait(
285
48
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
285
48
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
286
36
            if (stopped()) {
287
6
                return;
288
6
            }
289
30
            instance = std::move(pending_instance_queue_.front());
290
30
            pending_instance_queue_.pop_front();
291
30
            pending_instance_set_.erase(instance.instance_id());
292
30
        }
293
0
        auto& instance_id = instance.instance_id();
294
30
        {
295
30
            std::lock_guard lock(mtx_);
296
            // skip instance in recycling
297
30
            if (recycling_instance_map_.count(instance_id)) continue;
298
30
        }
299
30
        auto instance_recycler = std::make_shared<InstanceRecycler>(
300
30
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
301
302
30
        if (int r = instance_recycler->init(); r != 0) {
303
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
304
0
                         << " ret=" << r;
305
0
            continue;
306
0
        }
307
30
        std::string recycle_job_key;
308
30
        job_recycle_key({instance_id}, &recycle_job_key);
309
30
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
310
30
                                               ip_port_, config::recycle_interval_seconds * 1000);
311
30
        if (ret != 0) { // Prepare failed
312
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
313
20
                         << " ret=" << ret;
314
20
            continue;
315
20
        } else {
316
10
            std::lock_guard lock(mtx_);
317
10
            recycling_instance_map_.emplace(instance_id, instance_recycler);
318
10
        }
319
10
        if (stopped()) return;
320
10
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
321
10
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
322
10
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
323
10
        g_bvar_recycler_instance_recycle_task_status.put({"submitted"}, 1);
324
10
        ret = instance_recycler->do_recycle();
325
        // If instance recycler has been aborted, don't finish this job
326
327
10
        if (!instance_recycler->stopped()) {
328
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
329
10
                                        ret == 0, ctime_ms);
330
10
        }
331
10
        if (instance_recycler->stopped() || ret != 0) {
332
0
            g_bvar_recycler_instance_recycle_task_status.put({"error"}, 1);
333
0
        }
334
10
        {
335
10
            std::lock_guard lock(mtx_);
336
10
            recycling_instance_map_.erase(instance_id);
337
10
        }
338
339
10
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
340
10
        auto elpased_ms = now - ctime_ms;
341
10
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
342
10
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
343
10
        g_bvar_recycler_instance_next_ts.put({instance_id},
344
10
                                             now + config::recycle_interval_seconds * 1000);
345
10
        g_bvar_recycler_instance_recycle_task_status.put({"completed"}, 1);
346
10
        LOG(INFO) << "recycle instance done, "
347
10
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
348
10
                  << " now: " << now;
349
350
10
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
351
352
10
        LOG_WARNING("finish recycle instance")
353
10
                .tag("instance_id", instance_id)
354
10
                .tag("cost_ms", elpased_ms);
355
10
    }
356
8
}
357
358
4
void Recycler::lease_recycle_jobs() {
359
54
    while (!stopped()) {
360
50
        std::vector<std::string> instances;
361
50
        instances.reserve(recycling_instance_map_.size());
362
50
        {
363
50
            std::lock_guard lock(mtx_);
364
50
            for (auto& [id, _] : recycling_instance_map_) {
365
30
                instances.push_back(id);
366
30
            }
367
50
        }
368
50
        for (auto& i : instances) {
369
30
            std::string recycle_job_key;
370
30
            job_recycle_key({i}, &recycle_job_key);
371
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
372
30
            if (ret == 1) {
373
0
                std::lock_guard lock(mtx_);
374
0
                if (auto it = recycling_instance_map_.find(i);
375
0
                    it != recycling_instance_map_.end()) {
376
0
                    it->second->stop();
377
0
                }
378
0
            }
379
30
        }
380
50
        {
381
50
            std::unique_lock lock(mtx_);
382
50
            notifier_.wait_for(lock,
383
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
384
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
384
100
                               [&]() { return stopped(); });
385
50
        }
386
50
    }
387
4
}
388
389
4
void Recycler::check_recycle_tasks() {
390
7
    while (!stopped()) {
391
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
392
3
        {
393
3
            std::lock_guard lock(mtx_);
394
3
            recycling_instance_map = recycling_instance_map_;
395
3
        }
396
3
        for (auto& entry : recycling_instance_map) {
397
0
            entry.second->check_recycle_tasks();
398
0
        }
399
400
3
        std::unique_lock lock(mtx_);
401
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
402
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
402
6
                           [&]() { return stopped(); });
403
3
    }
404
4
}
405
406
4
int Recycler::start(brpc::Server* server) {
407
4
    instance_filter_.reset(config::recycle_whitelist, config::recycle_blacklist);
408
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
409
4
    S3Environment::getInstance();
410
411
4
    if (config::enable_checker) {
412
0
        checker_ = std::make_unique<Checker>(txn_kv_);
413
0
        int ret = checker_->start();
414
0
        std::string msg;
415
0
        if (ret != 0) {
416
0
            msg = "failed to start checker";
417
0
            LOG(ERROR) << msg;
418
0
            std::cerr << msg << std::endl;
419
0
            return ret;
420
0
        }
421
0
        msg = "checker started";
422
0
        LOG(INFO) << msg;
423
0
        std::cout << msg << std::endl;
424
0
    }
425
426
4
    if (server) {
427
        // Add service
428
1
        auto recycler_service =
429
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
430
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
431
1
    }
432
433
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
433
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
434
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
435
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
435
8
        workers_.emplace_back([this] { recycle_callback(); });
436
8
    }
437
438
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
439
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
440
441
4
    if (config::enable_snapshot_data_migrator) {
442
0
        snapshot_data_migrator_ = std::make_shared<SnapshotDataMigrator>(txn_kv_);
443
0
        int ret = snapshot_data_migrator_->start();
444
0
        if (ret != 0) {
445
0
            LOG(ERROR) << "failed to start snapshot data migrator";
446
0
            return ret;
447
0
        }
448
0
        LOG(INFO) << "snapshot data migrator started";
449
0
    }
450
451
4
    if (config::enable_snapshot_chain_compactor) {
452
0
        snapshot_chain_compactor_ = std::make_shared<SnapshotChainCompactor>(txn_kv_);
453
0
        int ret = snapshot_chain_compactor_->start();
454
0
        if (ret != 0) {
455
0
            LOG(ERROR) << "failed to start snapshot chain compactor";
456
0
            return ret;
457
0
        }
458
0
        LOG(INFO) << "snapshot chain compactor started";
459
0
    }
460
461
4
    return 0;
462
4
}
463
464
4
void Recycler::stop() {
465
4
    stopped_ = true;
466
4
    notifier_.notify_all();
467
4
    pending_instance_cond_.notify_all();
468
4
    {
469
4
        std::lock_guard lock(mtx_);
470
4
        for (auto& [_, recycler] : recycling_instance_map_) {
471
0
            recycler->stop();
472
0
        }
473
4
    }
474
20
    for (auto& w : workers_) {
475
20
        if (w.joinable()) w.join();
476
20
    }
477
4
    if (checker_) {
478
0
        checker_->stop();
479
0
    }
480
4
    if (snapshot_data_migrator_) {
481
0
        snapshot_data_migrator_->stop();
482
0
    }
483
4
    if (snapshot_chain_compactor_) {
484
0
        snapshot_chain_compactor_->stop();
485
0
    }
486
4
}
487
488
class InstanceRecycler::InvertedIndexIdCache {
489
public:
490
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
491
130
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
492
493
    // Return 0 if success, 1 if schema kv not found, negative for error
494
    // For the same index_id, schema_version, res, since `get` is not completely atomic
495
    // one thread has not finished inserting, and another thread has not get the index_id and schema_version,
496
    // resulting in repeated addition and inaccuracy.
497
    // however, this approach can reduce the lock range and sacrifice a bit of meta repeated get to improve concurrency performance.
498
    // repeated addition does not affect correctness.
499
28.4k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
500
28.4k
        {
501
28.4k
            std::lock_guard lock(mtx_);
502
28.4k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
503
3.87k
                return 0;
504
3.87k
            }
505
24.5k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
506
24.5k
                it != inverted_index_id_map_.end()) {
507
16.4k
                res = it->second;
508
16.4k
                return 0;
509
16.4k
            }
510
24.5k
        }
511
        // Get schema from kv
512
        // TODO(plat1ko): Single flight
513
8.08k
        std::unique_ptr<Transaction> txn;
514
8.08k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
515
8.08k
        if (err != TxnErrorCode::TXN_OK) {
516
0
            LOG(WARNING) << "failed to create txn, err=" << err;
517
0
            return -1;
518
0
        }
519
8.08k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
520
8.08k
        ValueBuf val_buf;
521
8.08k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
522
8.08k
        if (err != TxnErrorCode::TXN_OK) {
523
500
            LOG(WARNING) << "failed to get schema, err=" << err;
524
500
            return static_cast<int>(err);
525
500
        }
526
7.58k
        doris::TabletSchemaCloudPB schema;
527
7.58k
        if (!parse_schema_value(val_buf, &schema)) {
528
0
            LOG(WARNING) << "malformed schema value, key=" << hex(schema_key);
529
0
            return -1;
530
0
        }
531
7.58k
        if (schema.index_size() > 0) {
532
5.75k
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
533
5.75k
            if (schema.has_inverted_index_storage_format()) {
534
5.74k
                index_format = schema.inverted_index_storage_format();
535
5.74k
            }
536
5.75k
            res.first = index_format;
537
5.75k
            res.second.reserve(schema.index_size());
538
13.5k
            for (auto& i : schema.index()) {
539
13.5k
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
540
13.5k
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
541
13.5k
                }
542
13.5k
            }
543
5.75k
        }
544
7.58k
        insert(index_id, schema_version, res);
545
7.58k
        return 0;
546
7.58k
    }
547
548
    // Empty `ids` means this schema has no inverted index
549
7.58k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
550
7.58k
        if (index_info.second.empty()) {
551
1.83k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
552
1.83k
            std::lock_guard lock(mtx_);
553
1.83k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
554
5.75k
        } else {
555
5.75k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
556
5.75k
            std::lock_guard lock(mtx_);
557
5.75k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
558
5.75k
        }
559
7.58k
    }
560
561
private:
562
    std::string instance_id_;
563
    std::shared_ptr<TxnKv> txn_kv_;
564
565
    std::mutex mtx_;
566
    using Key = std::pair<int64_t, int32_t>; // <index_id, schema_version>
567
    struct HashOfKey {
568
60.5k
        size_t operator()(const Key& key) const {
569
60.5k
            size_t seed = 0;
570
60.5k
            seed = std::hash<int64_t> {}(key.first);
571
60.5k
            seed = std::hash<int32_t> {}(key.second);
572
60.5k
            return seed;
573
60.5k
        }
574
    };
575
    // <index_id, schema_version> -> inverted_index_ids
576
    std::unordered_map<Key, InvertedIndexInfo, HashOfKey> inverted_index_id_map_;
577
    // Store <index_id, schema_version> of schema which doesn't have inverted index
578
    std::unordered_set<Key, HashOfKey> schemas_without_inverted_index_;
579
};
580
581
InstanceRecycler::InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
582
                                   RecyclerThreadPoolGroup thread_pool_group,
583
                                   std::shared_ptr<TxnLazyCommitter> txn_lazy_committer)
584
        : txn_kv_(std::move(txn_kv)),
585
          instance_id_(instance.instance_id()),
586
          instance_info_(instance),
587
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
588
          _thread_pool_group(std::move(thread_pool_group)),
589
          txn_lazy_committer_(std::move(txn_lazy_committer)),
590
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
591
130
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
592
130
    delete_bitmap_lock_white_list_->init();
593
130
    resource_mgr_->init();
594
130
    snapshot_manager_ = std::make_shared<SnapshotManager>(txn_kv_);
595
596
    // Since the recycler's resource manager could not be notified when instance info changes,
597
    // we need to refresh the instance info here to ensure the resource manager has the latest info.
598
130
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
599
130
};
600
601
130
InstanceRecycler::~InstanceRecycler() = default;
602
603
114
int InstanceRecycler::init_obj_store_accessors() {
604
114
    for (const auto& obj_info : instance_info_.obj_info()) {
605
74
#ifdef UNIT_TEST
606
74
        auto accessor = std::make_shared<MockAccessor>();
607
#else
608
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
609
        if (!s3_conf) {
610
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
611
            return -1;
612
        }
613
614
        std::shared_ptr<S3Accessor> accessor;
615
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
616
        if (ret != 0) {
617
            LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
618
                         << " resource_id=" << obj_info.id();
619
            return ret;
620
        }
621
#endif
622
74
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
623
74
    }
624
625
114
    return 0;
626
114
}
627
628
114
int InstanceRecycler::init_storage_vault_accessors() {
629
114
    if (instance_info_.resource_ids().empty()) {
630
107
        return 0;
631
107
    }
632
633
7
    FullRangeGetOptions opts(txn_kv_);
634
7
    opts.prefetch = true;
635
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
636
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
637
638
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
639
18
        auto [k, v] = *kv;
640
18
        StorageVaultPB vault;
641
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
642
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
643
0
            return -1;
644
0
        }
645
18
        std::string recycler_storage_vault_white_list = accumulate(
646
18
                config::recycler_storage_vault_white_list.begin(),
647
18
                config::recycler_storage_vault_white_list.end(), std::string(),
648
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
Line
Count
Source
648
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
649
18
        LOG_INFO("config::recycler_storage_vault_white_list")
650
18
                .tag("", recycler_storage_vault_white_list);
651
18
        if (!config::recycler_storage_vault_white_list.empty()) {
652
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
653
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
654
8
                it == config::recycler_storage_vault_white_list.end()) {
655
2
                LOG_WARNING(
656
2
                        "failed to init accessor for vault because this vault is not in "
657
2
                        "config::recycler_storage_vault_white_list. ")
658
2
                        .tag(" vault name:", vault.name())
659
2
                        .tag(" config::recycler_storage_vault_white_list:",
660
2
                             recycler_storage_vault_white_list);
661
2
                continue;
662
2
            }
663
8
        }
664
16
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
665
16
                                 &accessor_map_, &vault);
666
16
        if (vault.has_hdfs_info()) {
667
9
#ifdef ENABLE_HDFS_STORAGE_VAULT
668
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
669
9
            int ret = accessor->init();
670
9
            if (ret != 0) {
671
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
672
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
673
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
674
4
                continue;
675
4
            }
676
5
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
677
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
678
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
679
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
680
#else
681
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
682
                       << "but HDFS storage vaults were detected";
683
#endif
684
7
        } else if (vault.has_obj_info()) {
685
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
686
7
            if (!s3_conf) {
687
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
688
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
689
1
                continue;
690
1
            }
691
692
6
            std::shared_ptr<S3Accessor> accessor;
693
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
694
6
            if (ret != 0) {
695
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
696
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
697
0
                             << " ret=" << ret
698
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
699
0
                continue;
700
0
            }
701
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
702
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
703
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
704
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
705
6
        }
706
16
    }
707
708
7
    if (!it->is_valid()) {
709
0
        LOG_WARNING("failed to get storage vault kv");
710
0
        return -1;
711
0
    }
712
713
7
    if (accessor_map_.empty()) {
714
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
715
1
        return -2;
716
1
    }
717
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
718
6
             instance_id_);
719
720
6
    return 0;
721
7
}
722
723
114
int InstanceRecycler::init() {
724
114
    int ret = init_obj_store_accessors();
725
114
    if (ret != 0) {
726
0
        return ret;
727
0
    }
728
729
114
    return init_storage_vault_accessors();
730
114
}
731
732
template <typename... Func>
733
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
120
    return [funcs...]() {
735
120
        return [](std::initializer_list<int> ret_vals) {
736
120
            int i = 0;
737
140
            for (int ret : ret_vals) {
738
140
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
140
            }
742
120
            return i;
743
120
        }({funcs()...});
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
20
            for (int ret : ret_vals) {
738
20
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
20
            }
742
10
            return i;
743
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
20
            for (int ret : ret_vals) {
738
20
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
20
            }
742
10
            return i;
743
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
120
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
120
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
746
747
10
int InstanceRecycler::do_recycle() {
748
10
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
749
10
    tablet_metrics_context_.reset();
750
10
    segment_metrics_context_.reset();
751
10
    DORIS_CLOUD_DEFER {
752
10
        tablet_metrics_context_.finish_report();
753
10
        segment_metrics_context_.finish_report();
754
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
751
10
    DORIS_CLOUD_DEFER {
752
10
        tablet_metrics_context_.finish_report();
753
10
        segment_metrics_context_.finish_report();
754
10
    };
755
10
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
756
0
        int res = recycle_cluster_snapshots();
757
0
        if (res != 0) {
758
0
            return -1;
759
0
        }
760
0
        return recycle_deleted_instance();
761
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
762
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
763
10
                                        fmt::format("instance id {}", instance_id_),
764
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
764
120
                                        [](int r) { return r != 0; });
765
10
        sync_executor
766
10
                .add(task_wrapper(
767
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
767
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
768
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_3clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_3clEv
Line
Count
Source
768
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
769
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
770
                                   // becase they may both recycle the same set of tablets
771
                        // recycle dropped table or idexes(mv, rollup)
772
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
772
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
773
                        // recycle dropped partitions
774
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
774
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
775
10
                .add(task_wrapper(
776
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
776
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
777
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_7clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_7clEv
Line
Count
Source
777
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
778
10
                .add(task_wrapper(
779
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
779
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
780
10
                .add(task_wrapper(
781
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
781
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
782
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
782
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
783
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_11clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_11clEv
Line
Count
Source
783
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
784
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_12clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_12clEv
Line
Count
Source
784
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
785
10
                .add(task_wrapper(
786
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
786
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
787
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_14clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_14clEv
Line
Count
Source
787
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
788
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_15clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_15clEv
Line
Count
Source
788
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
789
10
        bool finished = true;
790
10
        std::vector<int> rets = sync_executor.when_all(&finished);
791
120
        for (int ret : rets) {
792
120
            if (ret != 0) {
793
0
                return ret;
794
0
            }
795
120
        }
796
10
        return finished ? 0 : -1;
797
10
    } else {
798
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
799
0
                     << " instance_id=" << instance_id_;
800
0
        return -1;
801
0
    }
802
10
}
803
804
/**
805
* 1. delete all remote data
806
* 2. delete all kv
807
* 3. remove instance kv
808
*/
809
4
int InstanceRecycler::recycle_deleted_instance() {
810
4
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
811
812
4
    int ret = 0;
813
4
    auto start_time = steady_clock::now();
814
815
4
    DORIS_CLOUD_DEFER {
816
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
817
4
        LOG(WARNING) << (ret == 0 ? "successfully" : "failed to")
818
4
                     << " recycle deleted instance, cost=" << cost
819
4
                     << "s, instance_id=" << instance_id_;
820
4
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
815
4
    DORIS_CLOUD_DEFER {
816
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
817
4
        LOG(WARNING) << (ret == 0 ? "successfully" : "failed to")
818
4
                     << " recycle deleted instance, cost=" << cost
819
4
                     << "s, instance_id=" << instance_id_;
820
4
    };
821
822
    // Step 1: Recycle versioned rowsets in recycle space (already marked for deletion)
823
4
    if (recycle_versioned_rowsets() != 0) {
824
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
825
0
        return -1;
826
0
    }
827
828
    // Step 2: Recycle operation logs (can recycle logs not referenced by snapshots)
829
4
    if (recycle_operation_logs() != 0) {
830
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
831
0
        return -1;
832
0
    }
833
834
    // Step 3: Check if there are still cluster snapshots
835
4
    bool has_snapshots = false;
836
4
    if (has_cluster_snapshots(&has_snapshots) != 0) {
837
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
838
0
        return -1;
839
4
    } else if (has_snapshots) {
840
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
841
1
        return 0;
842
1
    }
843
844
3
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
845
3
                            instance_info().snapshot_switch_status() !=
846
0
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
847
3
    if (snapshot_enabled) {
848
0
        bool has_unrecycled_rowsets = false;
849
0
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
850
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
851
0
            return -1;
852
0
        } else if (has_unrecycled_rowsets) {
853
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
854
0
                    .tag("instance_id", instance_id_);
855
0
            return ret;
856
0
        }
857
3
    } else { // delete all remote data if snapshot is disabled
858
3
        for (auto& [_, accessor] : accessor_map_) {
859
3
            if (stopped()) {
860
0
                return ret;
861
0
            }
862
863
3
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
864
3
            int del_ret = accessor->delete_all();
865
3
            if (del_ret == 0) {
866
3
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
867
3
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
868
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
869
                // so the recycling has been successful.
870
0
                ret = -1;
871
0
            }
872
3
        }
873
874
3
        if (ret != 0) {
875
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
876
0
            return ret;
877
0
        }
878
3
    }
879
880
    // delete all kv
881
3
    std::unique_ptr<Transaction> txn;
882
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
883
3
    if (err != TxnErrorCode::TXN_OK) {
884
0
        LOG(WARNING) << "failed to create txn";
885
0
        ret = -1;
886
0
        return -1;
887
0
    }
888
3
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
889
    // delete kv before deleting objects to prevent the checker from misjudging data loss
890
3
    std::string start_txn_key = txn_key_prefix(instance_id_);
891
3
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
892
3
    txn->remove(start_txn_key, end_txn_key);
893
3
    std::string start_version_key = version_key_prefix(instance_id_);
894
3
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
895
3
    txn->remove(start_version_key, end_version_key);
896
3
    std::string start_meta_key = meta_key_prefix(instance_id_);
897
3
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
898
3
    txn->remove(start_meta_key, end_meta_key);
899
3
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
900
3
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
901
3
    txn->remove(start_recycle_key, end_recycle_key);
902
3
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
903
3
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
904
3
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
905
3
    std::string start_copy_key = copy_key_prefix(instance_id_);
906
3
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
907
3
    txn->remove(start_copy_key, end_copy_key);
908
    // should not remove job key range, because we need to reserve job recycle kv
909
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
910
3
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
911
3
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
912
3
    txn->remove(start_job_tablet_key, end_job_tablet_key);
913
3
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
914
3
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
915
3
    std::string start_vault_key = storage_vault_key(key_info0);
916
3
    std::string end_vault_key = storage_vault_key(key_info1);
917
3
    txn->remove(start_vault_key, end_vault_key);
918
3
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
919
3
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
920
3
    txn->remove(versioned_version_key_start, versioned_version_key_end);
921
3
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
922
3
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
923
3
    txn->remove(versioned_index_key_start, versioned_index_key_end);
924
3
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
925
3
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
926
3
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
927
3
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
928
3
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
929
3
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
930
3
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
931
3
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
932
3
    txn->remove(versioned_data_key_start, versioned_data_key_end);
933
3
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
934
3
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
935
3
    txn->remove(versioned_log_key_start, versioned_log_key_end);
936
3
    err = txn->commit();
937
3
    if (err != TxnErrorCode::TXN_OK) {
938
0
        LOG(WARNING) << "failed to delete all kv, instance_id=" << instance_id_ << ", err=" << err;
939
0
        ret = -1;
940
0
    }
941
942
3
    if (ret == 0) {
943
        // remove instance kv
944
        // ATTN: MUST ensure that cloud platform won't regenerate the same instance id
945
3
        err = txn_kv_->create_txn(&txn);
946
3
        if (err != TxnErrorCode::TXN_OK) {
947
0
            LOG(WARNING) << "failed to create txn";
948
0
            ret = -1;
949
0
            return ret;
950
0
        }
951
3
        std::string key;
952
3
        instance_key({instance_id_}, &key);
953
3
        txn->atomic_add(system_meta_service_instance_update_key(), 1);
954
3
        txn->remove(key);
955
3
        err = txn->commit();
956
3
        if (err != TxnErrorCode::TXN_OK) {
957
0
            LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
958
0
                         << " err=" << err;
959
0
            ret = -1;
960
0
        }
961
3
    }
962
3
    return ret;
963
3
}
964
965
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
966
9
                                          bool* exists, PackedFileRecycleStats* stats) {
967
9
    if (exists == nullptr) {
968
0
        return -1;
969
0
    }
970
9
    *exists = false;
971
972
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
973
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
974
9
    std::string scan_begin = begin;
975
976
9
    while (true) {
977
9
        std::unique_ptr<RangeGetIterator> it_range;
978
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
979
9
        if (get_ret < 0) {
980
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
981
0
                    .tag("instance_id", instance_id_)
982
0
                    .tag("tablet_id", tablet_id)
983
0
                    .tag("ret", get_ret);
984
0
            return -1;
985
0
        }
986
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
987
6
            return 0;
988
6
        }
989
990
3
        std::string last_key;
991
3
        while (it_range->has_next()) {
992
3
            auto [k, v] = it_range->next();
993
3
            last_key.assign(k.data(), k.size());
994
3
            doris::RowsetMetaCloudPB rowset_meta;
995
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
996
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
997
0
                        .tag("instance_id", instance_id_)
998
0
                        .tag("tablet_id", tablet_id)
999
0
                        .tag("key", hex(k));
1000
0
                continue;
1001
0
            }
1002
3
            if (stats) {
1003
3
                ++stats->rowset_scan_count;
1004
3
            }
1005
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1006
3
                *exists = true;
1007
3
                return 0;
1008
3
            }
1009
3
        }
1010
1011
0
        if (!it_range->more()) {
1012
0
            return 0;
1013
0
        }
1014
1015
        // Continue scanning from the next key to keep each transaction short.
1016
0
        scan_begin = std::move(last_key);
1017
0
        scan_begin.push_back('\x00');
1018
0
    }
1019
9
}
1020
1021
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1022
                                                          const std::string& rowset_id,
1023
                                                          int64_t txn_id, bool* recycle_exists,
1024
11
                                                          bool* tmp_exists) {
1025
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1026
0
        return -1;
1027
0
    }
1028
11
    *recycle_exists = false;
1029
11
    *tmp_exists = false;
1030
1031
11
    if (txn_id <= 0) {
1032
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1033
0
                .tag("instance_id", instance_id_)
1034
0
                .tag("tablet_id", tablet_id)
1035
0
                .tag("rowset_id", rowset_id)
1036
0
                .tag("txn_id", txn_id);
1037
0
        return -1;
1038
0
    }
1039
1040
11
    std::unique_ptr<Transaction> txn;
1041
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1042
11
    if (err != TxnErrorCode::TXN_OK) {
1043
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1044
0
                .tag("instance_id", instance_id_)
1045
0
                .tag("tablet_id", tablet_id)
1046
0
                .tag("rowset_id", rowset_id)
1047
0
                .tag("txn_id", txn_id)
1048
0
                .tag("err", err);
1049
0
        return -1;
1050
0
    }
1051
1052
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1053
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1054
11
    if (ret == TxnErrorCode::TXN_OK) {
1055
1
        *recycle_exists = true;
1056
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1057
0
        LOG_WARNING("failed to check recycle rowset existence")
1058
0
                .tag("instance_id", instance_id_)
1059
0
                .tag("tablet_id", tablet_id)
1060
0
                .tag("rowset_id", rowset_id)
1061
0
                .tag("key", hex(recycle_key))
1062
0
                .tag("err", ret);
1063
0
        return -1;
1064
0
    }
1065
1066
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1067
11
    ret = key_exists(txn.get(), tmp_key, true);
1068
11
    if (ret == TxnErrorCode::TXN_OK) {
1069
1
        *tmp_exists = true;
1070
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1071
0
        LOG_WARNING("failed to check tmp rowset existence")
1072
0
                .tag("instance_id", instance_id_)
1073
0
                .tag("tablet_id", tablet_id)
1074
0
                .tag("txn_id", txn_id)
1075
0
                .tag("key", hex(tmp_key))
1076
0
                .tag("err", ret);
1077
0
        return -1;
1078
0
    }
1079
1080
11
    return 0;
1081
11
}
1082
1083
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1084
8
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1085
8
    if (!hint.empty()) {
1086
8
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1087
8
            return {hint, it->second};
1088
8
        }
1089
8
    }
1090
1091
0
    return {"", nullptr};
1092
8
}
1093
1094
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1095
                                               const std::string& packed_file_path,
1096
3
                                               PackedFileRecycleStats* stats) {
1097
3
    bool local_changed = false;
1098
3
    int64_t left_num = 0;
1099
3
    int64_t left_bytes = 0;
1100
3
    bool all_small_files_confirmed = true;
1101
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1102
1103
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1104
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1105
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1106
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1107
14
        LOG_INFO("packed slice correction status")
1108
14
                .tag("instance_id", instance_id_)
1109
14
                .tag("packed_file_path", packed_file_path)
1110
14
                .tag("small_file_path", file.path())
1111
14
                .tag("tablet_id", tablet_id)
1112
14
                .tag("rowset_id", rowset_id)
1113
14
                .tag("txn_id", txn_id)
1114
14
                .tag("size", file.size())
1115
14
                .tag("deleted", file.deleted())
1116
14
                .tag("corrected", file.corrected())
1117
14
                .tag("confirmed_this_round", confirmed_this_round);
1118
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24correct_packed_file_infoEPNS0_16PackedFileInfoPBEPbRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS1_22PackedFileRecycleStatsEENK3$_0clERKNS0_13PackedSlicePBEb
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24correct_packed_file_infoEPNS0_16PackedFileInfoPBEPbRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS1_22PackedFileRecycleStatsEENK3$_0clERKNS0_13PackedSlicePBEb
Line
Count
Source
1103
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1104
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1105
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1106
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1107
14
        LOG_INFO("packed slice correction status")
1108
14
                .tag("instance_id", instance_id_)
1109
14
                .tag("packed_file_path", packed_file_path)
1110
14
                .tag("small_file_path", file.path())
1111
14
                .tag("tablet_id", tablet_id)
1112
14
                .tag("rowset_id", rowset_id)
1113
14
                .tag("txn_id", txn_id)
1114
14
                .tag("size", file.size())
1115
14
                .tag("deleted", file.deleted())
1116
14
                .tag("corrected", file.corrected())
1117
14
                .tag("confirmed_this_round", confirmed_this_round);
1118
14
    };
1119
1120
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1121
14
        auto* small_file = packed_info->mutable_slices(i);
1122
14
        if (small_file->deleted()) {
1123
3
            log_small_file_status(*small_file, small_file->corrected());
1124
3
            continue;
1125
3
        }
1126
1127
11
        if (small_file->corrected()) {
1128
0
            left_num++;
1129
0
            left_bytes += small_file->size();
1130
0
            log_small_file_status(*small_file, true);
1131
0
            continue;
1132
0
        }
1133
1134
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1135
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1136
0
                    .tag("instance_id", instance_id_)
1137
0
                    .tag("small_file_path", small_file->path())
1138
0
                    .tag("index", i);
1139
0
            return -1;
1140
0
        }
1141
1142
11
        int64_t tablet_id = small_file->tablet_id();
1143
11
        const std::string& rowset_id = small_file->rowset_id();
1144
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1145
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1146
0
                    .tag("instance_id", instance_id_)
1147
0
                    .tag("small_file_path", small_file->path())
1148
0
                    .tag("index", i)
1149
0
                    .tag("tablet_id", tablet_id)
1150
0
                    .tag("rowset_id", rowset_id)
1151
0
                    .tag("has_txn_id", small_file->has_txn_id())
1152
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1153
0
            return -1;
1154
0
        }
1155
11
        int64_t txn_id = small_file->txn_id();
1156
11
        bool recycle_exists = false;
1157
11
        bool tmp_exists = false;
1158
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1159
11
                                                &tmp_exists) != 0) {
1160
0
            return -1;
1161
0
        }
1162
1163
11
        bool small_file_confirmed = false;
1164
11
        if (tmp_exists) {
1165
1
            left_num++;
1166
1
            left_bytes += small_file->size();
1167
1
            small_file_confirmed = true;
1168
10
        } else if (recycle_exists) {
1169
1
            left_num++;
1170
1
            left_bytes += small_file->size();
1171
            // keep small_file_confirmed=false so the packed file remains uncorrected
1172
9
        } else {
1173
9
            bool rowset_exists = false;
1174
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1175
0
                return -1;
1176
0
            }
1177
1178
9
            if (!rowset_exists) {
1179
6
                if (!small_file->deleted()) {
1180
6
                    small_file->set_deleted(true);
1181
6
                    local_changed = true;
1182
6
                }
1183
6
                if (!small_file->corrected()) {
1184
6
                    small_file->set_corrected(true);
1185
6
                    local_changed = true;
1186
6
                }
1187
6
                small_file_confirmed = true;
1188
6
            } else {
1189
3
                left_num++;
1190
3
                left_bytes += small_file->size();
1191
3
                small_file_confirmed = true;
1192
3
            }
1193
9
        }
1194
1195
11
        if (!small_file_confirmed) {
1196
1
            all_small_files_confirmed = false;
1197
1
        }
1198
1199
11
        if (small_file->corrected() != small_file_confirmed) {
1200
4
            small_file->set_corrected(small_file_confirmed);
1201
4
            local_changed = true;
1202
4
        }
1203
1204
11
        log_small_file_status(*small_file, small_file_confirmed);
1205
11
    }
1206
1207
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1208
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1209
3
        local_changed = true;
1210
3
    }
1211
3
    if (packed_info->ref_cnt() != left_num) {
1212
3
        auto old_ref_cnt = packed_info->ref_cnt();
1213
3
        packed_info->set_ref_cnt(left_num);
1214
3
        LOG_INFO("corrected packed file ref count")
1215
3
                .tag("instance_id", instance_id_)
1216
3
                .tag("resource_id", packed_info->resource_id())
1217
3
                .tag("packed_file_path", packed_file_path)
1218
3
                .tag("old_ref_cnt", old_ref_cnt)
1219
3
                .tag("new_ref_cnt", left_num);
1220
3
        local_changed = true;
1221
3
    }
1222
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1223
2
        packed_info->set_corrected(all_small_files_confirmed);
1224
2
        local_changed = true;
1225
2
    }
1226
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1227
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1228
1
        local_changed = true;
1229
1
    }
1230
1231
3
    if (changed != nullptr) {
1232
3
        *changed = local_changed;
1233
3
    }
1234
3
    return 0;
1235
3
}
1236
1237
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1238
                                                 const std::string& packed_file_path,
1239
4
                                                 PackedFileRecycleStats* stats) {
1240
4
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1241
4
    bool correction_ok = false;
1242
4
    cloud::PackedFileInfoPB packed_info;
1243
1244
4
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1245
4
        if (stopped()) {
1246
0
            LOG_WARNING("recycler stopped before processing packed file")
1247
0
                    .tag("instance_id", instance_id_)
1248
0
                    .tag("packed_file_path", packed_file_path)
1249
0
                    .tag("attempt", attempt);
1250
0
            return -1;
1251
0
        }
1252
1253
4
        std::unique_ptr<Transaction> txn;
1254
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1255
4
        if (err != TxnErrorCode::TXN_OK) {
1256
0
            LOG_WARNING("failed to create txn when processing packed file")
1257
0
                    .tag("instance_id", instance_id_)
1258
0
                    .tag("packed_file_path", packed_file_path)
1259
0
                    .tag("attempt", attempt)
1260
0
                    .tag("err", err);
1261
0
            return -1;
1262
0
        }
1263
1264
4
        std::string packed_val;
1265
4
        err = txn->get(packed_key, &packed_val);
1266
4
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1267
0
            return 0;
1268
0
        }
1269
4
        if (err != TxnErrorCode::TXN_OK) {
1270
0
            LOG_WARNING("failed to get packed file kv")
1271
0
                    .tag("instance_id", instance_id_)
1272
0
                    .tag("packed_file_path", packed_file_path)
1273
0
                    .tag("attempt", attempt)
1274
0
                    .tag("err", err);
1275
0
            return -1;
1276
0
        }
1277
1278
4
        if (!packed_info.ParseFromString(packed_val)) {
1279
0
            LOG_WARNING("failed to parse packed file info")
1280
0
                    .tag("instance_id", instance_id_)
1281
0
                    .tag("packed_file_path", packed_file_path)
1282
0
                    .tag("attempt", attempt);
1283
0
            return -1;
1284
0
        }
1285
1286
4
        int64_t now_sec = ::time(nullptr);
1287
4
        bool corrected = packed_info.corrected();
1288
4
        bool due = config::force_immediate_recycle ||
1289
4
                   now_sec - packed_info.created_at_sec() >=
1290
4
                           config::packed_file_correction_delay_seconds;
1291
1292
4
        if (!corrected && due) {
1293
3
            bool changed = false;
1294
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1295
0
                LOG_WARNING("correct_packed_file_info failed")
1296
0
                        .tag("instance_id", instance_id_)
1297
0
                        .tag("packed_file_path", packed_file_path)
1298
0
                        .tag("attempt", attempt);
1299
0
                return -1;
1300
0
            }
1301
3
            if (changed) {
1302
3
                std::string updated;
1303
3
                if (!packed_info.SerializeToString(&updated)) {
1304
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1305
0
                            .tag("instance_id", instance_id_)
1306
0
                            .tag("packed_file_path", packed_file_path)
1307
0
                            .tag("attempt", attempt);
1308
0
                    return -1;
1309
0
                }
1310
3
                txn->put(packed_key, updated);
1311
3
                err = txn->commit();
1312
3
                if (err == TxnErrorCode::TXN_OK) {
1313
3
                    if (stats) {
1314
3
                        ++stats->num_corrected;
1315
3
                    }
1316
3
                } else {
1317
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1318
0
                        LOG_WARNING(
1319
0
                                "failed to commit correction for packed file due to conflict, "
1320
0
                                "retrying")
1321
0
                                .tag("instance_id", instance_id_)
1322
0
                                .tag("packed_file_path", packed_file_path)
1323
0
                                .tag("attempt", attempt);
1324
0
                        sleep_for_packed_file_retry();
1325
0
                        packed_info.Clear();
1326
0
                        continue;
1327
0
                    }
1328
0
                    LOG_WARNING("failed to commit correction for packed file")
1329
0
                            .tag("instance_id", instance_id_)
1330
0
                            .tag("packed_file_path", packed_file_path)
1331
0
                            .tag("attempt", attempt)
1332
0
                            .tag("err", err);
1333
0
                    return -1;
1334
0
                }
1335
3
            }
1336
3
        }
1337
1338
4
        correction_ok = true;
1339
4
        break;
1340
4
    }
1341
1342
4
    if (!correction_ok) {
1343
0
        return -1;
1344
0
    }
1345
1346
4
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1347
4
          packed_info.ref_cnt() == 0)) {
1348
3
        return 0;
1349
3
    }
1350
1351
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1352
0
        LOG_WARNING("packed file missing resource id when recycling")
1353
0
                .tag("instance_id", instance_id_)
1354
0
                .tag("packed_file_path", packed_file_path);
1355
0
        return -1;
1356
0
    }
1357
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1358
1
    if (!accessor) {
1359
0
        LOG_WARNING("no accessor available to delete packed file")
1360
0
                .tag("instance_id", instance_id_)
1361
0
                .tag("packed_file_path", packed_file_path)
1362
0
                .tag("resource_id", packed_info.resource_id());
1363
0
        return -1;
1364
0
    }
1365
1
    int del_ret = accessor->delete_file(packed_file_path);
1366
1
    if (del_ret != 0 && del_ret != 1) {
1367
0
        LOG_WARNING("failed to delete packed file")
1368
0
                .tag("instance_id", instance_id_)
1369
0
                .tag("packed_file_path", packed_file_path)
1370
0
                .tag("resource_id", resource_id)
1371
0
                .tag("ret", del_ret);
1372
0
        return -1;
1373
0
    }
1374
1
    if (del_ret == 1) {
1375
0
        LOG_INFO("packed file already removed")
1376
0
                .tag("instance_id", instance_id_)
1377
0
                .tag("packed_file_path", packed_file_path)
1378
0
                .tag("resource_id", resource_id);
1379
1
    } else {
1380
1
        LOG_INFO("deleted packed file")
1381
1
                .tag("instance_id", instance_id_)
1382
1
                .tag("packed_file_path", packed_file_path)
1383
1
                .tag("resource_id", resource_id);
1384
1
    }
1385
1386
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1387
1
        std::unique_ptr<Transaction> del_txn;
1388
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1389
1
        if (err != TxnErrorCode::TXN_OK) {
1390
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1391
0
                    .tag("instance_id", instance_id_)
1392
0
                    .tag("packed_file_path", packed_file_path)
1393
0
                    .tag("del_attempt", del_attempt)
1394
0
                    .tag("err", err);
1395
0
            return -1;
1396
0
        }
1397
1398
1
        std::string latest_val;
1399
1
        err = del_txn->get(packed_key, &latest_val);
1400
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1401
0
            return 0;
1402
0
        }
1403
1
        if (err != TxnErrorCode::TXN_OK) {
1404
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1405
0
                    .tag("instance_id", instance_id_)
1406
0
                    .tag("packed_file_path", packed_file_path)
1407
0
                    .tag("del_attempt", del_attempt)
1408
0
                    .tag("err", err);
1409
0
            return -1;
1410
0
        }
1411
1412
1
        cloud::PackedFileInfoPB latest_info;
1413
1
        if (!latest_info.ParseFromString(latest_val)) {
1414
0
            LOG_WARNING("failed to parse packed file info before removal")
1415
0
                    .tag("instance_id", instance_id_)
1416
0
                    .tag("packed_file_path", packed_file_path)
1417
0
                    .tag("del_attempt", del_attempt);
1418
0
            return -1;
1419
0
        }
1420
1421
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1422
1
              latest_info.ref_cnt() == 0)) {
1423
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1424
0
                    .tag("instance_id", instance_id_)
1425
0
                    .tag("packed_file_path", packed_file_path)
1426
0
                    .tag("del_attempt", del_attempt);
1427
0
            return 0;
1428
0
        }
1429
1430
1
        del_txn->remove(packed_key);
1431
1
        err = del_txn->commit();
1432
1
        if (err == TxnErrorCode::TXN_OK) {
1433
1
            if (stats) {
1434
1
                ++stats->num_deleted;
1435
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1436
1
                                        static_cast<int64_t>(latest_val.size());
1437
1
                if (del_ret == 0 || del_ret == 1) {
1438
1
                    ++stats->num_object_deleted;
1439
1
                    int64_t object_size = latest_info.total_slice_bytes();
1440
1
                    if (object_size <= 0) {
1441
0
                        object_size = packed_info.total_slice_bytes();
1442
0
                    }
1443
1
                    stats->bytes_object_deleted += object_size;
1444
1
                }
1445
1
            }
1446
1
            LOG_INFO("removed packed file metadata")
1447
1
                    .tag("instance_id", instance_id_)
1448
1
                    .tag("packed_file_path", packed_file_path);
1449
1
            return 0;
1450
1
        }
1451
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1452
0
            if (del_attempt >= max_retry_times) {
1453
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1454
0
                        .tag("instance_id", instance_id_)
1455
0
                        .tag("packed_file_path", packed_file_path)
1456
0
                        .tag("del_attempt", del_attempt);
1457
0
                return -1;
1458
0
            }
1459
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1460
0
                    .tag("instance_id", instance_id_)
1461
0
                    .tag("packed_file_path", packed_file_path)
1462
0
                    .tag("del_attempt", del_attempt);
1463
0
            sleep_for_packed_file_retry();
1464
0
            continue;
1465
0
        }
1466
0
        LOG_WARNING("failed to remove packed file kv")
1467
0
                .tag("instance_id", instance_id_)
1468
0
                .tag("packed_file_path", packed_file_path)
1469
0
                .tag("del_attempt", del_attempt)
1470
0
                .tag("err", err);
1471
0
        return -1;
1472
0
    }
1473
1474
0
    return -1;
1475
1
}
1476
1477
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view /*value*/,
1478
4
                                            PackedFileRecycleStats* stats, int* ret) {
1479
4
    if (stats) {
1480
4
        ++stats->num_scanned;
1481
4
    }
1482
4
    std::string packed_file_path;
1483
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1484
0
        LOG_WARNING("failed to decode packed file key")
1485
0
                .tag("instance_id", instance_id_)
1486
0
                .tag("key", hex(key));
1487
0
        if (stats) {
1488
0
            ++stats->num_failed;
1489
0
        }
1490
0
        if (ret) {
1491
0
            *ret = -1;
1492
0
        }
1493
0
        return 0;
1494
0
    }
1495
1496
4
    std::string packed_key(key);
1497
4
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1498
4
    if (process_ret != 0) {
1499
0
        if (stats) {
1500
0
            ++stats->num_failed;
1501
0
        }
1502
0
        if (ret) {
1503
0
            *ret = -1;
1504
0
        }
1505
0
    }
1506
4
    return 0;
1507
4
}
1508
1509
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1510
9.77k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1511
9.77k
    if (config::force_immediate_recycle) {
1512
15
        return 0L;
1513
15
    }
1514
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1515
9.75k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1516
9.75k
    int64_t retention_seconds = config::retention_seconds;
1517
9.75k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1518
7.80k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1519
7.80k
    }
1520
9.75k
    int64_t final_expiration = expiration + retention_seconds;
1521
9.75k
    if (*earlest_ts > final_expiration) {
1522
7
        *earlest_ts = final_expiration;
1523
7
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1524
7
    }
1525
9.75k
    return final_expiration;
1526
9.77k
}
1527
1528
int64_t calculate_partition_expired_time(
1529
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1530
9
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1531
9
    if (config::force_immediate_recycle) {
1532
3
        return 0L;
1533
3
    }
1534
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1535
6
                                                            : partition_meta_pb.creation_time();
1536
6
    int64_t retention_seconds = config::retention_seconds;
1537
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1538
6
        retention_seconds =
1539
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1540
6
    }
1541
6
    int64_t final_expiration = expiration + retention_seconds;
1542
6
    if (*earlest_ts > final_expiration) {
1543
2
        *earlest_ts = final_expiration;
1544
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1545
2
    }
1546
6
    return final_expiration;
1547
9
}
1548
1549
int64_t calculate_index_expired_time(const std::string& instance_id_,
1550
                                     const RecycleIndexPB& index_meta_pb,
1551
10
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1552
10
    if (config::force_immediate_recycle) {
1553
4
        return 0L;
1554
4
    }
1555
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1556
6
                                                        : index_meta_pb.creation_time();
1557
6
    int64_t retention_seconds = config::retention_seconds;
1558
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1559
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1560
6
    }
1561
6
    int64_t final_expiration = expiration + retention_seconds;
1562
6
    if (*earlest_ts > final_expiration) {
1563
2
        *earlest_ts = final_expiration;
1564
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1565
2
    }
1566
6
    return final_expiration;
1567
10
}
1568
1569
int64_t calculate_tmp_rowset_expired_time(
1570
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1571
102k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1572
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1573
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1574
    //  duration or timeout always < `retention_time` in practice.
1575
102k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1576
102k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1577
102k
                                 : tmp_rowset_meta_pb.creation_time();
1578
102k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1579
102k
    int64_t final_expiration = expiration + config::retention_seconds;
1580
102k
    if (*earlest_ts > final_expiration) {
1581
18
        *earlest_ts = final_expiration;
1582
18
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1583
18
    }
1584
102k
    return final_expiration;
1585
102k
}
1586
1587
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1588
30.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1589
30.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1590
30.0k
    if (*earlest_ts > final_expiration / 1000) {
1591
8
        *earlest_ts = final_expiration / 1000;
1592
8
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1593
8
    }
1594
30.0k
    return final_expiration;
1595
30.0k
}
1596
1597
int64_t calculate_restore_job_expired_time(
1598
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1599
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1600
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1601
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1602
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1603
        // final state, recycle immediately
1604
41
        return 0L;
1605
41
    }
1606
    // not final state, wait much longer than the FE's timeout(1 day)
1607
0
    int64_t last_modified_s =
1608
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1609
0
    int64_t expiration = restore_job.expired_at_s() > 0
1610
0
                                 ? last_modified_s + restore_job.expired_at_s()
1611
0
                                 : last_modified_s;
1612
0
    int64_t final_expiration = expiration + config::retention_seconds;
1613
0
    if (*earlest_ts > final_expiration) {
1614
0
        *earlest_ts = final_expiration;
1615
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1616
0
    }
1617
0
    return final_expiration;
1618
41
}
1619
1620
2
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1621
2
    AbortTxnRequest req;
1622
2
    TxnInfoPB txn_info;
1623
2
    MetaServiceCode code = MetaServiceCode::OK;
1624
2
    std::string msg;
1625
2
    std::stringstream ss;
1626
2
    std::unique_ptr<Transaction> txn;
1627
2
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1628
2
    if (err != TxnErrorCode::TXN_OK) {
1629
0
        LOG_WARNING("failed to create txn").tag("err", err);
1630
0
        return -1;
1631
0
    }
1632
1633
    // get txn index
1634
2
    TxnIndexPB txn_idx_pb;
1635
2
    auto index_key = txn_index_key({instance_id_, txn_id});
1636
2
    std::string index_val;
1637
2
    err = txn->get(index_key, &index_val);
1638
2
    if (err != TxnErrorCode::TXN_OK) {
1639
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1640
            // maybe recycled
1641
0
            LOG_INFO("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1642
0
                    .tag("key", hex(index_key))
1643
0
                    .tag("txn_id", txn_id);
1644
0
            return 0;
1645
0
        }
1646
0
        LOG_WARNING("failed to get txn index")
1647
0
                .tag("err", err)
1648
0
                .tag("key", hex(index_key))
1649
0
                .tag("txn_id", txn_id);
1650
0
        return -1;
1651
0
    }
1652
2
    if (!txn_idx_pb.ParseFromString(index_val)) {
1653
0
        LOG_WARNING("failed to parse txn index")
1654
0
                .tag("err", err)
1655
0
                .tag("key", hex(index_key))
1656
0
                .tag("txn_id", txn_id);
1657
0
        return -1;
1658
0
    }
1659
1660
2
    auto info_key = txn_info_key({instance_id_, txn_idx_pb.tablet_index().db_id(), txn_id});
1661
2
    std::string info_val;
1662
2
    err = txn->get(info_key, &info_val);
1663
2
    if (err != TxnErrorCode::TXN_OK) {
1664
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1665
            // maybe recycled
1666
0
            LOG_INFO("txn info not found, txn_id={} instance_id={}", txn_id, instance_id_)
1667
0
                    .tag("key", hex(info_key))
1668
0
                    .tag("txn_id", txn_id);
1669
0
            return 0;
1670
0
        }
1671
0
        LOG_WARNING("failed to get txn info")
1672
0
                .tag("err", err)
1673
0
                .tag("key", hex(info_key))
1674
0
                .tag("txn_id", txn_id);
1675
0
        return -1;
1676
0
    }
1677
2
    if (!txn_info.ParseFromString(info_val)) {
1678
0
        LOG_WARNING("failed to parse txn info")
1679
0
                .tag("err", err)
1680
0
                .tag("key", hex(info_key))
1681
0
                .tag("txn_id", txn_id);
1682
0
        return -1;
1683
0
    }
1684
1685
2
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
1686
0
        LOG_INFO("txn is not prepared status, txn_id={} status={}", txn_id, txn_info.status())
1687
0
                .tag("key", hex(info_key))
1688
0
                .tag("txn_id", txn_id);
1689
0
        return 0;
1690
0
    }
1691
1692
2
    req.set_txn_id(txn_id);
1693
1694
2
    LOG(INFO) << "begin abort txn for related rowset, txn_id=" << txn_id
1695
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString();
1696
1697
2
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
1698
2
    err = txn->commit();
1699
2
    if (err != TxnErrorCode::TXN_OK) {
1700
0
        code = cast_as<ErrCategory::COMMIT>(err);
1701
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
1702
0
        msg = ss.str();
1703
0
        return -1;
1704
0
    }
1705
1706
2
    LOG(INFO) << "finish abort txn for related rowset, txn_id=" << txn_id
1707
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString()
1708
2
              << " code=" << code << " msg=" << msg;
1709
1710
2
    return 0;
1711
2
}
1712
1713
4
int InstanceRecycler::abort_job_for_related_rowset(const RowsetMetaCloudPB& rowset_meta) {
1714
4
    FinishTabletJobRequest req;
1715
4
    FinishTabletJobResponse res;
1716
4
    req.set_action(FinishTabletJobRequest::ABORT);
1717
4
    MetaServiceCode code = MetaServiceCode::OK;
1718
4
    std::string msg;
1719
4
    std::stringstream ss;
1720
1721
4
    TabletIndexPB tablet_idx;
1722
4
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, rowset_meta.tablet_id(), tablet_idx);
1723
4
    if (ret == 1) {
1724
        // tablet maybe recycled, directly return 0
1725
1
        return 0;
1726
3
    } else if (ret != 0) {
1727
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << rowset_meta.tablet_id()
1728
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
1729
0
        return ret;
1730
0
    }
1731
1732
3
    std::unique_ptr<Transaction> txn;
1733
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1734
3
    if (err != TxnErrorCode::TXN_OK) {
1735
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
1736
0
        return -1;
1737
0
    }
1738
1739
3
    std::string job_key =
1740
3
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
1741
3
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
1742
3
    std::string job_val;
1743
3
    err = txn->get(job_key, &job_val);
1744
3
    if (err != TxnErrorCode::TXN_OK) {
1745
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1746
0
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
1747
0
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
1748
0
            return 0;
1749
0
        }
1750
0
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
1751
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
1752
0
                     << " key=" << hex(job_key);
1753
0
        return -1;
1754
0
    }
1755
1756
3
    TabletJobInfoPB job_pb;
1757
3
    if (!job_pb.ParseFromString(job_val)) {
1758
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
1759
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
1760
0
        return -1;
1761
0
    }
1762
1763
3
    std::string job_id {};
1764
3
    if (!job_pb.compaction().empty()) {
1765
2
        for (const auto& c : job_pb.compaction()) {
1766
2
            if (c.id() == rowset_meta.job_id()) {
1767
2
                job_id = c.id();
1768
2
                break;
1769
2
            }
1770
2
        }
1771
2
    } else if (job_pb.has_schema_change()) {
1772
1
        job_id = job_pb.schema_change().id();
1773
1
    }
1774
1775
3
    if (!job_id.empty() && rowset_meta.job_id() == job_id) {
1776
3
        LOG(INFO) << "begin to abort job for related rowset, job_id=" << rowset_meta.job_id()
1777
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
1778
3
        req.mutable_job()->CopyFrom(job_pb);
1779
3
        req.set_action(FinishTabletJobRequest::ABORT);
1780
3
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
1781
3
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
1782
3
                           ss);
1783
3
        if (code != MetaServiceCode::OK) {
1784
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
1785
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
1786
0
                         << " msg=" << msg;
1787
0
            return -1;
1788
0
        }
1789
3
        LOG(INFO) << "finish abort job for related rowset, job_id=" << rowset_meta.job_id()
1790
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
1791
3
                  << " code=" << code << " msg=" << msg;
1792
3
    } else {
1793
        // clang-format off
1794
0
        LOG(INFO) << "there is no job for related rowset, directly recycle rowset data"
1795
0
                  << ", instance_id=" << instance_id_ 
1796
0
                  << ", tablet_id=" << tablet_idx.tablet_id() 
1797
0
                  << ", job_id=" << job_id
1798
0
                  << ", rowset_id=" << rowset_meta.rowset_id_v2();
1799
        // clang-format on
1800
0
    }
1801
1802
3
    return 0;
1803
3
}
1804
1805
template <typename T>
1806
54.7k
int InstanceRecycler::abort_txn_or_job_for_recycle(T& rowset_meta_pb) {
1807
54.7k
    RowsetMetaCloudPB* rs_meta;
1808
54.7k
    RecycleRowsetPB::Type rowset_type = RecycleRowsetPB::PREPARE;
1809
1810
54.7k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1811
        // For keys that are not in the RecycleRowsetPB::PREPARE state
1812
        // we do not need to check the job or txn state
1813
        // because tmp_rowset_key already exists when this key is generated.
1814
3.75k
        rowset_type = rowset_meta_pb.type();
1815
3.75k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1816
51.0k
    } else {
1817
51.0k
        rs_meta = &rowset_meta_pb;
1818
51.0k
    }
1819
1820
54.7k
    DCHECK(rs_meta != nullptr);
1821
1822
    // compaction/sc will generate recycle_rowset_key for each input rowset with load_id
1823
    // we need skip them because the related txn has been finished
1824
    // load_rowset1 load_rowset2 => pick for compaction => compact_rowset
1825
    // compact_rowset1 compact_rowset2 => pick for compaction/sc job => new_rowset
1826
54.7k
    if (rowset_type == RecycleRowsetPB::PREPARE) {
1827
51.6k
        if (rs_meta->has_load_id()) {
1828
            // load
1829
2
            return abort_txn_for_related_rowset(rs_meta->txn_id());
1830
51.6k
        } else if (rs_meta->has_job_id()) {
1831
            // compaction / schema change
1832
3
            return abort_job_for_related_rowset(*rs_meta);
1833
3
        }
1834
51.6k
    }
1835
1836
54.7k
    return 0;
1837
54.7k
}
_ZN5doris5cloud16InstanceRecycler28abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRT_
Line
Count
Source
1806
3.75k
int InstanceRecycler::abort_txn_or_job_for_recycle(T& rowset_meta_pb) {
1807
3.75k
    RowsetMetaCloudPB* rs_meta;
1808
3.75k
    RecycleRowsetPB::Type rowset_type = RecycleRowsetPB::PREPARE;
1809
1810
3.75k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1811
        // For keys that are not in the RecycleRowsetPB::PREPARE state
1812
        // we do not need to check the job or txn state
1813
        // because tmp_rowset_key already exists when this key is generated.
1814
3.75k
        rowset_type = rowset_meta_pb.type();
1815
3.75k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1816
3.75k
    } else {
1817
3.75k
        rs_meta = &rowset_meta_pb;
1818
3.75k
    }
1819
1820
3.75k
    DCHECK(rs_meta != nullptr);
1821
1822
    // compaction/sc will generate recycle_rowset_key for each input rowset with load_id
1823
    // we need skip them because the related txn has been finished
1824
    // load_rowset1 load_rowset2 => pick for compaction => compact_rowset
1825
    // compact_rowset1 compact_rowset2 => pick for compaction/sc job => new_rowset
1826
3.75k
    if (rowset_type == RecycleRowsetPB::PREPARE) {
1827
652
        if (rs_meta->has_load_id()) {
1828
            // load
1829
1
            return abort_txn_for_related_rowset(rs_meta->txn_id());
1830
651
        } else if (rs_meta->has_job_id()) {
1831
            // compaction / schema change
1832
1
            return abort_job_for_related_rowset(*rs_meta);
1833
1
        }
1834
652
    }
1835
1836
3.75k
    return 0;
1837
3.75k
}
_ZN5doris5cloud16InstanceRecycler28abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRT_
Line
Count
Source
1806
51.0k
int InstanceRecycler::abort_txn_or_job_for_recycle(T& rowset_meta_pb) {
1807
51.0k
    RowsetMetaCloudPB* rs_meta;
1808
51.0k
    RecycleRowsetPB::Type rowset_type = RecycleRowsetPB::PREPARE;
1809
1810
51.0k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1811
        // For keys that are not in the RecycleRowsetPB::PREPARE state
1812
        // we do not need to check the job or txn state
1813
        // because tmp_rowset_key already exists when this key is generated.
1814
51.0k
        rowset_type = rowset_meta_pb.type();
1815
51.0k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1816
51.0k
    } else {
1817
51.0k
        rs_meta = &rowset_meta_pb;
1818
51.0k
    }
1819
1820
51.0k
    DCHECK(rs_meta != nullptr);
1821
1822
    // compaction/sc will generate recycle_rowset_key for each input rowset with load_id
1823
    // we need skip them because the related txn has been finished
1824
    // load_rowset1 load_rowset2 => pick for compaction => compact_rowset
1825
    // compact_rowset1 compact_rowset2 => pick for compaction/sc job => new_rowset
1826
51.0k
    if (rowset_type == RecycleRowsetPB::PREPARE) {
1827
51.0k
        if (rs_meta->has_load_id()) {
1828
            // load
1829
1
            return abort_txn_for_related_rowset(rs_meta->txn_id());
1830
51.0k
        } else if (rs_meta->has_job_id()) {
1831
            // compaction / schema change
1832
2
            return abort_job_for_related_rowset(*rs_meta);
1833
2
        }
1834
51.0k
    }
1835
1836
51.0k
    return 0;
1837
51.0k
}
1838
1839
template <typename T>
1840
int mark_rowset_as_recycled(TxnKv* txn_kv, const std::string& instance_id, std::string_view key,
1841
109k
                            T& rowset_meta_pb) {
1842
109k
    RowsetMetaCloudPB* rs_meta;
1843
1844
109k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1845
102k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1846
102k
    } else {
1847
102k
        rs_meta = &rowset_meta_pb;
1848
102k
    }
1849
1850
109k
    bool need_write_back = false;
1851
109k
    if ((!rs_meta->has_is_recycled() || !rs_meta->is_recycled())) {
1852
54.7k
        need_write_back = true;
1853
54.7k
        rs_meta->set_is_recycled(true);
1854
54.7k
    }
1855
1856
109k
    if (need_write_back) {
1857
54.7k
        std::unique_ptr<Transaction> txn;
1858
54.7k
        TxnErrorCode err = txn_kv->create_txn(&txn);
1859
54.7k
        if (err != TxnErrorCode::TXN_OK) {
1860
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1861
0
            return -1;
1862
0
        }
1863
        // double check becase of new transaction
1864
54.7k
        T rowset_meta;
1865
54.7k
        std::string val;
1866
54.7k
        err = txn->get(key, &val);
1867
54.7k
        if (!rowset_meta.ParseFromString(val)) {
1868
0
            LOG(WARNING) << "failed to parse rs_meta, instance_id=" << instance_id;
1869
0
            return -1;
1870
0
        }
1871
54.7k
        if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1872
51.0k
            rs_meta = rowset_meta.mutable_rowset_meta();
1873
51.0k
        } else {
1874
51.0k
            rs_meta = &rowset_meta;
1875
51.0k
        }
1876
54.7k
        if ((rs_meta->has_is_recycled() && rs_meta->is_recycled())) {
1877
0
            return 0;
1878
0
        }
1879
54.7k
        rs_meta->set_is_recycled(true);
1880
54.7k
        val.clear();
1881
54.7k
        rowset_meta.SerializeToString(&val);
1882
54.7k
        txn->put(key, val);
1883
54.7k
        err = txn->commit();
1884
54.7k
        if (err != TxnErrorCode::TXN_OK) {
1885
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
1886
0
            return -1;
1887
0
        }
1888
54.7k
    }
1889
109k
    return need_write_back ? 1 : 0;
1890
109k
}
_ZN5doris5cloud23mark_rowset_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS8_ERT_
Line
Count
Source
1841
7.50k
                            T& rowset_meta_pb) {
1842
7.50k
    RowsetMetaCloudPB* rs_meta;
1843
1844
7.50k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1845
7.50k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1846
7.50k
    } else {
1847
7.50k
        rs_meta = &rowset_meta_pb;
1848
7.50k
    }
1849
1850
7.50k
    bool need_write_back = false;
1851
7.50k
    if ((!rs_meta->has_is_recycled() || !rs_meta->is_recycled())) {
1852
3.75k
        need_write_back = true;
1853
3.75k
        rs_meta->set_is_recycled(true);
1854
3.75k
    }
1855
1856
7.50k
    if (need_write_back) {
1857
3.75k
        std::unique_ptr<Transaction> txn;
1858
3.75k
        TxnErrorCode err = txn_kv->create_txn(&txn);
1859
3.75k
        if (err != TxnErrorCode::TXN_OK) {
1860
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1861
0
            return -1;
1862
0
        }
1863
        // double check becase of new transaction
1864
3.75k
        T rowset_meta;
1865
3.75k
        std::string val;
1866
3.75k
        err = txn->get(key, &val);
1867
3.75k
        if (!rowset_meta.ParseFromString(val)) {
1868
0
            LOG(WARNING) << "failed to parse rs_meta, instance_id=" << instance_id;
1869
0
            return -1;
1870
0
        }
1871
3.75k
        if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1872
3.75k
            rs_meta = rowset_meta.mutable_rowset_meta();
1873
3.75k
        } else {
1874
3.75k
            rs_meta = &rowset_meta;
1875
3.75k
        }
1876
3.75k
        if ((rs_meta->has_is_recycled() && rs_meta->is_recycled())) {
1877
0
            return 0;
1878
0
        }
1879
3.75k
        rs_meta->set_is_recycled(true);
1880
3.75k
        val.clear();
1881
3.75k
        rowset_meta.SerializeToString(&val);
1882
3.75k
        txn->put(key, val);
1883
3.75k
        err = txn->commit();
1884
3.75k
        if (err != TxnErrorCode::TXN_OK) {
1885
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
1886
0
            return -1;
1887
0
        }
1888
3.75k
    }
1889
7.50k
    return need_write_back ? 1 : 0;
1890
7.50k
}
_ZN5doris5cloud23mark_rowset_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS8_ERT_
Line
Count
Source
1841
102k
                            T& rowset_meta_pb) {
1842
102k
    RowsetMetaCloudPB* rs_meta;
1843
1844
102k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1845
102k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1846
102k
    } else {
1847
102k
        rs_meta = &rowset_meta_pb;
1848
102k
    }
1849
1850
102k
    bool need_write_back = false;
1851
102k
    if ((!rs_meta->has_is_recycled() || !rs_meta->is_recycled())) {
1852
51.0k
        need_write_back = true;
1853
51.0k
        rs_meta->set_is_recycled(true);
1854
51.0k
    }
1855
1856
102k
    if (need_write_back) {
1857
51.0k
        std::unique_ptr<Transaction> txn;
1858
51.0k
        TxnErrorCode err = txn_kv->create_txn(&txn);
1859
51.0k
        if (err != TxnErrorCode::TXN_OK) {
1860
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1861
0
            return -1;
1862
0
        }
1863
        // double check becase of new transaction
1864
51.0k
        T rowset_meta;
1865
51.0k
        std::string val;
1866
51.0k
        err = txn->get(key, &val);
1867
51.0k
        if (!rowset_meta.ParseFromString(val)) {
1868
0
            LOG(WARNING) << "failed to parse rs_meta, instance_id=" << instance_id;
1869
0
            return -1;
1870
0
        }
1871
51.0k
        if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1872
51.0k
            rs_meta = rowset_meta.mutable_rowset_meta();
1873
51.0k
        } else {
1874
51.0k
            rs_meta = &rowset_meta;
1875
51.0k
        }
1876
51.0k
        if ((rs_meta->has_is_recycled() && rs_meta->is_recycled())) {
1877
0
            return 0;
1878
0
        }
1879
51.0k
        rs_meta->set_is_recycled(true);
1880
51.0k
        val.clear();
1881
51.0k
        rowset_meta.SerializeToString(&val);
1882
51.0k
        txn->put(key, val);
1883
51.0k
        err = txn->commit();
1884
51.0k
        if (err != TxnErrorCode::TXN_OK) {
1885
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
1886
0
            return -1;
1887
0
        }
1888
51.0k
    }
1889
102k
    return need_write_back ? 1 : 0;
1890
102k
}
1891
1892
0
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
1893
0
    const std::string task_name = "recycle_ref_rowsets";
1894
0
    *has_unrecycled_rowsets = false;
1895
1896
0
    std::string data_rowset_ref_count_key_start =
1897
0
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
1898
0
    std::string data_rowset_ref_count_key_end =
1899
0
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
1900
1901
0
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
1902
1903
0
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
1904
0
    register_recycle_task(task_name, start_time);
1905
1906
0
    DORIS_CLOUD_DEFER {
1907
0
        unregister_recycle_task(task_name);
1908
0
        int64_t cost =
1909
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
1910
0
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
1911
0
                .tag("instance_id", instance_id_);
1912
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
1913
1914
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
1915
0
    std::set<int64_t> tablets_with_refs;
1916
0
    int64_t num_scanned = 0;
1917
1918
0
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
1919
0
        ++num_scanned;
1920
0
        int64_t tablet_id;
1921
0
        std::string rowset_id;
1922
0
        std::string_view key(k);
1923
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
1924
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
1925
0
            return 0; // Continue scanning
1926
0
        }
1927
1928
0
        tablets_with_refs.insert(tablet_id);
1929
0
        return 0;
1930
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
1931
1932
0
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
1933
0
                         std::move(scan_func)) != 0) {
1934
0
        LOG_WARNING("failed to scan data rowset ref count keys");
1935
0
        return -1;
1936
0
    }
1937
1938
0
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
1939
0
             tablets_with_refs.size(), num_scanned)
1940
0
            .tag("instance_id", instance_id_);
1941
1942
    // Phase 2: Recycle each tablet
1943
0
    int64_t num_recycled_tablets = 0;
1944
0
    for (int64_t tablet_id : tablets_with_refs) {
1945
0
        if (stopped()) {
1946
0
            LOG_INFO("recycler stopped, skip remaining tablets")
1947
0
                    .tag("instance_id", instance_id_)
1948
0
                    .tag("tablets_processed", num_recycled_tablets)
1949
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
1950
0
            break;
1951
0
        }
1952
1953
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
1954
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
1955
0
            LOG_WARNING("failed to recycle tablet")
1956
0
                    .tag("instance_id", instance_id_)
1957
0
                    .tag("tablet_id", tablet_id);
1958
0
            return -1;
1959
0
        }
1960
0
        ++num_recycled_tablets;
1961
0
    }
1962
1963
0
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
1964
0
            .tag("instance_id", instance_id_)
1965
0
            .tag("total_tablets", tablets_with_refs.size());
1966
1967
    // Phase 3: Scan again to check if any ref count keys still exist
1968
0
    std::unique_ptr<Transaction> txn;
1969
0
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1970
0
    if (err != TxnErrorCode::TXN_OK) {
1971
0
        LOG_WARNING("failed to create txn for final check")
1972
0
                .tag("instance_id", instance_id_)
1973
0
                .tag("err", err);
1974
0
        return -1;
1975
0
    }
1976
1977
0
    std::unique_ptr<RangeGetIterator> iter;
1978
0
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
1979
0
    if (err != TxnErrorCode::TXN_OK) {
1980
0
        LOG_WARNING("failed to create range iterator for final check")
1981
0
                .tag("instance_id", instance_id_)
1982
0
                .tag("err", err);
1983
0
        return -1;
1984
0
    }
1985
1986
0
    *has_unrecycled_rowsets = iter->has_next();
1987
0
    if (*has_unrecycled_rowsets) {
1988
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
1989
0
                .tag("instance_id", instance_id_);
1990
0
    }
1991
1992
0
    return 0;
1993
0
}
1994
1995
17
int InstanceRecycler::recycle_indexes() {
1996
17
    const std::string task_name = "recycle_indexes";
1997
17
    int64_t num_scanned = 0;
1998
17
    int64_t num_expired = 0;
1999
17
    int64_t num_recycled = 0;
2000
17
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2001
2002
17
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2003
17
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2004
17
    std::string index_key0;
2005
17
    std::string index_key1;
2006
17
    recycle_index_key(index_key_info0, &index_key0);
2007
17
    recycle_index_key(index_key_info1, &index_key1);
2008
2009
17
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2010
2011
17
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2012
17
    register_recycle_task(task_name, start_time);
2013
2014
17
    DORIS_CLOUD_DEFER {
2015
17
        unregister_recycle_task(task_name);
2016
17
        int64_t cost =
2017
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2018
17
        metrics_context.finish_report();
2019
17
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2020
17
                .tag("instance_id", instance_id_)
2021
17
                .tag("num_scanned", num_scanned)
2022
17
                .tag("num_expired", num_expired)
2023
17
                .tag("num_recycled", num_recycled);
2024
17
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2014
2
    DORIS_CLOUD_DEFER {
2015
2
        unregister_recycle_task(task_name);
2016
2
        int64_t cost =
2017
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2018
2
        metrics_context.finish_report();
2019
2
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2020
2
                .tag("instance_id", instance_id_)
2021
2
                .tag("num_scanned", num_scanned)
2022
2
                .tag("num_expired", num_expired)
2023
2
                .tag("num_recycled", num_recycled);
2024
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2014
15
    DORIS_CLOUD_DEFER {
2015
15
        unregister_recycle_task(task_name);
2016
15
        int64_t cost =
2017
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2018
15
        metrics_context.finish_report();
2019
15
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2020
15
                .tag("instance_id", instance_id_)
2021
15
                .tag("num_scanned", num_scanned)
2022
15
                .tag("num_expired", num_expired)
2023
15
                .tag("num_recycled", num_recycled);
2024
15
    };
2025
2026
17
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2027
2028
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2029
17
    std::vector<std::string_view> index_keys;
2030
17
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2031
10
        ++num_scanned;
2032
10
        RecycleIndexPB index_pb;
2033
10
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2034
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2035
0
            return -1;
2036
0
        }
2037
10
        int64_t current_time = ::time(nullptr);
2038
10
        if (current_time <
2039
10
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2040
0
            return 0;
2041
0
        }
2042
10
        ++num_expired;
2043
        // decode index_id
2044
10
        auto k1 = k;
2045
10
        k1.remove_prefix(1);
2046
10
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2047
10
        decode_key(&k1, &out);
2048
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2049
10
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2050
10
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2051
10
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2052
10
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2053
        // Change state to RECYCLING
2054
10
        std::unique_ptr<Transaction> txn;
2055
10
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2056
10
        if (err != TxnErrorCode::TXN_OK) {
2057
0
            LOG_WARNING("failed to create txn").tag("err", err);
2058
0
            return -1;
2059
0
        }
2060
10
        std::string val;
2061
10
        err = txn->get(k, &val);
2062
10
        if (err ==
2063
10
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2064
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2065
0
            return 0;
2066
0
        }
2067
10
        if (err != TxnErrorCode::TXN_OK) {
2068
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2069
0
            return -1;
2070
0
        }
2071
10
        index_pb.Clear();
2072
10
        if (!index_pb.ParseFromString(val)) {
2073
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2074
0
            return -1;
2075
0
        }
2076
10
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2077
9
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2078
9
            txn->put(k, index_pb.SerializeAsString());
2079
9
            err = txn->commit();
2080
9
            if (err != TxnErrorCode::TXN_OK) {
2081
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2082
0
                return -1;
2083
0
            }
2084
9
        }
2085
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2086
1
            LOG_WARNING("failed to recycle tablets under index")
2087
1
                    .tag("table_id", index_pb.table_id())
2088
1
                    .tag("instance_id", instance_id_)
2089
1
                    .tag("index_id", index_id);
2090
1
            return -1;
2091
1
        }
2092
2093
9
        if (index_pb.has_db_id()) {
2094
            // Recycle the versioned keys
2095
3
            std::unique_ptr<Transaction> txn;
2096
3
            err = txn_kv_->create_txn(&txn);
2097
3
            if (err != TxnErrorCode::TXN_OK) {
2098
0
                LOG_WARNING("failed to create txn").tag("err", err);
2099
0
                return -1;
2100
0
            }
2101
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2102
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2103
3
            std::string index_inverted_key = versioned::index_inverted_key(
2104
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2105
3
            versioned_remove_all(txn.get(), meta_key);
2106
3
            txn->remove(index_key);
2107
3
            txn->remove(index_inverted_key);
2108
3
            err = txn->commit();
2109
3
            if (err != TxnErrorCode::TXN_OK) {
2110
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2111
0
                return -1;
2112
0
            }
2113
3
        }
2114
2115
9
        metrics_context.total_recycled_num = ++num_recycled;
2116
9
        metrics_context.report();
2117
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2118
9
        index_keys.push_back(k);
2119
9
        return 0;
2120
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2030
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2031
2
        ++num_scanned;
2032
2
        RecycleIndexPB index_pb;
2033
2
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2034
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2035
0
            return -1;
2036
0
        }
2037
2
        int64_t current_time = ::time(nullptr);
2038
2
        if (current_time <
2039
2
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2040
0
            return 0;
2041
0
        }
2042
2
        ++num_expired;
2043
        // decode index_id
2044
2
        auto k1 = k;
2045
2
        k1.remove_prefix(1);
2046
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2047
2
        decode_key(&k1, &out);
2048
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2049
2
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2050
2
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2051
2
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2052
2
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2053
        // Change state to RECYCLING
2054
2
        std::unique_ptr<Transaction> txn;
2055
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2056
2
        if (err != TxnErrorCode::TXN_OK) {
2057
0
            LOG_WARNING("failed to create txn").tag("err", err);
2058
0
            return -1;
2059
0
        }
2060
2
        std::string val;
2061
2
        err = txn->get(k, &val);
2062
2
        if (err ==
2063
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2064
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2065
0
            return 0;
2066
0
        }
2067
2
        if (err != TxnErrorCode::TXN_OK) {
2068
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2069
0
            return -1;
2070
0
        }
2071
2
        index_pb.Clear();
2072
2
        if (!index_pb.ParseFromString(val)) {
2073
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2074
0
            return -1;
2075
0
        }
2076
2
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2077
1
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2078
1
            txn->put(k, index_pb.SerializeAsString());
2079
1
            err = txn->commit();
2080
1
            if (err != TxnErrorCode::TXN_OK) {
2081
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2082
0
                return -1;
2083
0
            }
2084
1
        }
2085
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2086
1
            LOG_WARNING("failed to recycle tablets under index")
2087
1
                    .tag("table_id", index_pb.table_id())
2088
1
                    .tag("instance_id", instance_id_)
2089
1
                    .tag("index_id", index_id);
2090
1
            return -1;
2091
1
        }
2092
2093
1
        if (index_pb.has_db_id()) {
2094
            // Recycle the versioned keys
2095
1
            std::unique_ptr<Transaction> txn;
2096
1
            err = txn_kv_->create_txn(&txn);
2097
1
            if (err != TxnErrorCode::TXN_OK) {
2098
0
                LOG_WARNING("failed to create txn").tag("err", err);
2099
0
                return -1;
2100
0
            }
2101
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2102
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2103
1
            std::string index_inverted_key = versioned::index_inverted_key(
2104
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2105
1
            versioned_remove_all(txn.get(), meta_key);
2106
1
            txn->remove(index_key);
2107
1
            txn->remove(index_inverted_key);
2108
1
            err = txn->commit();
2109
1
            if (err != TxnErrorCode::TXN_OK) {
2110
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2111
0
                return -1;
2112
0
            }
2113
1
        }
2114
2115
1
        metrics_context.total_recycled_num = ++num_recycled;
2116
1
        metrics_context.report();
2117
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2118
1
        index_keys.push_back(k);
2119
1
        return 0;
2120
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2030
8
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2031
8
        ++num_scanned;
2032
8
        RecycleIndexPB index_pb;
2033
8
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2034
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2035
0
            return -1;
2036
0
        }
2037
8
        int64_t current_time = ::time(nullptr);
2038
8
        if (current_time <
2039
8
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2040
0
            return 0;
2041
0
        }
2042
8
        ++num_expired;
2043
        // decode index_id
2044
8
        auto k1 = k;
2045
8
        k1.remove_prefix(1);
2046
8
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2047
8
        decode_key(&k1, &out);
2048
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2049
8
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2050
8
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2051
8
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2052
8
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2053
        // Change state to RECYCLING
2054
8
        std::unique_ptr<Transaction> txn;
2055
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2056
8
        if (err != TxnErrorCode::TXN_OK) {
2057
0
            LOG_WARNING("failed to create txn").tag("err", err);
2058
0
            return -1;
2059
0
        }
2060
8
        std::string val;
2061
8
        err = txn->get(k, &val);
2062
8
        if (err ==
2063
8
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2064
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2065
0
            return 0;
2066
0
        }
2067
8
        if (err != TxnErrorCode::TXN_OK) {
2068
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2069
0
            return -1;
2070
0
        }
2071
8
        index_pb.Clear();
2072
8
        if (!index_pb.ParseFromString(val)) {
2073
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2074
0
            return -1;
2075
0
        }
2076
8
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2077
8
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2078
8
            txn->put(k, index_pb.SerializeAsString());
2079
8
            err = txn->commit();
2080
8
            if (err != TxnErrorCode::TXN_OK) {
2081
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2082
0
                return -1;
2083
0
            }
2084
8
        }
2085
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2086
0
            LOG_WARNING("failed to recycle tablets under index")
2087
0
                    .tag("table_id", index_pb.table_id())
2088
0
                    .tag("instance_id", instance_id_)
2089
0
                    .tag("index_id", index_id);
2090
0
            return -1;
2091
0
        }
2092
2093
8
        if (index_pb.has_db_id()) {
2094
            // Recycle the versioned keys
2095
2
            std::unique_ptr<Transaction> txn;
2096
2
            err = txn_kv_->create_txn(&txn);
2097
2
            if (err != TxnErrorCode::TXN_OK) {
2098
0
                LOG_WARNING("failed to create txn").tag("err", err);
2099
0
                return -1;
2100
0
            }
2101
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2102
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2103
2
            std::string index_inverted_key = versioned::index_inverted_key(
2104
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2105
2
            versioned_remove_all(txn.get(), meta_key);
2106
2
            txn->remove(index_key);
2107
2
            txn->remove(index_inverted_key);
2108
2
            err = txn->commit();
2109
2
            if (err != TxnErrorCode::TXN_OK) {
2110
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2111
0
                return -1;
2112
0
            }
2113
2
        }
2114
2115
8
        metrics_context.total_recycled_num = ++num_recycled;
2116
8
        metrics_context.report();
2117
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2118
8
        index_keys.push_back(k);
2119
8
        return 0;
2120
8
    };
2121
2122
17
    auto loop_done = [&index_keys, this]() -> int {
2123
6
        if (index_keys.empty()) return 0;
2124
5
        DORIS_CLOUD_DEFER {
2125
5
            index_keys.clear();
2126
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2124
1
        DORIS_CLOUD_DEFER {
2125
1
            index_keys.clear();
2126
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2124
4
        DORIS_CLOUD_DEFER {
2125
4
            index_keys.clear();
2126
4
        };
2127
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2128
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2129
0
            return -1;
2130
0
        }
2131
5
        return 0;
2132
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2122
2
    auto loop_done = [&index_keys, this]() -> int {
2123
2
        if (index_keys.empty()) return 0;
2124
1
        DORIS_CLOUD_DEFER {
2125
1
            index_keys.clear();
2126
1
        };
2127
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2128
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2129
0
            return -1;
2130
0
        }
2131
1
        return 0;
2132
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2122
4
    auto loop_done = [&index_keys, this]() -> int {
2123
4
        if (index_keys.empty()) return 0;
2124
4
        DORIS_CLOUD_DEFER {
2125
4
            index_keys.clear();
2126
4
        };
2127
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2128
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2129
0
            return -1;
2130
0
        }
2131
4
        return 0;
2132
4
    };
2133
2134
17
    if (config::enable_recycler_stats_metrics) {
2135
0
        scan_and_statistics_indexes();
2136
0
    }
2137
    // recycle_func and loop_done for scan and recycle
2138
17
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
2139
17
}
2140
2141
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
2142
8.24k
                             int64_t tablet_id) {
2143
8.24k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
2144
2145
8.24k
    std::unique_ptr<Transaction> txn;
2146
8.24k
    TxnErrorCode err = txn_kv->create_txn(&txn);
2147
8.24k
    if (err != TxnErrorCode::TXN_OK) {
2148
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
2149
0
                     << " tablet_id=" << tablet_id << " err=" << err;
2150
0
        return false;
2151
0
    }
2152
2153
8.24k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
2154
8.24k
    std::string tablet_idx_val;
2155
8.24k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
2156
8.24k
    if (TxnErrorCode::TXN_OK != err) {
2157
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
2158
0
                     << " tablet_id=" << tablet_id << " err=" << err
2159
0
                     << " key=" << hex(tablet_idx_key);
2160
0
        return false;
2161
0
    }
2162
2163
8.24k
    TabletIndexPB tablet_idx_pb;
2164
8.24k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
2165
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
2166
0
                     << " tablet_id=" << tablet_id;
2167
0
        return false;
2168
0
    }
2169
2170
8.24k
    if (!tablet_idx_pb.has_db_id()) {
2171
        // In the previous version, the db_id was not set in the index_pb.
2172
        // If updating to the version which enable txn lazy commit, the db_id will be set.
2173
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
2174
0
                  << " instance_id=" << instance_id
2175
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
2176
0
        return true;
2177
0
    }
2178
2179
8.24k
    std::string ver_val;
2180
8.24k
    std::string ver_key =
2181
8.24k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
2182
8.24k
                                   tablet_idx_pb.partition_id()});
2183
8.24k
    err = txn->get(ver_key, &ver_val);
2184
2185
8.24k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
2186
204
        LOG(INFO) << ""
2187
204
                     "partition version not found, instance_id="
2188
204
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
2189
204
                  << " table_id=" << tablet_idx_pb.table_id()
2190
204
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
2191
204
                  << " key=" << hex(ver_key);
2192
204
        return true;
2193
204
    }
2194
2195
8.03k
    if (TxnErrorCode::TXN_OK != err) {
2196
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
2197
0
                     << " db_id=" << tablet_idx_pb.db_id()
2198
0
                     << " table_id=" << tablet_idx_pb.table_id()
2199
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2200
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
2201
0
        return false;
2202
0
    }
2203
2204
8.03k
    VersionPB version_pb;
2205
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
2206
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
2207
0
                     << " db_id=" << tablet_idx_pb.db_id()
2208
0
                     << " table_id=" << tablet_idx_pb.table_id()
2209
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2210
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
2211
0
        return false;
2212
0
    }
2213
2214
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
2215
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
2216
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
2217
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
2218
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
2219
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
2220
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
2221
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
2222
4.00k
                     << " key=" << hex(ver_key);
2223
4.00k
        return false;
2224
4.00k
    }
2225
4.03k
    return true;
2226
8.03k
}
2227
2228
15
int InstanceRecycler::recycle_partitions() {
2229
15
    const std::string task_name = "recycle_partitions";
2230
15
    int64_t num_scanned = 0;
2231
15
    int64_t num_expired = 0;
2232
15
    int64_t num_recycled = 0;
2233
15
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2234
2235
15
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
2236
15
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
2237
15
    std::string part_key0;
2238
15
    std::string part_key1;
2239
15
    recycle_partition_key(part_key_info0, &part_key0);
2240
15
    recycle_partition_key(part_key_info1, &part_key1);
2241
2242
15
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
2243
2244
15
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2245
15
    register_recycle_task(task_name, start_time);
2246
2247
15
    DORIS_CLOUD_DEFER {
2248
15
        unregister_recycle_task(task_name);
2249
15
        int64_t cost =
2250
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2251
15
        metrics_context.finish_report();
2252
15
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2253
15
                .tag("instance_id", instance_id_)
2254
15
                .tag("num_scanned", num_scanned)
2255
15
                .tag("num_expired", num_expired)
2256
15
                .tag("num_recycled", num_recycled);
2257
15
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2247
2
    DORIS_CLOUD_DEFER {
2248
2
        unregister_recycle_task(task_name);
2249
2
        int64_t cost =
2250
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2251
2
        metrics_context.finish_report();
2252
2
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2253
2
                .tag("instance_id", instance_id_)
2254
2
                .tag("num_scanned", num_scanned)
2255
2
                .tag("num_expired", num_expired)
2256
2
                .tag("num_recycled", num_recycled);
2257
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2247
13
    DORIS_CLOUD_DEFER {
2248
13
        unregister_recycle_task(task_name);
2249
13
        int64_t cost =
2250
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2251
13
        metrics_context.finish_report();
2252
13
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2253
13
                .tag("instance_id", instance_id_)
2254
13
                .tag("num_scanned", num_scanned)
2255
13
                .tag("num_expired", num_expired)
2256
13
                .tag("num_recycled", num_recycled);
2257
13
    };
2258
2259
15
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2260
2261
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
2262
15
    std::vector<std::string_view> partition_keys;
2263
15
    std::vector<std::string> partition_version_keys;
2264
15
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2265
9
        ++num_scanned;
2266
9
        RecyclePartitionPB part_pb;
2267
9
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2268
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2269
0
            return -1;
2270
0
        }
2271
9
        int64_t current_time = ::time(nullptr);
2272
9
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2273
9
                                                            &earlest_ts)) { // not expired
2274
0
            return 0;
2275
0
        }
2276
9
        ++num_expired;
2277
        // decode partition_id
2278
9
        auto k1 = k;
2279
9
        k1.remove_prefix(1);
2280
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2281
9
        decode_key(&k1, &out);
2282
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2283
9
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2284
9
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2285
9
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2286
9
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2287
        // Change state to RECYCLING
2288
9
        std::unique_ptr<Transaction> txn;
2289
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2290
9
        if (err != TxnErrorCode::TXN_OK) {
2291
0
            LOG_WARNING("failed to create txn").tag("err", err);
2292
0
            return -1;
2293
0
        }
2294
9
        std::string val;
2295
9
        err = txn->get(k, &val);
2296
9
        if (err ==
2297
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2298
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2299
0
            return 0;
2300
0
        }
2301
9
        if (err != TxnErrorCode::TXN_OK) {
2302
0
            LOG_WARNING("failed to get kv");
2303
0
            return -1;
2304
0
        }
2305
9
        part_pb.Clear();
2306
9
        if (!part_pb.ParseFromString(val)) {
2307
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2308
0
            return -1;
2309
0
        }
2310
        // Partitions with PREPARED state MUST have no data
2311
9
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2312
8
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2313
8
            txn->put(k, part_pb.SerializeAsString());
2314
8
            err = txn->commit();
2315
8
            if (err != TxnErrorCode::TXN_OK) {
2316
0
                LOG_WARNING("failed to commit txn: {}", err);
2317
0
                return -1;
2318
0
            }
2319
8
        }
2320
2321
9
        int ret = 0;
2322
33
        for (int64_t index_id : part_pb.index_id()) {
2323
33
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2324
1
                LOG_WARNING("failed to recycle tablets under partition")
2325
1
                        .tag("table_id", part_pb.table_id())
2326
1
                        .tag("instance_id", instance_id_)
2327
1
                        .tag("index_id", index_id)
2328
1
                        .tag("partition_id", partition_id);
2329
1
                ret = -1;
2330
1
            }
2331
33
        }
2332
9
        if (ret == 0 && part_pb.has_db_id()) {
2333
            // Recycle the versioned keys
2334
8
            std::unique_ptr<Transaction> txn;
2335
8
            err = txn_kv_->create_txn(&txn);
2336
8
            if (err != TxnErrorCode::TXN_OK) {
2337
0
                LOG_WARNING("failed to create txn").tag("err", err);
2338
0
                return -1;
2339
0
            }
2340
8
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2341
8
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2342
8
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2343
8
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2344
8
            std::string partition_version_key =
2345
8
                    versioned::partition_version_key({instance_id_, partition_id});
2346
8
            versioned_remove_all(txn.get(), meta_key);
2347
8
            txn->remove(index_key);
2348
8
            txn->remove(inverted_index_key);
2349
8
            versioned_remove_all(txn.get(), partition_version_key);
2350
8
            err = txn->commit();
2351
8
            if (err != TxnErrorCode::TXN_OK) {
2352
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2353
0
                return -1;
2354
0
            }
2355
8
        }
2356
2357
9
        if (ret == 0) {
2358
8
            ++num_recycled;
2359
8
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2360
8
            partition_keys.push_back(k);
2361
8
            if (part_pb.db_id() > 0) {
2362
8
                partition_version_keys.push_back(partition_version_key(
2363
8
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2364
8
            }
2365
8
            metrics_context.total_recycled_num = num_recycled;
2366
8
            metrics_context.report();
2367
8
        }
2368
9
        return ret;
2369
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2264
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2265
2
        ++num_scanned;
2266
2
        RecyclePartitionPB part_pb;
2267
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2268
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2269
0
            return -1;
2270
0
        }
2271
2
        int64_t current_time = ::time(nullptr);
2272
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2273
2
                                                            &earlest_ts)) { // not expired
2274
0
            return 0;
2275
0
        }
2276
2
        ++num_expired;
2277
        // decode partition_id
2278
2
        auto k1 = k;
2279
2
        k1.remove_prefix(1);
2280
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2281
2
        decode_key(&k1, &out);
2282
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2283
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2284
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2285
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2286
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2287
        // Change state to RECYCLING
2288
2
        std::unique_ptr<Transaction> txn;
2289
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2290
2
        if (err != TxnErrorCode::TXN_OK) {
2291
0
            LOG_WARNING("failed to create txn").tag("err", err);
2292
0
            return -1;
2293
0
        }
2294
2
        std::string val;
2295
2
        err = txn->get(k, &val);
2296
2
        if (err ==
2297
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2298
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2299
0
            return 0;
2300
0
        }
2301
2
        if (err != TxnErrorCode::TXN_OK) {
2302
0
            LOG_WARNING("failed to get kv");
2303
0
            return -1;
2304
0
        }
2305
2
        part_pb.Clear();
2306
2
        if (!part_pb.ParseFromString(val)) {
2307
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2308
0
            return -1;
2309
0
        }
2310
        // Partitions with PREPARED state MUST have no data
2311
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2312
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2313
1
            txn->put(k, part_pb.SerializeAsString());
2314
1
            err = txn->commit();
2315
1
            if (err != TxnErrorCode::TXN_OK) {
2316
0
                LOG_WARNING("failed to commit txn: {}", err);
2317
0
                return -1;
2318
0
            }
2319
1
        }
2320
2321
2
        int ret = 0;
2322
2
        for (int64_t index_id : part_pb.index_id()) {
2323
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2324
1
                LOG_WARNING("failed to recycle tablets under partition")
2325
1
                        .tag("table_id", part_pb.table_id())
2326
1
                        .tag("instance_id", instance_id_)
2327
1
                        .tag("index_id", index_id)
2328
1
                        .tag("partition_id", partition_id);
2329
1
                ret = -1;
2330
1
            }
2331
2
        }
2332
2
        if (ret == 0 && part_pb.has_db_id()) {
2333
            // Recycle the versioned keys
2334
1
            std::unique_ptr<Transaction> txn;
2335
1
            err = txn_kv_->create_txn(&txn);
2336
1
            if (err != TxnErrorCode::TXN_OK) {
2337
0
                LOG_WARNING("failed to create txn").tag("err", err);
2338
0
                return -1;
2339
0
            }
2340
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2341
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2342
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2343
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2344
1
            std::string partition_version_key =
2345
1
                    versioned::partition_version_key({instance_id_, partition_id});
2346
1
            versioned_remove_all(txn.get(), meta_key);
2347
1
            txn->remove(index_key);
2348
1
            txn->remove(inverted_index_key);
2349
1
            versioned_remove_all(txn.get(), partition_version_key);
2350
1
            err = txn->commit();
2351
1
            if (err != TxnErrorCode::TXN_OK) {
2352
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2353
0
                return -1;
2354
0
            }
2355
1
        }
2356
2357
2
        if (ret == 0) {
2358
1
            ++num_recycled;
2359
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2360
1
            partition_keys.push_back(k);
2361
1
            if (part_pb.db_id() > 0) {
2362
1
                partition_version_keys.push_back(partition_version_key(
2363
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2364
1
            }
2365
1
            metrics_context.total_recycled_num = num_recycled;
2366
1
            metrics_context.report();
2367
1
        }
2368
2
        return ret;
2369
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2264
7
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2265
7
        ++num_scanned;
2266
7
        RecyclePartitionPB part_pb;
2267
7
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2268
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2269
0
            return -1;
2270
0
        }
2271
7
        int64_t current_time = ::time(nullptr);
2272
7
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2273
7
                                                            &earlest_ts)) { // not expired
2274
0
            return 0;
2275
0
        }
2276
7
        ++num_expired;
2277
        // decode partition_id
2278
7
        auto k1 = k;
2279
7
        k1.remove_prefix(1);
2280
7
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2281
7
        decode_key(&k1, &out);
2282
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2283
7
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2284
7
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2285
7
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2286
7
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2287
        // Change state to RECYCLING
2288
7
        std::unique_ptr<Transaction> txn;
2289
7
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2290
7
        if (err != TxnErrorCode::TXN_OK) {
2291
0
            LOG_WARNING("failed to create txn").tag("err", err);
2292
0
            return -1;
2293
0
        }
2294
7
        std::string val;
2295
7
        err = txn->get(k, &val);
2296
7
        if (err ==
2297
7
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2298
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2299
0
            return 0;
2300
0
        }
2301
7
        if (err != TxnErrorCode::TXN_OK) {
2302
0
            LOG_WARNING("failed to get kv");
2303
0
            return -1;
2304
0
        }
2305
7
        part_pb.Clear();
2306
7
        if (!part_pb.ParseFromString(val)) {
2307
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2308
0
            return -1;
2309
0
        }
2310
        // Partitions with PREPARED state MUST have no data
2311
7
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2312
7
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2313
7
            txn->put(k, part_pb.SerializeAsString());
2314
7
            err = txn->commit();
2315
7
            if (err != TxnErrorCode::TXN_OK) {
2316
0
                LOG_WARNING("failed to commit txn: {}", err);
2317
0
                return -1;
2318
0
            }
2319
7
        }
2320
2321
7
        int ret = 0;
2322
31
        for (int64_t index_id : part_pb.index_id()) {
2323
31
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2324
0
                LOG_WARNING("failed to recycle tablets under partition")
2325
0
                        .tag("table_id", part_pb.table_id())
2326
0
                        .tag("instance_id", instance_id_)
2327
0
                        .tag("index_id", index_id)
2328
0
                        .tag("partition_id", partition_id);
2329
0
                ret = -1;
2330
0
            }
2331
31
        }
2332
7
        if (ret == 0 && part_pb.has_db_id()) {
2333
            // Recycle the versioned keys
2334
7
            std::unique_ptr<Transaction> txn;
2335
7
            err = txn_kv_->create_txn(&txn);
2336
7
            if (err != TxnErrorCode::TXN_OK) {
2337
0
                LOG_WARNING("failed to create txn").tag("err", err);
2338
0
                return -1;
2339
0
            }
2340
7
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2341
7
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2342
7
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2343
7
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2344
7
            std::string partition_version_key =
2345
7
                    versioned::partition_version_key({instance_id_, partition_id});
2346
7
            versioned_remove_all(txn.get(), meta_key);
2347
7
            txn->remove(index_key);
2348
7
            txn->remove(inverted_index_key);
2349
7
            versioned_remove_all(txn.get(), partition_version_key);
2350
7
            err = txn->commit();
2351
7
            if (err != TxnErrorCode::TXN_OK) {
2352
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2353
0
                return -1;
2354
0
            }
2355
7
        }
2356
2357
7
        if (ret == 0) {
2358
7
            ++num_recycled;
2359
7
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2360
7
            partition_keys.push_back(k);
2361
7
            if (part_pb.db_id() > 0) {
2362
7
                partition_version_keys.push_back(partition_version_key(
2363
7
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2364
7
            }
2365
7
            metrics_context.total_recycled_num = num_recycled;
2366
7
            metrics_context.report();
2367
7
        }
2368
7
        return ret;
2369
7
    };
2370
2371
15
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2372
5
        if (partition_keys.empty()) return 0;
2373
4
        DORIS_CLOUD_DEFER {
2374
4
            partition_keys.clear();
2375
4
            partition_version_keys.clear();
2376
4
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2373
1
        DORIS_CLOUD_DEFER {
2374
1
            partition_keys.clear();
2375
1
            partition_version_keys.clear();
2376
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2373
3
        DORIS_CLOUD_DEFER {
2374
3
            partition_keys.clear();
2375
3
            partition_version_keys.clear();
2376
3
        };
2377
4
        std::unique_ptr<Transaction> txn;
2378
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2379
4
        if (err != TxnErrorCode::TXN_OK) {
2380
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2381
0
            return -1;
2382
0
        }
2383
8
        for (auto& k : partition_keys) {
2384
8
            txn->remove(k);
2385
8
        }
2386
8
        for (auto& k : partition_version_keys) {
2387
8
            txn->remove(k);
2388
8
        }
2389
4
        err = txn->commit();
2390
4
        if (err != TxnErrorCode::TXN_OK) {
2391
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2392
0
                         << " err=" << err;
2393
0
            return -1;
2394
0
        }
2395
4
        return 0;
2396
4
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2371
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2372
2
        if (partition_keys.empty()) return 0;
2373
1
        DORIS_CLOUD_DEFER {
2374
1
            partition_keys.clear();
2375
1
            partition_version_keys.clear();
2376
1
        };
2377
1
        std::unique_ptr<Transaction> txn;
2378
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2379
1
        if (err != TxnErrorCode::TXN_OK) {
2380
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2381
0
            return -1;
2382
0
        }
2383
1
        for (auto& k : partition_keys) {
2384
1
            txn->remove(k);
2385
1
        }
2386
1
        for (auto& k : partition_version_keys) {
2387
1
            txn->remove(k);
2388
1
        }
2389
1
        err = txn->commit();
2390
1
        if (err != TxnErrorCode::TXN_OK) {
2391
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2392
0
                         << " err=" << err;
2393
0
            return -1;
2394
0
        }
2395
1
        return 0;
2396
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2371
3
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2372
3
        if (partition_keys.empty()) return 0;
2373
3
        DORIS_CLOUD_DEFER {
2374
3
            partition_keys.clear();
2375
3
            partition_version_keys.clear();
2376
3
        };
2377
3
        std::unique_ptr<Transaction> txn;
2378
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2379
3
        if (err != TxnErrorCode::TXN_OK) {
2380
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2381
0
            return -1;
2382
0
        }
2383
7
        for (auto& k : partition_keys) {
2384
7
            txn->remove(k);
2385
7
        }
2386
7
        for (auto& k : partition_version_keys) {
2387
7
            txn->remove(k);
2388
7
        }
2389
3
        err = txn->commit();
2390
3
        if (err != TxnErrorCode::TXN_OK) {
2391
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2392
0
                         << " err=" << err;
2393
0
            return -1;
2394
0
        }
2395
3
        return 0;
2396
3
    };
2397
2398
15
    if (config::enable_recycler_stats_metrics) {
2399
0
        scan_and_statistics_partitions();
2400
0
    }
2401
    // recycle_func and loop_done for scan and recycle
2402
15
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
2403
15
}
2404
2405
14
int InstanceRecycler::recycle_versions() {
2406
14
    if (should_recycle_versioned_keys()) {
2407
2
        return recycle_orphan_partitions();
2408
2
    }
2409
2410
12
    int64_t num_scanned = 0;
2411
12
    int64_t num_recycled = 0;
2412
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
2413
2414
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
2415
2416
12
    auto start_time = steady_clock::now();
2417
2418
12
    DORIS_CLOUD_DEFER {
2419
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2420
12
        metrics_context.finish_report();
2421
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
2422
12
                .tag("instance_id", instance_id_)
2423
12
                .tag("num_scanned", num_scanned)
2424
12
                .tag("num_recycled", num_recycled);
2425
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
2418
12
    DORIS_CLOUD_DEFER {
2419
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2420
12
        metrics_context.finish_report();
2421
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
2422
12
                .tag("instance_id", instance_id_)
2423
12
                .tag("num_scanned", num_scanned)
2424
12
                .tag("num_recycled", num_recycled);
2425
12
    };
2426
2427
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
2428
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
2429
12
    int64_t last_scanned_table_id = 0;
2430
12
    bool is_recycled = false; // Is last scanned kv recycled
2431
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
2432
12
                         &metrics_context, this](std::string_view k, std::string_view) {
2433
2
        ++num_scanned;
2434
2
        auto k1 = k;
2435
2
        k1.remove_prefix(1);
2436
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
2437
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2438
2
        decode_key(&k1, &out);
2439
2
        DCHECK_EQ(out.size(), 6) << k;
2440
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
2441
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
2442
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
2443
0
            return 0;
2444
0
        }
2445
2
        last_scanned_table_id = table_id;
2446
2
        is_recycled = false;
2447
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
2448
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
2449
2
        std::unique_ptr<Transaction> txn;
2450
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2451
2
        if (err != TxnErrorCode::TXN_OK) {
2452
0
            return -1;
2453
0
        }
2454
2
        std::unique_ptr<RangeGetIterator> iter;
2455
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
2456
2
        if (err != TxnErrorCode::TXN_OK) {
2457
0
            return -1;
2458
0
        }
2459
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
2460
1
            return 0;
2461
1
        }
2462
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2463
        // 1. Remove all partition version kvs of this table
2464
1
        auto partition_version_key_begin =
2465
1
                partition_version_key({instance_id_, db_id, table_id, 0});
2466
1
        auto partition_version_key_end =
2467
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
2468
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
2469
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
2470
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
2471
1
                     << " table_id=" << table_id;
2472
        // 2. Remove the table version kv of this table
2473
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
2474
1
        txn->remove(tbl_version_key);
2475
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
2476
        // 3. Remove mow delete bitmap update lock and tablet job lock
2477
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2478
1
        txn->remove(lock_key);
2479
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2480
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2481
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2482
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
2483
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2484
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2485
1
                     << " table_id=" << table_id;
2486
1
        err = txn->commit();
2487
1
        if (err != TxnErrorCode::TXN_OK) {
2488
0
            return -1;
2489
0
        }
2490
1
        metrics_context.total_recycled_num = ++num_recycled;
2491
1
        metrics_context.report();
2492
1
        is_recycled = true;
2493
1
        return 0;
2494
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2432
2
                         &metrics_context, this](std::string_view k, std::string_view) {
2433
2
        ++num_scanned;
2434
2
        auto k1 = k;
2435
2
        k1.remove_prefix(1);
2436
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
2437
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2438
2
        decode_key(&k1, &out);
2439
2
        DCHECK_EQ(out.size(), 6) << k;
2440
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
2441
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
2442
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
2443
0
            return 0;
2444
0
        }
2445
2
        last_scanned_table_id = table_id;
2446
2
        is_recycled = false;
2447
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
2448
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
2449
2
        std::unique_ptr<Transaction> txn;
2450
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2451
2
        if (err != TxnErrorCode::TXN_OK) {
2452
0
            return -1;
2453
0
        }
2454
2
        std::unique_ptr<RangeGetIterator> iter;
2455
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
2456
2
        if (err != TxnErrorCode::TXN_OK) {
2457
0
            return -1;
2458
0
        }
2459
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
2460
1
            return 0;
2461
1
        }
2462
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2463
        // 1. Remove all partition version kvs of this table
2464
1
        auto partition_version_key_begin =
2465
1
                partition_version_key({instance_id_, db_id, table_id, 0});
2466
1
        auto partition_version_key_end =
2467
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
2468
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
2469
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
2470
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
2471
1
                     << " table_id=" << table_id;
2472
        // 2. Remove the table version kv of this table
2473
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
2474
1
        txn->remove(tbl_version_key);
2475
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
2476
        // 3. Remove mow delete bitmap update lock and tablet job lock
2477
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2478
1
        txn->remove(lock_key);
2479
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2480
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2481
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2482
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
2483
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2484
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2485
1
                     << " table_id=" << table_id;
2486
1
        err = txn->commit();
2487
1
        if (err != TxnErrorCode::TXN_OK) {
2488
0
            return -1;
2489
0
        }
2490
1
        metrics_context.total_recycled_num = ++num_recycled;
2491
1
        metrics_context.report();
2492
1
        is_recycled = true;
2493
1
        return 0;
2494
1
    };
2495
2496
12
    if (config::enable_recycler_stats_metrics) {
2497
0
        scan_and_statistics_versions();
2498
0
    }
2499
    // recycle_func and loop_done for scan and recycle
2500
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
2501
14
}
2502
2503
3
int InstanceRecycler::recycle_orphan_partitions() {
2504
3
    int64_t num_scanned = 0;
2505
3
    int64_t num_recycled = 0;
2506
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
2507
2508
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
2509
3
            .tag("instance_id", instance_id_);
2510
2511
3
    auto start_time = steady_clock::now();
2512
2513
3
    DORIS_CLOUD_DEFER {
2514
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2515
3
        metrics_context.finish_report();
2516
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
2517
3
                .tag("instance_id", instance_id_)
2518
3
                .tag("num_scanned", num_scanned)
2519
3
                .tag("num_recycled", num_recycled);
2520
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
2513
3
    DORIS_CLOUD_DEFER {
2514
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2515
3
        metrics_context.finish_report();
2516
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
2517
3
                .tag("instance_id", instance_id_)
2518
3
                .tag("num_scanned", num_scanned)
2519
3
                .tag("num_recycled", num_recycled);
2520
3
    };
2521
2522
3
    bool is_empty_table = false;        // whether the table has no indexes
2523
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
2524
3
    int64_t current_table_id = 0;       // current scanning table id
2525
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
2526
3
                         &current_table_id, &is_table_kvs_recycled,
2527
3
                         this](std::string_view k, std::string_view) {
2528
2
        ++num_scanned;
2529
2530
2
        std::string_view k1(k);
2531
2
        int64_t db_id, table_id, partition_id;
2532
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
2533
2
                                                            &partition_id)) {
2534
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
2535
0
            return -1;
2536
2
        } else if (table_id != current_table_id) {
2537
2
            current_table_id = table_id;
2538
2
            is_table_kvs_recycled = false;
2539
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
2540
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
2541
2
            if (err != TxnErrorCode::TXN_OK) {
2542
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
2543
0
                             << " table_id=" << table_id << " err=" << err;
2544
0
                return -1;
2545
0
            }
2546
2
        }
2547
2548
2
        if (!is_empty_table) {
2549
            // table is not empty, skip recycle
2550
1
            return 0;
2551
1
        }
2552
2553
1
        std::unique_ptr<Transaction> txn;
2554
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2555
1
        if (err != TxnErrorCode::TXN_OK) {
2556
0
            return -1;
2557
0
        }
2558
2559
        // 1. Remove all partition related kvs
2560
1
        std::string partition_meta_key =
2561
1
                versioned::meta_partition_key({instance_id_, partition_id});
2562
1
        std::string partition_index_key =
2563
1
                versioned::partition_index_key({instance_id_, partition_id});
2564
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
2565
1
                {instance_id_, db_id, table_id, partition_id});
2566
1
        std::string partition_version_key =
2567
1
                versioned::partition_version_key({instance_id_, partition_id});
2568
1
        txn->remove(partition_index_key);
2569
1
        txn->remove(partition_inverted_key);
2570
1
        versioned_remove_all(txn.get(), partition_meta_key);
2571
1
        versioned_remove_all(txn.get(), partition_version_key);
2572
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
2573
1
                     << " table_id=" << table_id << " db_id=" << db_id
2574
1
                     << " partition_meta_key=" << hex(partition_meta_key)
2575
1
                     << " partition_version_key=" << hex(partition_version_key);
2576
2577
1
        if (!is_table_kvs_recycled) {
2578
1
            is_table_kvs_recycled = true;
2579
2580
            // 2. Remove the table version kv of this table
2581
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
2582
1
            versioned_remove_all(txn.get(), table_version_key);
2583
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
2584
            // 3. Remove mow delete bitmap update lock and tablet job lock
2585
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2586
1
            txn->remove(lock_key);
2587
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2588
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2589
1
            std::string tablet_job_key_end =
2590
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2591
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
2592
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2593
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2594
1
                         << " table_id=" << table_id;
2595
1
        }
2596
2597
1
        err = txn->commit();
2598
1
        if (err != TxnErrorCode::TXN_OK) {
2599
0
            return -1;
2600
0
        }
2601
1
        metrics_context.total_recycled_num = ++num_recycled;
2602
1
        metrics_context.report();
2603
1
        return 0;
2604
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2527
2
                         this](std::string_view k, std::string_view) {
2528
2
        ++num_scanned;
2529
2530
2
        std::string_view k1(k);
2531
2
        int64_t db_id, table_id, partition_id;
2532
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
2533
2
                                                            &partition_id)) {
2534
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
2535
0
            return -1;
2536
2
        } else if (table_id != current_table_id) {
2537
2
            current_table_id = table_id;
2538
2
            is_table_kvs_recycled = false;
2539
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
2540
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
2541
2
            if (err != TxnErrorCode::TXN_OK) {
2542
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
2543
0
                             << " table_id=" << table_id << " err=" << err;
2544
0
                return -1;
2545
0
            }
2546
2
        }
2547
2548
2
        if (!is_empty_table) {
2549
            // table is not empty, skip recycle
2550
1
            return 0;
2551
1
        }
2552
2553
1
        std::unique_ptr<Transaction> txn;
2554
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2555
1
        if (err != TxnErrorCode::TXN_OK) {
2556
0
            return -1;
2557
0
        }
2558
2559
        // 1. Remove all partition related kvs
2560
1
        std::string partition_meta_key =
2561
1
                versioned::meta_partition_key({instance_id_, partition_id});
2562
1
        std::string partition_index_key =
2563
1
                versioned::partition_index_key({instance_id_, partition_id});
2564
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
2565
1
                {instance_id_, db_id, table_id, partition_id});
2566
1
        std::string partition_version_key =
2567
1
                versioned::partition_version_key({instance_id_, partition_id});
2568
1
        txn->remove(partition_index_key);
2569
1
        txn->remove(partition_inverted_key);
2570
1
        versioned_remove_all(txn.get(), partition_meta_key);
2571
1
        versioned_remove_all(txn.get(), partition_version_key);
2572
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
2573
1
                     << " table_id=" << table_id << " db_id=" << db_id
2574
1
                     << " partition_meta_key=" << hex(partition_meta_key)
2575
1
                     << " partition_version_key=" << hex(partition_version_key);
2576
2577
1
        if (!is_table_kvs_recycled) {
2578
1
            is_table_kvs_recycled = true;
2579
2580
            // 2. Remove the table version kv of this table
2581
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
2582
1
            versioned_remove_all(txn.get(), table_version_key);
2583
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
2584
            // 3. Remove mow delete bitmap update lock and tablet job lock
2585
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2586
1
            txn->remove(lock_key);
2587
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2588
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2589
1
            std::string tablet_job_key_end =
2590
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2591
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
2592
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2593
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2594
1
                         << " table_id=" << table_id;
2595
1
        }
2596
2597
1
        err = txn->commit();
2598
1
        if (err != TxnErrorCode::TXN_OK) {
2599
0
            return -1;
2600
0
        }
2601
1
        metrics_context.total_recycled_num = ++num_recycled;
2602
1
        metrics_context.report();
2603
1
        return 0;
2604
1
    };
2605
2606
    // recycle_func and loop_done for scan and recycle
2607
3
    return scan_and_recycle(
2608
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
2609
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
2610
3
            std::move(recycle_func));
2611
3
}
2612
2613
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
2614
                                      RecyclerMetricsContext& metrics_context,
2615
49
                                      int64_t partition_id) {
2616
49
    bool is_multi_version =
2617
49
            instance_info_.has_multi_version_status() &&
2618
49
            instance_info_.multi_version_status() != MultiVersionStatus::MULTI_VERSION_DISABLED;
2619
49
    int64_t num_scanned = 0;
2620
49
    std::atomic_long num_recycled = 0;
2621
2622
49
    std::string tablet_key_begin, tablet_key_end;
2623
49
    std::string stats_key_begin, stats_key_end;
2624
49
    std::string job_key_begin, job_key_end;
2625
2626
49
    std::string tablet_belongs;
2627
49
    if (partition_id > 0) {
2628
        // recycle tablets in a partition belonging to the index
2629
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
2630
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
2631
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
2632
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
2633
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
2634
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
2635
33
        tablet_belongs = "partition";
2636
33
    } else {
2637
        // recycle tablets in the index
2638
16
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
2639
16
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
2640
16
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
2641
16
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
2642
16
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
2643
16
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
2644
16
        tablet_belongs = "index";
2645
16
    }
2646
2647
49
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
2648
49
            .tag("table_id", table_id)
2649
49
            .tag("index_id", index_id)
2650
49
            .tag("partition_id", partition_id);
2651
2652
49
    auto start_time = steady_clock::now();
2653
2654
49
    DORIS_CLOUD_DEFER {
2655
49
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2656
49
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
2657
49
                .tag("instance_id", instance_id_)
2658
49
                .tag("table_id", table_id)
2659
49
                .tag("index_id", index_id)
2660
49
                .tag("partition_id", partition_id)
2661
49
                .tag("num_scanned", num_scanned)
2662
49
                .tag("num_recycled", num_recycled);
2663
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
2654
4
    DORIS_CLOUD_DEFER {
2655
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2656
4
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
2657
4
                .tag("instance_id", instance_id_)
2658
4
                .tag("table_id", table_id)
2659
4
                .tag("index_id", index_id)
2660
4
                .tag("partition_id", partition_id)
2661
4
                .tag("num_scanned", num_scanned)
2662
4
                .tag("num_recycled", num_recycled);
2663
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
2654
45
    DORIS_CLOUD_DEFER {
2655
45
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2656
45
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
2657
45
                .tag("instance_id", instance_id_)
2658
45
                .tag("table_id", table_id)
2659
45
                .tag("index_id", index_id)
2660
45
                .tag("partition_id", partition_id)
2661
45
                .tag("num_scanned", num_scanned)
2662
45
                .tag("num_recycled", num_recycled);
2663
45
    };
2664
2665
    // The first string_view represents the tablet key which has been recycled
2666
    // The second bool represents whether the following fdb's tablet key deletion could be done using range move or not
2667
49
    using TabletKeyPair = std::pair<std::string_view, bool>;
2668
49
    SyncExecutor<TabletKeyPair> sync_executor(
2669
49
            _thread_pool_group.recycle_tablet_pool,
2670
49
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
2671
49
                        index_id, partition_id),
2672
4.23k
            [](const TabletKeyPair& k) { return k.first.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKSt4pairISt17basic_string_viewIcSt11char_traitsIcEEbE
Line
Count
Source
2672
4.00k
            [](const TabletKeyPair& k) { return k.first.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKSt4pairISt17basic_string_viewIcSt11char_traitsIcEEbE
Line
Count
Source
2672
237
            [](const TabletKeyPair& k) { return k.first.empty(); });
2673
2674
    // Elements in `tablet_keys` has the same lifetime as `it` in `scan_and_recycle`
2675
49
    std::vector<std::string> tablet_idx_keys;
2676
49
    std::vector<std::string> restore_job_keys;
2677
49
    std::vector<std::string> init_rs_keys;
2678
49
    std::vector<std::string> tablet_compact_stats_keys;
2679
49
    std::vector<std::string> tablet_load_stats_keys;
2680
49
    std::vector<std::string> versioned_meta_tablet_keys;
2681
8.24k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2682
8.24k
        bool use_range_remove = true;
2683
8.24k
        ++num_scanned;
2684
8.24k
        doris::TabletMetaCloudPB tablet_meta_pb;
2685
8.24k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
2686
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
2687
0
            use_range_remove = false;
2688
0
            return -1;
2689
0
        }
2690
8.24k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
2691
2692
8.24k
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
2693
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
2694
4.00k
            return -1;
2695
4.00k
        }
2696
2697
4.24k
        tablet_idx_keys.push_back(meta_tablet_idx_key({instance_id_, tablet_id}));
2698
4.24k
        restore_job_keys.push_back(job_restore_tablet_key({instance_id_, tablet_id}));
2699
4.24k
        if (is_multi_version) {
2700
            // The tablet index/inverted index are recycled in recycle_versioned_tablet.
2701
6
            tablet_compact_stats_keys.push_back(
2702
6
                    versioned::tablet_compact_stats_key({instance_id_, tablet_id}));
2703
6
            tablet_load_stats_keys.push_back(
2704
6
                    versioned::tablet_load_stats_key({instance_id_, tablet_id}));
2705
6
            versioned_meta_tablet_keys.push_back(
2706
6
                    versioned::meta_tablet_key({instance_id_, tablet_id}));
2707
6
        }
2708
4.24k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
2709
4.23k
        sync_executor.add([this, &num_recycled, tid = tablet_id, range_move = use_range_remove,
2710
4.23k
                           &metrics_context, k]() mutable -> TabletKeyPair {
2711
4.23k
            if (recycle_tablet(tid, metrics_context) != 0) {
2712
1
                LOG_WARNING("failed to recycle tablet")
2713
1
                        .tag("instance_id", instance_id_)
2714
1
                        .tag("tablet_id", tid);
2715
1
                range_move = false;
2716
1
                return {std::string_view(), range_move};
2717
1
            }
2718
4.23k
            ++num_recycled;
2719
4.23k
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2720
4.23k
            return {k, range_move};
2721
4.23k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENUlvE_clEv
Line
Count
Source
2710
4.00k
                           &metrics_context, k]() mutable -> TabletKeyPair {
2711
4.00k
            if (recycle_tablet(tid, metrics_context) != 0) {
2712
0
                LOG_WARNING("failed to recycle tablet")
2713
0
                        .tag("instance_id", instance_id_)
2714
0
                        .tag("tablet_id", tid);
2715
0
                range_move = false;
2716
0
                return {std::string_view(), range_move};
2717
0
            }
2718
4.00k
            ++num_recycled;
2719
4.00k
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2720
4.00k
            return {k, range_move};
2721
4.00k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENUlvE_clEv
Line
Count
Source
2710
237
                           &metrics_context, k]() mutable -> TabletKeyPair {
2711
237
            if (recycle_tablet(tid, metrics_context) != 0) {
2712
1
                LOG_WARNING("failed to recycle tablet")
2713
1
                        .tag("instance_id", instance_id_)
2714
1
                        .tag("tablet_id", tid);
2715
1
                range_move = false;
2716
1
                return {std::string_view(), range_move};
2717
1
            }
2718
236
            ++num_recycled;
2719
236
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2720
236
            return {k, range_move};
2721
237
        });
2722
4.23k
        return 0;
2723
4.24k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
2681
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2682
8.00k
        bool use_range_remove = true;
2683
8.00k
        ++num_scanned;
2684
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
2685
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
2686
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
2687
0
            use_range_remove = false;
2688
0
            return -1;
2689
0
        }
2690
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
2691
2692
8.00k
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
2693
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
2694
4.00k
            return -1;
2695
4.00k
        }
2696
2697
4.00k
        tablet_idx_keys.push_back(meta_tablet_idx_key({instance_id_, tablet_id}));
2698
4.00k
        restore_job_keys.push_back(job_restore_tablet_key({instance_id_, tablet_id}));
2699
4.00k
        if (is_multi_version) {
2700
            // The tablet index/inverted index are recycled in recycle_versioned_tablet.
2701
0
            tablet_compact_stats_keys.push_back(
2702
0
                    versioned::tablet_compact_stats_key({instance_id_, tablet_id}));
2703
0
            tablet_load_stats_keys.push_back(
2704
0
                    versioned::tablet_load_stats_key({instance_id_, tablet_id}));
2705
0
            versioned_meta_tablet_keys.push_back(
2706
0
                    versioned::meta_tablet_key({instance_id_, tablet_id}));
2707
0
        }
2708
4.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
2709
4.00k
        sync_executor.add([this, &num_recycled, tid = tablet_id, range_move = use_range_remove,
2710
4.00k
                           &metrics_context, k]() mutable -> TabletKeyPair {
2711
4.00k
            if (recycle_tablet(tid, metrics_context) != 0) {
2712
4.00k
                LOG_WARNING("failed to recycle tablet")
2713
4.00k
                        .tag("instance_id", instance_id_)
2714
4.00k
                        .tag("tablet_id", tid);
2715
4.00k
                range_move = false;
2716
4.00k
                return {std::string_view(), range_move};
2717
4.00k
            }
2718
4.00k
            ++num_recycled;
2719
4.00k
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2720
4.00k
            return {k, range_move};
2721
4.00k
        });
2722
4.00k
        return 0;
2723
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
2681
240
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2682
240
        bool use_range_remove = true;
2683
240
        ++num_scanned;
2684
240
        doris::TabletMetaCloudPB tablet_meta_pb;
2685
240
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
2686
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
2687
0
            use_range_remove = false;
2688
0
            return -1;
2689
0
        }
2690
240
        int64_t tablet_id = tablet_meta_pb.tablet_id();
2691
2692
240
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
2693
0
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
2694
0
            return -1;
2695
0
        }
2696
2697
240
        tablet_idx_keys.push_back(meta_tablet_idx_key({instance_id_, tablet_id}));
2698
240
        restore_job_keys.push_back(job_restore_tablet_key({instance_id_, tablet_id}));
2699
240
        if (is_multi_version) {
2700
            // The tablet index/inverted index are recycled in recycle_versioned_tablet.
2701
6
            tablet_compact_stats_keys.push_back(
2702
6
                    versioned::tablet_compact_stats_key({instance_id_, tablet_id}));
2703
6
            tablet_load_stats_keys.push_back(
2704
6
                    versioned::tablet_load_stats_key({instance_id_, tablet_id}));
2705
6
            versioned_meta_tablet_keys.push_back(
2706
6
                    versioned::meta_tablet_key({instance_id_, tablet_id}));
2707
6
        }
2708
240
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
2709
237
        sync_executor.add([this, &num_recycled, tid = tablet_id, range_move = use_range_remove,
2710
237
                           &metrics_context, k]() mutable -> TabletKeyPair {
2711
237
            if (recycle_tablet(tid, metrics_context) != 0) {
2712
237
                LOG_WARNING("failed to recycle tablet")
2713
237
                        .tag("instance_id", instance_id_)
2714
237
                        .tag("tablet_id", tid);
2715
237
                range_move = false;
2716
237
                return {std::string_view(), range_move};
2717
237
            }
2718
237
            ++num_recycled;
2719
237
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2720
237
            return {k, range_move};
2721
237
        });
2722
237
        return 0;
2723
240
    };
2724
2725
    // TODO(AlexYue): Add one ut to cover use_range_remove = false
2726
49
    auto loop_done = [&, this]() -> int {
2727
49
        bool finished = true;
2728
49
        auto tablet_keys = sync_executor.when_all(&finished);
2729
49
        if (!finished) {
2730
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
2731
1
            return -1;
2732
1
        }
2733
48
        if (tablet_keys.empty() && tablet_idx_keys.empty()) return 0;
2734
46
        if (!tablet_keys.empty() &&
2735
46
            std::ranges::all_of(tablet_keys, [](const auto& k) { return k.first.empty(); })) {
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_E_clISt4pairISt17basic_string_viewIcSt11char_traitsIcEEbEEEDaS7_
Line
Count
Source
2735
2
            std::ranges::all_of(tablet_keys, [](const auto& k) { return k.first.empty(); })) {
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_E_clISt4pairISt17basic_string_viewIcSt11char_traitsIcEEbEEEDaS7_
Line
Count
Source
2735
42
            std::ranges::all_of(tablet_keys, [](const auto& k) { return k.first.empty(); })) {
2736
0
            return -1;
2737
0
        }
2738
        // sort the vector using key's order
2739
46
        std::sort(tablet_keys.begin(), tablet_keys.end(),
2740
49.4k
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_RKT0_E_clISt4pairISt17basic_string_viewIcSt11char_traitsIcEEbESI_EEDaS7_SA_
Line
Count
Source
2740
48.4k
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_RKT0_E_clISt4pairISt17basic_string_viewIcSt11char_traitsIcEEbESI_EEDaS7_SA_
Line
Count
Source
2740
944
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
2741
46
        bool use_range_remove = true;
2742
4.23k
        for (auto& [_, remove] : tablet_keys) {
2743
4.23k
            if (!remove) {
2744
0
                use_range_remove = remove;
2745
0
                break;
2746
0
            }
2747
4.23k
        }
2748
46
        DORIS_CLOUD_DEFER {
2749
46
            tablet_idx_keys.clear();
2750
46
            restore_job_keys.clear();
2751
46
            init_rs_keys.clear();
2752
46
            tablet_compact_stats_keys.clear();
2753
46
            tablet_load_stats_keys.clear();
2754
46
            versioned_meta_tablet_keys.clear();
2755
46
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2748
2
        DORIS_CLOUD_DEFER {
2749
2
            tablet_idx_keys.clear();
2750
2
            restore_job_keys.clear();
2751
2
            init_rs_keys.clear();
2752
2
            tablet_compact_stats_keys.clear();
2753
2
            tablet_load_stats_keys.clear();
2754
2
            versioned_meta_tablet_keys.clear();
2755
2
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2748
44
        DORIS_CLOUD_DEFER {
2749
44
            tablet_idx_keys.clear();
2750
44
            restore_job_keys.clear();
2751
44
            init_rs_keys.clear();
2752
44
            tablet_compact_stats_keys.clear();
2753
44
            tablet_load_stats_keys.clear();
2754
44
            versioned_meta_tablet_keys.clear();
2755
44
        };
2756
46
        std::unique_ptr<Transaction> txn;
2757
46
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2758
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
2759
0
            return -1;
2760
0
        }
2761
46
        std::string tablet_key_end;
2762
46
        if (!tablet_keys.empty()) {
2763
44
            if (use_range_remove) {
2764
44
                tablet_key_end = std::string(tablet_keys.back().first) + '\x00';
2765
44
                txn->remove(tablet_keys.front().first, tablet_key_end);
2766
44
            } else {
2767
0
                for (auto& [k, _] : tablet_keys) {
2768
0
                    txn->remove(k);
2769
0
                }
2770
0
            }
2771
44
        }
2772
46
        if (is_multi_version) {
2773
6
            for (auto& k : tablet_compact_stats_keys) {
2774
                // Remove all versions of tablet compact stats for recycled tablet
2775
6
                LOG_INFO("remove versioned tablet compact stats key")
2776
6
                        .tag("compact_stats_key", hex(k));
2777
6
                versioned_remove_all(txn.get(), k);
2778
6
            }
2779
6
            for (auto& k : tablet_load_stats_keys) {
2780
                // Remove all versions of tablet load stats for recycled tablet
2781
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
2782
6
                versioned_remove_all(txn.get(), k);
2783
6
            }
2784
6
            for (auto& k : versioned_meta_tablet_keys) {
2785
                // Remove all versions of meta tablet for recycled tablet
2786
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
2787
6
                versioned_remove_all(txn.get(), k);
2788
6
            }
2789
5
        }
2790
4.24k
        for (auto& k : tablet_idx_keys) {
2791
4.24k
            txn->remove(k);
2792
4.24k
        }
2793
4.24k
        for (auto& k : restore_job_keys) {
2794
4.24k
            txn->remove(k);
2795
4.24k
        }
2796
46
        for (auto& k : init_rs_keys) {
2797
0
            txn->remove(k);
2798
0
        }
2799
46
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
2800
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
2801
0
                         << ", err=" << err;
2802
0
            return -1;
2803
0
        }
2804
46
        return 0;
2805
46
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
2726
4
    auto loop_done = [&, this]() -> int {
2727
4
        bool finished = true;
2728
4
        auto tablet_keys = sync_executor.when_all(&finished);
2729
4
        if (!finished) {
2730
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
2731
0
            return -1;
2732
0
        }
2733
4
        if (tablet_keys.empty() && tablet_idx_keys.empty()) return 0;
2734
2
        if (!tablet_keys.empty() &&
2735
2
            std::ranges::all_of(tablet_keys, [](const auto& k) { return k.first.empty(); })) {
2736
0
            return -1;
2737
0
        }
2738
        // sort the vector using key's order
2739
2
        std::sort(tablet_keys.begin(), tablet_keys.end(),
2740
2
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
2741
2
        bool use_range_remove = true;
2742
4.00k
        for (auto& [_, remove] : tablet_keys) {
2743
4.00k
            if (!remove) {
2744
0
                use_range_remove = remove;
2745
0
                break;
2746
0
            }
2747
4.00k
        }
2748
2
        DORIS_CLOUD_DEFER {
2749
2
            tablet_idx_keys.clear();
2750
2
            restore_job_keys.clear();
2751
2
            init_rs_keys.clear();
2752
2
            tablet_compact_stats_keys.clear();
2753
2
            tablet_load_stats_keys.clear();
2754
2
            versioned_meta_tablet_keys.clear();
2755
2
        };
2756
2
        std::unique_ptr<Transaction> txn;
2757
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2758
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
2759
0
            return -1;
2760
0
        }
2761
2
        std::string tablet_key_end;
2762
2
        if (!tablet_keys.empty()) {
2763
2
            if (use_range_remove) {
2764
2
                tablet_key_end = std::string(tablet_keys.back().first) + '\x00';
2765
2
                txn->remove(tablet_keys.front().first, tablet_key_end);
2766
2
            } else {
2767
0
                for (auto& [k, _] : tablet_keys) {
2768
0
                    txn->remove(k);
2769
0
                }
2770
0
            }
2771
2
        }
2772
2
        if (is_multi_version) {
2773
0
            for (auto& k : tablet_compact_stats_keys) {
2774
                // Remove all versions of tablet compact stats for recycled tablet
2775
0
                LOG_INFO("remove versioned tablet compact stats key")
2776
0
                        .tag("compact_stats_key", hex(k));
2777
0
                versioned_remove_all(txn.get(), k);
2778
0
            }
2779
0
            for (auto& k : tablet_load_stats_keys) {
2780
                // Remove all versions of tablet load stats for recycled tablet
2781
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
2782
0
                versioned_remove_all(txn.get(), k);
2783
0
            }
2784
0
            for (auto& k : versioned_meta_tablet_keys) {
2785
                // Remove all versions of meta tablet for recycled tablet
2786
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
2787
0
                versioned_remove_all(txn.get(), k);
2788
0
            }
2789
0
        }
2790
4.00k
        for (auto& k : tablet_idx_keys) {
2791
4.00k
            txn->remove(k);
2792
4.00k
        }
2793
4.00k
        for (auto& k : restore_job_keys) {
2794
4.00k
            txn->remove(k);
2795
4.00k
        }
2796
2
        for (auto& k : init_rs_keys) {
2797
0
            txn->remove(k);
2798
0
        }
2799
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
2800
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
2801
0
                         << ", err=" << err;
2802
0
            return -1;
2803
0
        }
2804
2
        return 0;
2805
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
2726
45
    auto loop_done = [&, this]() -> int {
2727
45
        bool finished = true;
2728
45
        auto tablet_keys = sync_executor.when_all(&finished);
2729
45
        if (!finished) {
2730
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
2731
1
            return -1;
2732
1
        }
2733
44
        if (tablet_keys.empty() && tablet_idx_keys.empty()) return 0;
2734
44
        if (!tablet_keys.empty() &&
2735
44
            std::ranges::all_of(tablet_keys, [](const auto& k) { return k.first.empty(); })) {
2736
0
            return -1;
2737
0
        }
2738
        // sort the vector using key's order
2739
44
        std::sort(tablet_keys.begin(), tablet_keys.end(),
2740
44
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
2741
44
        bool use_range_remove = true;
2742
236
        for (auto& [_, remove] : tablet_keys) {
2743
236
            if (!remove) {
2744
0
                use_range_remove = remove;
2745
0
                break;
2746
0
            }
2747
236
        }
2748
44
        DORIS_CLOUD_DEFER {
2749
44
            tablet_idx_keys.clear();
2750
44
            restore_job_keys.clear();
2751
44
            init_rs_keys.clear();
2752
44
            tablet_compact_stats_keys.clear();
2753
44
            tablet_load_stats_keys.clear();
2754
44
            versioned_meta_tablet_keys.clear();
2755
44
        };
2756
44
        std::unique_ptr<Transaction> txn;
2757
44
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2758
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
2759
0
            return -1;
2760
0
        }
2761
44
        std::string tablet_key_end;
2762
44
        if (!tablet_keys.empty()) {
2763
42
            if (use_range_remove) {
2764
42
                tablet_key_end = std::string(tablet_keys.back().first) + '\x00';
2765
42
                txn->remove(tablet_keys.front().first, tablet_key_end);
2766
42
            } else {
2767
0
                for (auto& [k, _] : tablet_keys) {
2768
0
                    txn->remove(k);
2769
0
                }
2770
0
            }
2771
42
        }
2772
44
        if (is_multi_version) {
2773
6
            for (auto& k : tablet_compact_stats_keys) {
2774
                // Remove all versions of tablet compact stats for recycled tablet
2775
6
                LOG_INFO("remove versioned tablet compact stats key")
2776
6
                        .tag("compact_stats_key", hex(k));
2777
6
                versioned_remove_all(txn.get(), k);
2778
6
            }
2779
6
            for (auto& k : tablet_load_stats_keys) {
2780
                // Remove all versions of tablet load stats for recycled tablet
2781
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
2782
6
                versioned_remove_all(txn.get(), k);
2783
6
            }
2784
6
            for (auto& k : versioned_meta_tablet_keys) {
2785
                // Remove all versions of meta tablet for recycled tablet
2786
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
2787
6
                versioned_remove_all(txn.get(), k);
2788
6
            }
2789
5
        }
2790
239
        for (auto& k : tablet_idx_keys) {
2791
239
            txn->remove(k);
2792
239
        }
2793
239
        for (auto& k : restore_job_keys) {
2794
239
            txn->remove(k);
2795
239
        }
2796
44
        for (auto& k : init_rs_keys) {
2797
0
            txn->remove(k);
2798
0
        }
2799
44
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
2800
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
2801
0
                         << ", err=" << err;
2802
0
            return -1;
2803
0
        }
2804
44
        return 0;
2805
44
    };
2806
2807
49
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
2808
49
                               std::move(loop_done));
2809
49
    if (ret != 0) {
2810
3
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
2811
3
        return ret;
2812
3
    }
2813
2814
    // directly remove tablet stats and tablet jobs of these dropped index or partition
2815
46
    std::unique_ptr<Transaction> txn;
2816
46
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2817
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
2818
0
        return -1;
2819
0
    }
2820
46
    txn->remove(stats_key_begin, stats_key_end);
2821
46
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
2822
46
                 << " end=" << hex(stats_key_end);
2823
46
    txn->remove(job_key_begin, job_key_end);
2824
46
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
2825
46
    std::string schema_key_begin, schema_key_end;
2826
46
    std::string schema_dict_key;
2827
46
    std::string versioned_schema_key_begin, versioned_schema_key_end;
2828
46
    if (partition_id <= 0) {
2829
        // Delete schema kv of this index
2830
14
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
2831
14
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
2832
14
        txn->remove(schema_key_begin, schema_key_end);
2833
14
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
2834
14
                     << " end=" << hex(schema_key_end);
2835
14
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
2836
14
        txn->remove(schema_dict_key);
2837
14
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
2838
14
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
2839
14
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
2840
14
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
2841
14
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
2842
14
                     << " end=" << hex(versioned_schema_key_end);
2843
14
    }
2844
2845
46
    TxnErrorCode err = txn->commit();
2846
46
    if (err != TxnErrorCode::TXN_OK) {
2847
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
2848
0
                     << " err=" << err;
2849
0
        return -1;
2850
0
    }
2851
2852
46
    return ret;
2853
46
}
2854
2855
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
2856
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
2857
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
2858
5.61k
    if (num_segments <= 0) return 0;
2859
2860
5.61k
    std::vector<std::string> file_paths;
2861
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
2862
0
        return -1;
2863
0
    }
2864
2865
    // Process inverted indexes
2866
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
2867
    // default format as v1.
2868
5.61k
    InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
2869
5.61k
    bool delete_rowset_data_by_prefix = false;
2870
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
2871
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
2872
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
2873
0
        delete_rowset_data_by_prefix = true;
2874
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
2875
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
2876
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
2877
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
2878
10.0k
            }
2879
10.0k
        }
2880
4.80k
        if (rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
2881
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
2882
2.00k
        }
2883
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
2884
        // schema version and index id are not found, delete rowset data by prefix directly.
2885
0
        delete_rowset_data_by_prefix = true;
2886
809
    } else {
2887
        // otherwise, try to get schema kv
2888
809
        InvertedIndexInfo index_info;
2889
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
2890
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
2891
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
2892
809
                                 &inverted_index_get_ret);
2893
809
        if (inverted_index_get_ret == 0) {
2894
809
            index_format = index_info.first;
2895
809
            index_ids = index_info.second;
2896
809
        } else if (inverted_index_get_ret == 1) {
2897
            // 1. Schema kv not found means tablet has been recycled
2898
            // Maybe some tablet recycle failed by some bugs
2899
            // We need to delete again to double check
2900
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
2901
            // because we are uncertain about the inverted index information.
2902
            // If there are inverted indexes, some data might not be deleted,
2903
            // but this is acceptable as we have made our best effort to delete the data.
2904
0
            LOG_INFO(
2905
0
                    "delete rowset data schema kv not found, need to delete again to double "
2906
0
                    "check")
2907
0
                    .tag("instance_id", instance_id_)
2908
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
2909
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
2910
            // Currently index_ids is guaranteed to be empty,
2911
            // but we clear it again here as a safeguard against future code changes
2912
            // that might cause index_ids to no longer be empty
2913
0
            index_format = InvertedIndexStorageFormatPB::V2;
2914
0
            index_ids.clear();
2915
0
        } else {
2916
            // failed to get schema kv, delete rowset data by prefix directly.
2917
0
            delete_rowset_data_by_prefix = true;
2918
0
        }
2919
809
    }
2920
2921
5.61k
    if (delete_rowset_data_by_prefix) {
2922
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
2923
0
                                  rs_meta_pb.rowset_id_v2());
2924
0
    }
2925
2926
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
2927
5.61k
    if (it == accessor_map_.end()) {
2928
1.59k
        LOG_WARNING("instance has no such resource id")
2929
1.59k
                .tag("instance_id", instance_id_)
2930
1.59k
                .tag("resource_id", rs_meta_pb.resource_id());
2931
1.59k
        return -1;
2932
1.59k
    }
2933
4.01k
    auto& accessor = it->second;
2934
2935
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
2936
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
2937
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
2938
20.0k
        file_paths.push_back(segment_path(tablet_id, rowset_id, i));
2939
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
2940
40.0k
            for (const auto& index_id : index_ids) {
2941
40.0k
                file_paths.push_back(inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
2942
40.0k
                                                            index_id.second));
2943
40.0k
            }
2944
20.0k
        } else if (!index_ids.empty()) {
2945
0
            file_paths.push_back(inverted_index_path_v2(tablet_id, rowset_id, i));
2946
0
        }
2947
20.0k
    }
2948
2949
    // Process delete bitmap - check if it's stored in packed file
2950
4.01k
    bool delete_bitmap_is_packed = false;
2951
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
2952
4.01k
                                                       &delete_bitmap_is_packed) != 0) {
2953
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
2954
0
                .tag("instance_id", instance_id_)
2955
0
                .tag("tablet_id", tablet_id)
2956
0
                .tag("rowset_id", rowset_id);
2957
0
        return -1;
2958
0
    }
2959
    // Only delete standalone delete bitmap file if not stored in packed file
2960
4.01k
    if (!delete_bitmap_is_packed) {
2961
4.01k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
2962
4.01k
    }
2963
    // TODO(AlexYue): seems could do do batch
2964
4.01k
    return accessor->delete_files(file_paths);
2965
4.01k
}
2966
2967
62.3k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
2968
62.3k
    LOG_INFO("begin process_packed_file_location_index")
2969
62.3k
            .tag("instance_id", instance_id_)
2970
62.3k
            .tag("tablet_id", rs_meta_pb.tablet_id())
2971
62.3k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
2972
62.3k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
2973
62.3k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
2974
62.3k
    if (index_map.empty()) {
2975
62.3k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
2976
62.3k
                .tag("instance_id", instance_id_)
2977
62.3k
                .tag("tablet_id", rs_meta_pb.tablet_id())
2978
62.3k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
2979
62.3k
        return 0;
2980
62.3k
    }
2981
2982
16
    struct PackedSmallFileInfo {
2983
16
        std::string small_file_path;
2984
16
    };
2985
16
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
2986
16
    packed_file_updates.reserve(index_map.size());
2987
27
    for (const auto& [small_path, index_pb] : index_map) {
2988
27
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
2989
0
            continue;
2990
0
        }
2991
27
        packed_file_updates[index_pb.packed_file_path()].push_back(
2992
27
                PackedSmallFileInfo {small_path});
2993
27
    }
2994
16
    if (packed_file_updates.empty()) {
2995
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
2996
0
                .tag("instance_id", instance_id_)
2997
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
2998
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
2999
0
                .tag("index_map_size", index_map.size());
3000
0
        return 0;
3001
0
    }
3002
3003
16
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3004
16
    int ret = 0;
3005
24
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3006
24
        if (small_files.empty()) {
3007
0
            continue;
3008
0
        }
3009
3010
24
        bool success = false;
3011
24
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3012
24
            std::unique_ptr<Transaction> txn;
3013
24
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3014
24
            if (err != TxnErrorCode::TXN_OK) {
3015
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3016
0
                        .tag("instance_id", instance_id_)
3017
0
                        .tag("packed_file_path", packed_file_path)
3018
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3019
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3020
0
                        .tag("err", err);
3021
0
                ret = -1;
3022
0
                break;
3023
0
            }
3024
3025
24
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3026
24
            std::string packed_val;
3027
24
            err = txn->get(packed_key, &packed_val);
3028
24
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3029
0
                LOG_WARNING("packed file info not found when recycling rowset")
3030
0
                        .tag("instance_id", instance_id_)
3031
0
                        .tag("packed_file_path", packed_file_path)
3032
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3033
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3034
0
                        .tag("key", hex(packed_key))
3035
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3036
                // Skip this packed file entry and continue with others
3037
0
                success = true;
3038
0
                break;
3039
0
            }
3040
24
            if (err != TxnErrorCode::TXN_OK) {
3041
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
3042
0
                        .tag("instance_id", instance_id_)
3043
0
                        .tag("packed_file_path", packed_file_path)
3044
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3045
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3046
0
                        .tag("err", err);
3047
0
                ret = -1;
3048
0
                break;
3049
0
            }
3050
3051
24
            cloud::PackedFileInfoPB packed_info;
3052
24
            if (!packed_info.ParseFromString(packed_val)) {
3053
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
3054
0
                        .tag("instance_id", instance_id_)
3055
0
                        .tag("packed_file_path", packed_file_path)
3056
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3057
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3058
0
                ret = -1;
3059
0
                break;
3060
0
            }
3061
3062
24
            LOG_INFO("packed file update check")
3063
24
                    .tag("instance_id", instance_id_)
3064
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3065
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3066
24
                    .tag("merged_file_path", packed_file_path)
3067
24
                    .tag("requested_small_files", small_files.size())
3068
24
                    .tag("merge_entries", packed_info.slices_size());
3069
3070
24
            auto* small_file_entries = packed_info.mutable_slices();
3071
24
            int64_t changed_files = 0;
3072
24
            int64_t missing_entries = 0;
3073
24
            int64_t already_deleted = 0;
3074
27
            for (const auto& small_file_info : small_files) {
3075
27
                bool found = false;
3076
87
                for (auto& small_file_entry : *small_file_entries) {
3077
87
                    if (small_file_entry.path() == small_file_info.small_file_path) {
3078
27
                        if (!small_file_entry.deleted()) {
3079
27
                            small_file_entry.set_deleted(true);
3080
27
                            if (!small_file_entry.corrected()) {
3081
27
                                small_file_entry.set_corrected(true);
3082
27
                            }
3083
27
                            ++changed_files;
3084
27
                        } else {
3085
0
                            ++already_deleted;
3086
0
                        }
3087
27
                        found = true;
3088
27
                        break;
3089
27
                    }
3090
87
                }
3091
27
                if (!found) {
3092
0
                    ++missing_entries;
3093
0
                    LOG_WARNING("packed file info missing small file entry")
3094
0
                            .tag("instance_id", instance_id_)
3095
0
                            .tag("packed_file_path", packed_file_path)
3096
0
                            .tag("small_file_path", small_file_info.small_file_path)
3097
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3098
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
3099
0
                }
3100
27
            }
3101
3102
24
            if (changed_files == 0) {
3103
0
                LOG_INFO("skip merge file update: no merge entries changed")
3104
0
                        .tag("instance_id", instance_id_)
3105
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3106
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3107
0
                        .tag("merged_file_path", packed_file_path)
3108
0
                        .tag("missing_entries", missing_entries)
3109
0
                        .tag("already_deleted", already_deleted)
3110
0
                        .tag("requested_small_files", small_files.size())
3111
0
                        .tag("merge_entries", packed_info.slices_size());
3112
0
                success = true;
3113
0
                break;
3114
0
            }
3115
3116
            // Calculate remaining files
3117
24
            int64_t left_file_count = 0;
3118
24
            int64_t left_file_bytes = 0;
3119
141
            for (const auto& small_file_entry : packed_info.slices()) {
3120
141
                if (!small_file_entry.deleted()) {
3121
57
                    ++left_file_count;
3122
57
                    left_file_bytes += small_file_entry.size();
3123
57
                }
3124
141
            }
3125
24
            packed_info.set_remaining_slice_bytes(left_file_bytes);
3126
24
            packed_info.set_ref_cnt(left_file_count);
3127
24
            LOG_INFO("updated packed file reference info")
3128
24
                    .tag("instance_id", instance_id_)
3129
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3130
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3131
24
                    .tag("packed_file_path", packed_file_path)
3132
24
                    .tag("ref_cnt", left_file_count)
3133
24
                    .tag("left_file_bytes", left_file_bytes);
3134
3135
24
            if (left_file_count == 0) {
3136
7
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3137
7
            }
3138
3139
24
            std::string updated_val;
3140
24
            if (!packed_info.SerializeToString(&updated_val)) {
3141
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
3142
0
                        .tag("instance_id", instance_id_)
3143
0
                        .tag("packed_file_path", packed_file_path)
3144
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3145
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3146
0
                ret = -1;
3147
0
                break;
3148
0
            }
3149
3150
24
            txn->put(packed_key, updated_val);
3151
24
            err = txn->commit();
3152
24
            if (err == TxnErrorCode::TXN_OK) {
3153
24
                success = true;
3154
24
                if (left_file_count == 0) {
3155
7
                    LOG_INFO("packed file ready to delete, deleting immediately")
3156
7
                            .tag("instance_id", instance_id_)
3157
7
                            .tag("packed_file_path", packed_file_path);
3158
7
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3159
0
                        ret = -1;
3160
0
                    }
3161
7
                }
3162
24
                break;
3163
24
            }
3164
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
3165
0
                if (attempt >= max_retry_times) {
3166
0
                    LOG_WARNING("packed file info update conflict after max retry")
3167
0
                            .tag("instance_id", instance_id_)
3168
0
                            .tag("packed_file_path", packed_file_path)
3169
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3170
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
3171
0
                            .tag("changed_files", changed_files)
3172
0
                            .tag("attempt", attempt);
3173
0
                    ret = -1;
3174
0
                    break;
3175
0
                }
3176
0
                LOG_WARNING("packed file info update conflict, retrying")
3177
0
                        .tag("instance_id", instance_id_)
3178
0
                        .tag("packed_file_path", packed_file_path)
3179
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3180
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3181
0
                        .tag("changed_files", changed_files)
3182
0
                        .tag("attempt", attempt);
3183
0
                sleep_for_packed_file_retry();
3184
0
                continue;
3185
0
            }
3186
3187
0
            LOG_WARNING("failed to commit packed file info update")
3188
0
                    .tag("instance_id", instance_id_)
3189
0
                    .tag("packed_file_path", packed_file_path)
3190
0
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3191
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3192
0
                    .tag("err", err)
3193
0
                    .tag("changed_files", changed_files);
3194
0
            ret = -1;
3195
0
            break;
3196
0
        }
3197
3198
24
        if (!success) {
3199
0
            ret = -1;
3200
0
        }
3201
24
    }
3202
3203
16
    return ret;
3204
16
}
3205
3206
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(int64_t tablet_id,
3207
                                                                     const std::string& rowset_id,
3208
58.2k
                                                                     bool* out_is_packed) {
3209
58.2k
    if (out_is_packed) {
3210
58.2k
        *out_is_packed = false;
3211
58.2k
    }
3212
3213
    // Get delete bitmap storage info from FDB
3214
58.2k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
3215
58.2k
    std::unique_ptr<Transaction> txn;
3216
58.2k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
3217
58.2k
    if (err != TxnErrorCode::TXN_OK) {
3218
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
3219
0
                .tag("instance_id", instance_id_)
3220
0
                .tag("tablet_id", tablet_id)
3221
0
                .tag("rowset_id", rowset_id)
3222
0
                .tag("err", err);
3223
0
        return -1;
3224
0
    }
3225
3226
58.2k
    std::string dbm_val;
3227
58.2k
    err = txn->get(dbm_key, &dbm_val);
3228
58.2k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3229
        // No delete bitmap for this rowset, nothing to do
3230
4.63k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
3231
4.63k
                .tag("instance_id", instance_id_)
3232
4.63k
                .tag("tablet_id", tablet_id)
3233
4.63k
                .tag("rowset_id", rowset_id);
3234
4.63k
        return 0;
3235
4.63k
    }
3236
53.5k
    if (err != TxnErrorCode::TXN_OK) {
3237
0
        LOG_WARNING("failed to get delete bitmap storage")
3238
0
                .tag("instance_id", instance_id_)
3239
0
                .tag("tablet_id", tablet_id)
3240
0
                .tag("rowset_id", rowset_id)
3241
0
                .tag("err", err);
3242
0
        return -1;
3243
0
    }
3244
3245
53.5k
    DeleteBitmapStoragePB storage;
3246
53.5k
    if (!storage.ParseFromString(dbm_val)) {
3247
0
        LOG_WARNING("failed to parse delete bitmap storage")
3248
0
                .tag("instance_id", instance_id_)
3249
0
                .tag("tablet_id", tablet_id)
3250
0
                .tag("rowset_id", rowset_id);
3251
0
        return -1;
3252
0
    }
3253
3254
    // Check if delete bitmap is stored in packed file
3255
53.5k
    if (!storage.has_packed_slice_location() ||
3256
53.5k
        storage.packed_slice_location().packed_file_path().empty()) {
3257
        // Not stored in packed file, nothing to do
3258
53.5k
        return 0;
3259
53.5k
    }
3260
3261
0
    if (out_is_packed) {
3262
0
        *out_is_packed = true;
3263
0
    }
3264
3265
0
    const auto& packed_loc = storage.packed_slice_location();
3266
0
    const std::string& packed_file_path = packed_loc.packed_file_path();
3267
3268
0
    LOG_INFO("decrementing delete bitmap packed file ref count")
3269
0
            .tag("instance_id", instance_id_)
3270
0
            .tag("tablet_id", tablet_id)
3271
0
            .tag("rowset_id", rowset_id)
3272
0
            .tag("packed_file_path", packed_file_path);
3273
3274
0
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3275
0
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3276
0
        std::unique_ptr<Transaction> update_txn;
3277
0
        err = txn_kv_->create_txn(&update_txn);
3278
0
        if (err != TxnErrorCode::TXN_OK) {
3279
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
3280
0
                    .tag("instance_id", instance_id_)
3281
0
                    .tag("tablet_id", tablet_id)
3282
0
                    .tag("rowset_id", rowset_id)
3283
0
                    .tag("err", err);
3284
0
            return -1;
3285
0
        }
3286
3287
0
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3288
0
        std::string packed_val;
3289
0
        err = update_txn->get(packed_key, &packed_val);
3290
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3291
0
            LOG_WARNING("packed file info not found for delete bitmap")
3292
0
                    .tag("instance_id", instance_id_)
3293
0
                    .tag("tablet_id", tablet_id)
3294
0
                    .tag("rowset_id", rowset_id)
3295
0
                    .tag("packed_file_path", packed_file_path);
3296
0
            return 0;
3297
0
        }
3298
0
        if (err != TxnErrorCode::TXN_OK) {
3299
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
3300
0
                    .tag("instance_id", instance_id_)
3301
0
                    .tag("tablet_id", tablet_id)
3302
0
                    .tag("rowset_id", rowset_id)
3303
0
                    .tag("packed_file_path", packed_file_path)
3304
0
                    .tag("err", err);
3305
0
            return -1;
3306
0
        }
3307
3308
0
        cloud::PackedFileInfoPB packed_info;
3309
0
        if (!packed_info.ParseFromString(packed_val)) {
3310
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
3311
0
                    .tag("instance_id", instance_id_)
3312
0
                    .tag("tablet_id", tablet_id)
3313
0
                    .tag("rowset_id", rowset_id)
3314
0
                    .tag("packed_file_path", packed_file_path);
3315
0
            return -1;
3316
0
        }
3317
3318
        // Find and mark the small file entry as deleted
3319
        // Use tablet_id and rowset_id to match entry instead of path,
3320
        // because path format may vary with path_version (with or without shard prefix)
3321
0
        auto* entries = packed_info.mutable_slices();
3322
0
        bool found = false;
3323
0
        bool already_deleted = false;
3324
0
        for (auto& entry : *entries) {
3325
0
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
3326
0
                if (!entry.deleted()) {
3327
0
                    entry.set_deleted(true);
3328
0
                    if (!entry.corrected()) {
3329
0
                        entry.set_corrected(true);
3330
0
                    }
3331
0
                } else {
3332
0
                    already_deleted = true;
3333
0
                }
3334
0
                found = true;
3335
0
                break;
3336
0
            }
3337
0
        }
3338
3339
0
        if (!found) {
3340
0
            LOG_WARNING("delete bitmap entry not found in packed file")
3341
0
                    .tag("instance_id", instance_id_)
3342
0
                    .tag("tablet_id", tablet_id)
3343
0
                    .tag("rowset_id", rowset_id)
3344
0
                    .tag("packed_file_path", packed_file_path);
3345
0
            return 0;
3346
0
        }
3347
3348
0
        if (already_deleted) {
3349
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
3350
0
                    .tag("instance_id", instance_id_)
3351
0
                    .tag("tablet_id", tablet_id)
3352
0
                    .tag("rowset_id", rowset_id)
3353
0
                    .tag("packed_file_path", packed_file_path);
3354
0
            return 0;
3355
0
        }
3356
3357
        // Calculate remaining files
3358
0
        int64_t left_file_count = 0;
3359
0
        int64_t left_file_bytes = 0;
3360
0
        for (const auto& entry : packed_info.slices()) {
3361
0
            if (!entry.deleted()) {
3362
0
                ++left_file_count;
3363
0
                left_file_bytes += entry.size();
3364
0
            }
3365
0
        }
3366
0
        packed_info.set_remaining_slice_bytes(left_file_bytes);
3367
0
        packed_info.set_ref_cnt(left_file_count);
3368
3369
0
        if (left_file_count == 0) {
3370
0
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3371
0
        }
3372
3373
0
        std::string updated_val;
3374
0
        if (!packed_info.SerializeToString(&updated_val)) {
3375
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
3376
0
                    .tag("instance_id", instance_id_)
3377
0
                    .tag("tablet_id", tablet_id)
3378
0
                    .tag("rowset_id", rowset_id)
3379
0
                    .tag("packed_file_path", packed_file_path);
3380
0
            return -1;
3381
0
        }
3382
3383
0
        update_txn->put(packed_key, updated_val);
3384
0
        err = update_txn->commit();
3385
0
        if (err == TxnErrorCode::TXN_OK) {
3386
0
            LOG_INFO("delete bitmap packed file ref count decremented")
3387
0
                    .tag("instance_id", instance_id_)
3388
0
                    .tag("tablet_id", tablet_id)
3389
0
                    .tag("rowset_id", rowset_id)
3390
0
                    .tag("packed_file_path", packed_file_path)
3391
0
                    .tag("left_file_count", left_file_count);
3392
0
            if (left_file_count == 0) {
3393
0
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3394
0
                    return -1;
3395
0
                }
3396
0
            }
3397
0
            return 0;
3398
0
        }
3399
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
3400
0
            if (attempt >= max_retry_times) {
3401
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
3402
0
                        .tag("instance_id", instance_id_)
3403
0
                        .tag("tablet_id", tablet_id)
3404
0
                        .tag("rowset_id", rowset_id)
3405
0
                        .tag("packed_file_path", packed_file_path)
3406
0
                        .tag("attempt", attempt);
3407
0
                return -1;
3408
0
            }
3409
0
            sleep_for_packed_file_retry();
3410
0
            continue;
3411
0
        }
3412
3413
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
3414
0
                .tag("instance_id", instance_id_)
3415
0
                .tag("tablet_id", tablet_id)
3416
0
                .tag("rowset_id", rowset_id)
3417
0
                .tag("packed_file_path", packed_file_path)
3418
0
                .tag("err", err);
3419
0
        return -1;
3420
0
    }
3421
3422
0
    return -1;
3423
0
}
3424
3425
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
3426
                                                const std::string& packed_key,
3427
7
                                                const cloud::PackedFileInfoPB& packed_info) {
3428
7
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
3429
0
        LOG_WARNING("packed file missing resource id when recycling")
3430
0
                .tag("instance_id", instance_id_)
3431
0
                .tag("packed_file_path", packed_file_path);
3432
0
        return -1;
3433
0
    }
3434
3435
7
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
3436
7
    if (!accessor) {
3437
0
        LOG_WARNING("no accessor available to delete packed file")
3438
0
                .tag("instance_id", instance_id_)
3439
0
                .tag("packed_file_path", packed_file_path)
3440
0
                .tag("resource_id", packed_info.resource_id());
3441
0
        return -1;
3442
0
    }
3443
3444
7
    int del_ret = accessor->delete_file(packed_file_path);
3445
7
    if (del_ret != 0 && del_ret != 1) {
3446
0
        LOG_WARNING("failed to delete packed file")
3447
0
                .tag("instance_id", instance_id_)
3448
0
                .tag("packed_file_path", packed_file_path)
3449
0
                .tag("resource_id", resource_id)
3450
0
                .tag("ret", del_ret);
3451
0
        return -1;
3452
0
    }
3453
7
    if (del_ret == 1) {
3454
0
        LOG_INFO("packed file already removed")
3455
0
                .tag("instance_id", instance_id_)
3456
0
                .tag("packed_file_path", packed_file_path)
3457
0
                .tag("resource_id", resource_id);
3458
7
    } else {
3459
7
        LOG_INFO("deleted packed file")
3460
7
                .tag("instance_id", instance_id_)
3461
7
                .tag("packed_file_path", packed_file_path)
3462
7
                .tag("resource_id", resource_id);
3463
7
    }
3464
3465
7
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
3466
7
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3467
7
        std::unique_ptr<Transaction> del_txn;
3468
7
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
3469
7
        if (err != TxnErrorCode::TXN_OK) {
3470
0
            LOG_WARNING("failed to create txn when removing packed file kv")
3471
0
                    .tag("instance_id", instance_id_)
3472
0
                    .tag("packed_file_path", packed_file_path)
3473
0
                    .tag("attempt", attempt)
3474
0
                    .tag("err", err);
3475
0
            return -1;
3476
0
        }
3477
3478
7
        std::string latest_val;
3479
7
        err = del_txn->get(packed_key, &latest_val);
3480
7
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3481
0
            return 0;
3482
0
        }
3483
7
        if (err != TxnErrorCode::TXN_OK) {
3484
0
            LOG_WARNING("failed to re-read packed file kv before removal")
3485
0
                    .tag("instance_id", instance_id_)
3486
0
                    .tag("packed_file_path", packed_file_path)
3487
0
                    .tag("attempt", attempt)
3488
0
                    .tag("err", err);
3489
0
            return -1;
3490
0
        }
3491
3492
7
        cloud::PackedFileInfoPB latest_info;
3493
7
        if (!latest_info.ParseFromString(latest_val)) {
3494
0
            LOG_WARNING("failed to parse packed file info before removal")
3495
0
                    .tag("instance_id", instance_id_)
3496
0
                    .tag("packed_file_path", packed_file_path)
3497
0
                    .tag("attempt", attempt);
3498
0
            return -1;
3499
0
        }
3500
3501
7
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
3502
7
              latest_info.ref_cnt() == 0)) {
3503
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
3504
0
                    .tag("instance_id", instance_id_)
3505
0
                    .tag("packed_file_path", packed_file_path)
3506
0
                    .tag("attempt", attempt);
3507
0
            return 0;
3508
0
        }
3509
3510
7
        del_txn->remove(packed_key);
3511
7
        err = del_txn->commit();
3512
7
        if (err == TxnErrorCode::TXN_OK) {
3513
7
            LOG_INFO("removed packed file metadata")
3514
7
                    .tag("instance_id", instance_id_)
3515
7
                    .tag("packed_file_path", packed_file_path);
3516
7
            return 0;
3517
7
        }
3518
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
3519
0
            if (attempt >= max_retry_times) {
3520
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
3521
0
                        .tag("instance_id", instance_id_)
3522
0
                        .tag("packed_file_path", packed_file_path)
3523
0
                        .tag("attempt", attempt);
3524
0
                return -1;
3525
0
            }
3526
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
3527
0
                    .tag("instance_id", instance_id_)
3528
0
                    .tag("packed_file_path", packed_file_path)
3529
0
                    .tag("attempt", attempt);
3530
0
            sleep_for_packed_file_retry();
3531
0
            continue;
3532
0
        }
3533
0
        LOG_WARNING("failed to remove packed file kv")
3534
0
                .tag("instance_id", instance_id_)
3535
0
                .tag("packed_file_path", packed_file_path)
3536
0
                .tag("attempt", attempt)
3537
0
                .tag("err", err);
3538
0
        return -1;
3539
0
    }
3540
0
    return -1;
3541
7
}
3542
3543
int InstanceRecycler::delete_rowset_data(
3544
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
3545
92
        RecyclerMetricsContext& metrics_context) {
3546
92
    int ret = 0;
3547
    // resource_id -> file_paths
3548
92
    std::map<std::string, std::vector<std::string>> resource_file_paths;
3549
    // (resource_id, tablet_id, rowset_id)
3550
92
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
3551
92
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
3552
3553
54.1k
    for (const auto& [_, rs] : rowsets) {
3554
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
3555
        // due to aborted schema change.
3556
54.1k
        if (is_formal_rowset) {
3557
3.16k
            std::lock_guard lock(recycled_tablets_mtx_);
3558
3.16k
            if (recycled_tablets_.count(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
3559
                // Tablet has been recycled and this rowset has no packed slices, so file data
3560
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
3561
                // slice info must still run to decrement packed file ref counts.
3562
0
                continue;
3563
0
            }
3564
3.16k
        }
3565
3566
54.1k
        auto it = accessor_map_.find(rs.resource_id());
3567
        // possible if the accessor is not initilized correctly
3568
54.1k
        if (it == accessor_map_.end()) [[unlikely]] {
3569
1
            LOG_WARNING("instance has no such resource id")
3570
1
                    .tag("instance_id", instance_id_)
3571
1
                    .tag("resource_id", rs.resource_id());
3572
1
            ret = -1;
3573
1
            continue;
3574
1
        }
3575
3576
54.1k
        auto& file_paths = resource_file_paths[rs.resource_id()];
3577
54.1k
        const auto& rowset_id = rs.rowset_id_v2();
3578
54.1k
        int64_t tablet_id = rs.tablet_id();
3579
54.1k
        LOG_INFO("recycle rowset merge index size")
3580
54.1k
                .tag("instance_id", instance_id_)
3581
54.1k
                .tag("tablet_id", tablet_id)
3582
54.1k
                .tag("rowset_id", rowset_id)
3583
54.1k
                .tag("merge_index_size", rs.packed_slice_locations_size());
3584
54.1k
        if (decrement_packed_file_ref_counts(rs) != 0) {
3585
0
            ret = -1;
3586
0
            continue;
3587
0
        }
3588
54.1k
        int64_t num_segments = rs.num_segments();
3589
54.1k
        if (num_segments <= 0) {
3590
0
            metrics_context.total_recycled_num++;
3591
0
            metrics_context.total_recycled_data_size += rs.total_disk_size();
3592
0
            continue;
3593
0
        }
3594
3595
        // Process delete bitmap - check if it's stored in packed file
3596
54.1k
        bool delete_bitmap_is_packed = false;
3597
54.1k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3598
54.1k
                                                           &delete_bitmap_is_packed) != 0) {
3599
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3600
0
                    .tag("instance_id", instance_id_)
3601
0
                    .tag("tablet_id", tablet_id)
3602
0
                    .tag("rowset_id", rowset_id);
3603
0
            ret = -1;
3604
0
            continue;
3605
0
        }
3606
        // Only delete standalone delete bitmap file if not stored in packed file
3607
54.2k
        if (!delete_bitmap_is_packed) {
3608
54.2k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3609
54.2k
        }
3610
3611
        // Process inverted indexes
3612
54.1k
        std::vector<std::pair<int64_t, std::string>> index_ids;
3613
        // default format as v1.
3614
54.1k
        InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
3615
54.1k
        int inverted_index_get_ret = 0;
3616
54.1k
        if (rs.has_tablet_schema()) {
3617
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
3618
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3619
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3620
53.5k
                }
3621
53.5k
            }
3622
26.6k
            if (rs.tablet_schema().has_inverted_index_storage_format()) {
3623
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
3624
26.5k
            }
3625
27.5k
        } else {
3626
27.5k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
3627
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
3628
0
                                "instance_id="
3629
0
                             << instance_id_ << " tablet_id=" << tablet_id
3630
0
                             << " rowset_id=" << rowset_id;
3631
0
                ret = -1;
3632
0
                continue;
3633
0
            }
3634
27.5k
            InvertedIndexInfo index_info;
3635
27.5k
            inverted_index_get_ret =
3636
27.5k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
3637
27.5k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3638
27.5k
                                     &inverted_index_get_ret);
3639
27.5k
            if (inverted_index_get_ret == 0) {
3640
27.0k
                index_format = index_info.first;
3641
27.0k
                index_ids = index_info.second;
3642
27.0k
            } else if (inverted_index_get_ret == 1) {
3643
                // 1. Schema kv not found means tablet has been recycled
3644
                // Maybe some tablet recycle failed by some bugs
3645
                // We need to delete again to double check
3646
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3647
                // because we are uncertain about the inverted index information.
3648
                // If there are inverted indexes, some data might not be deleted,
3649
                // but this is acceptable as we have made our best effort to delete the data.
3650
503
                LOG_INFO(
3651
503
                        "delete rowset data schema kv not found, need to delete again to "
3652
503
                        "double "
3653
503
                        "check")
3654
503
                        .tag("instance_id", instance_id_)
3655
503
                        .tag("tablet_id", tablet_id)
3656
503
                        .tag("rowset", rs.ShortDebugString());
3657
                // Currently index_ids is guaranteed to be empty,
3658
                // but we clear it again here as a safeguard against future code changes
3659
                // that might cause index_ids to no longer be empty
3660
503
                index_format = InvertedIndexStorageFormatPB::V2;
3661
503
                index_ids.clear();
3662
18.4E
            } else {
3663
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
3664
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
3665
18.4E
                ret = -1;
3666
18.4E
                continue;
3667
18.4E
            }
3668
27.5k
        }
3669
54.2k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3670
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3671
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3672
5
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
3673
5
            continue;
3674
5
        }
3675
323k
        for (int64_t i = 0; i < num_segments; ++i) {
3676
269k
            file_paths.push_back(segment_path(tablet_id, rowset_id, i));
3677
269k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
3678
535k
                for (const auto& index_id : index_ids) {
3679
535k
                    file_paths.push_back(inverted_index_path_v1(tablet_id, rowset_id, i,
3680
535k
                                                                index_id.first, index_id.second));
3681
535k
                }
3682
267k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
3683
                // try to recycle inverted index v2 when get_ret == 1
3684
                // we treat schema not found as if it has a v2 format inverted index
3685
                // to reduce chance of data leakage
3686
2.50k
                if (inverted_index_get_ret == 1) {
3687
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
3688
2.50k
                            .tag("instance_id", instance_id_)
3689
2.50k
                            .tag("inverted index v2 path",
3690
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, i));
3691
2.50k
                }
3692
2.50k
                file_paths.push_back(inverted_index_path_v2(tablet_id, rowset_id, i));
3693
2.50k
            }
3694
269k
        }
3695
54.1k
    }
3696
3697
92
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
3698
92
                                                 "delete_rowset_data",
3699
92
                                                 [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clERKi
Line
Count
Source
3699
5
                                                 [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clERKi
Line
Count
Source
3699
50
                                                 [](const int& ret) { return ret != 0; });
3700
92
    for (auto& [resource_id, file_paths] : resource_file_paths) {
3701
50
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
3702
50
            DCHECK(accessor_map_.count(*rid))
3703
0
                    << "uninitilized accessor, instance_id=" << instance_id_
3704
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
3705
50
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
3706
50
                                     &accessor_map_);
3707
50
            if (!accessor_map_.contains(*rid)) {
3708
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
3709
0
                        .tag("resource_id", resource_id)
3710
0
                        .tag("instance_id", instance_id_);
3711
0
                return -1;
3712
0
            }
3713
50
            auto& accessor = accessor_map_[*rid];
3714
50
            int ret = accessor->delete_files(*paths);
3715
50
            if (!ret) {
3716
                // deduplication of different files with the same rowset id
3717
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
3718
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
3719
50
                std::set<std::string> deleted_rowset_id;
3720
3721
50
                std::for_each(paths->begin(), paths->end(),
3722
50
                              [&metrics_context, &rowsets, &deleted_rowset_id,
3723
861k
                               this](const std::string& path) {
3724
861k
                                  std::vector<std::string> str;
3725
861k
                                  butil::SplitString(path, '/', &str);
3726
861k
                                  std::string rowset_id;
3727
861k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3728
857k
                                      rowset_id = str.back().substr(0, pos);
3729
857k
                                  } else {
3730
4.18k
                                      if (path.find("packed_file/") != std::string::npos) {
3731
0
                                          return; // packed files do not have rowset_id encoded
3732
0
                                      }
3733
4.18k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3734
4.18k
                                      return;
3735
4.18k
                                  }
3736
857k
                                  auto rs_meta = rowsets.find(rowset_id);
3737
857k
                                  if (rs_meta != rowsets.end() &&
3738
861k
                                      !deleted_rowset_id.contains(rowset_id)) {
3739
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
3740
54.1k
                                      metrics_context.total_recycled_data_size +=
3741
54.1k
                                              rs_meta->second.total_disk_size();
3742
54.1k
                                      segment_metrics_context_.total_recycled_num +=
3743
54.1k
                                              rs_meta->second.num_segments();
3744
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
3745
54.1k
                                              rs_meta->second.total_disk_size();
3746
54.1k
                                      metrics_context.total_recycled_num++;
3747
54.1k
                                  }
3748
857k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
3723
14
                               this](const std::string& path) {
3724
14
                                  std::vector<std::string> str;
3725
14
                                  butil::SplitString(path, '/', &str);
3726
14
                                  std::string rowset_id;
3727
14
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3728
14
                                      rowset_id = str.back().substr(0, pos);
3729
14
                                  } else {
3730
0
                                      if (path.find("packed_file/") != std::string::npos) {
3731
0
                                          return; // packed files do not have rowset_id encoded
3732
0
                                      }
3733
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3734
0
                                      return;
3735
0
                                  }
3736
14
                                  auto rs_meta = rowsets.find(rowset_id);
3737
14
                                  if (rs_meta != rowsets.end() &&
3738
14
                                      !deleted_rowset_id.contains(rowset_id)) {
3739
7
                                      deleted_rowset_id.emplace(rowset_id);
3740
7
                                      metrics_context.total_recycled_data_size +=
3741
7
                                              rs_meta->second.total_disk_size();
3742
7
                                      segment_metrics_context_.total_recycled_num +=
3743
7
                                              rs_meta->second.num_segments();
3744
7
                                      segment_metrics_context_.total_recycled_data_size +=
3745
7
                                              rs_meta->second.total_disk_size();
3746
7
                                      metrics_context.total_recycled_num++;
3747
7
                                  }
3748
14
                              });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
3723
861k
                               this](const std::string& path) {
3724
861k
                                  std::vector<std::string> str;
3725
861k
                                  butil::SplitString(path, '/', &str);
3726
861k
                                  std::string rowset_id;
3727
861k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3728
857k
                                      rowset_id = str.back().substr(0, pos);
3729
857k
                                  } else {
3730
4.18k
                                      if (path.find("packed_file/") != std::string::npos) {
3731
0
                                          return; // packed files do not have rowset_id encoded
3732
0
                                      }
3733
4.18k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3734
4.18k
                                      return;
3735
4.18k
                                  }
3736
857k
                                  auto rs_meta = rowsets.find(rowset_id);
3737
857k
                                  if (rs_meta != rowsets.end() &&
3738
861k
                                      !deleted_rowset_id.contains(rowset_id)) {
3739
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
3740
54.1k
                                      metrics_context.total_recycled_data_size +=
3741
54.1k
                                              rs_meta->second.total_disk_size();
3742
54.1k
                                      segment_metrics_context_.total_recycled_num +=
3743
54.1k
                                              rs_meta->second.num_segments();
3744
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
3745
54.1k
                                              rs_meta->second.total_disk_size();
3746
54.1k
                                      metrics_context.total_recycled_num++;
3747
54.1k
                                  }
3748
857k
                              });
3749
50
            }
3750
50
            return ret;
3751
50
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
3701
5
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
3702
5
            DCHECK(accessor_map_.count(*rid))
3703
0
                    << "uninitilized accessor, instance_id=" << instance_id_
3704
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
3705
5
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
3706
5
                                     &accessor_map_);
3707
5
            if (!accessor_map_.contains(*rid)) {
3708
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
3709
0
                        .tag("resource_id", resource_id)
3710
0
                        .tag("instance_id", instance_id_);
3711
0
                return -1;
3712
0
            }
3713
5
            auto& accessor = accessor_map_[*rid];
3714
5
            int ret = accessor->delete_files(*paths);
3715
5
            if (!ret) {
3716
                // deduplication of different files with the same rowset id
3717
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
3718
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
3719
5
                std::set<std::string> deleted_rowset_id;
3720
3721
5
                std::for_each(paths->begin(), paths->end(),
3722
5
                              [&metrics_context, &rowsets, &deleted_rowset_id,
3723
5
                               this](const std::string& path) {
3724
5
                                  std::vector<std::string> str;
3725
5
                                  butil::SplitString(path, '/', &str);
3726
5
                                  std::string rowset_id;
3727
5
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3728
5
                                      rowset_id = str.back().substr(0, pos);
3729
5
                                  } else {
3730
5
                                      if (path.find("packed_file/") != std::string::npos) {
3731
5
                                          return; // packed files do not have rowset_id encoded
3732
5
                                      }
3733
5
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3734
5
                                      return;
3735
5
                                  }
3736
5
                                  auto rs_meta = rowsets.find(rowset_id);
3737
5
                                  if (rs_meta != rowsets.end() &&
3738
5
                                      !deleted_rowset_id.contains(rowset_id)) {
3739
5
                                      deleted_rowset_id.emplace(rowset_id);
3740
5
                                      metrics_context.total_recycled_data_size +=
3741
5
                                              rs_meta->second.total_disk_size();
3742
5
                                      segment_metrics_context_.total_recycled_num +=
3743
5
                                              rs_meta->second.num_segments();
3744
5
                                      segment_metrics_context_.total_recycled_data_size +=
3745
5
                                              rs_meta->second.total_disk_size();
3746
5
                                      metrics_context.total_recycled_num++;
3747
5
                                  }
3748
5
                              });
3749
5
            }
3750
5
            return ret;
3751
5
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
3701
45
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
3702
45
            DCHECK(accessor_map_.count(*rid))
3703
0
                    << "uninitilized accessor, instance_id=" << instance_id_
3704
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
3705
45
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
3706
45
                                     &accessor_map_);
3707
45
            if (!accessor_map_.contains(*rid)) {
3708
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
3709
0
                        .tag("resource_id", resource_id)
3710
0
                        .tag("instance_id", instance_id_);
3711
0
                return -1;
3712
0
            }
3713
45
            auto& accessor = accessor_map_[*rid];
3714
45
            int ret = accessor->delete_files(*paths);
3715
45
            if (!ret) {
3716
                // deduplication of different files with the same rowset id
3717
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
3718
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
3719
45
                std::set<std::string> deleted_rowset_id;
3720
3721
45
                std::for_each(paths->begin(), paths->end(),
3722
45
                              [&metrics_context, &rowsets, &deleted_rowset_id,
3723
45
                               this](const std::string& path) {
3724
45
                                  std::vector<std::string> str;
3725
45
                                  butil::SplitString(path, '/', &str);
3726
45
                                  std::string rowset_id;
3727
45
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3728
45
                                      rowset_id = str.back().substr(0, pos);
3729
45
                                  } else {
3730
45
                                      if (path.find("packed_file/") != std::string::npos) {
3731
45
                                          return; // packed files do not have rowset_id encoded
3732
45
                                      }
3733
45
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3734
45
                                      return;
3735
45
                                  }
3736
45
                                  auto rs_meta = rowsets.find(rowset_id);
3737
45
                                  if (rs_meta != rowsets.end() &&
3738
45
                                      !deleted_rowset_id.contains(rowset_id)) {
3739
45
                                      deleted_rowset_id.emplace(rowset_id);
3740
45
                                      metrics_context.total_recycled_data_size +=
3741
45
                                              rs_meta->second.total_disk_size();
3742
45
                                      segment_metrics_context_.total_recycled_num +=
3743
45
                                              rs_meta->second.num_segments();
3744
45
                                      segment_metrics_context_.total_recycled_data_size +=
3745
45
                                              rs_meta->second.total_disk_size();
3746
45
                                      metrics_context.total_recycled_num++;
3747
45
                                  }
3748
45
                              });
3749
45
            }
3750
45
            return ret;
3751
45
        });
3752
50
    }
3753
92
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
3754
5
        LOG_INFO(
3755
5
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
3756
5
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
3757
5
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
3758
5
        concurrent_delete_executor.add([&]() -> int {
3759
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
3760
5
            if (!ret) {
3761
5
                auto rs = rowsets.at(rowset_id);
3762
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
3763
5
                metrics_context.total_recycled_num++;
3764
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
3765
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
3766
5
            }
3767
5
            return ret;
3768
5
        });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_2clEv
Line
Count
Source
3758
5
        concurrent_delete_executor.add([&]() -> int {
3759
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
3760
5
            if (!ret) {
3761
5
                auto rs = rowsets.at(rowset_id);
3762
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
3763
5
                metrics_context.total_recycled_num++;
3764
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
3765
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
3766
5
            }
3767
5
            return ret;
3768
5
        });
3769
5
    }
3770
3771
92
    bool finished = true;
3772
92
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
3773
92
    for (int r : rets) {
3774
55
        if (r != 0) {
3775
0
            ret = -1;
3776
0
            break;
3777
0
        }
3778
55
    }
3779
92
    ret = finished ? ret : -1;
3780
92
    return ret;
3781
92
}
3782
3783
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
3784
3.30k
                                         const std::string& rowset_id) {
3785
3.30k
    auto it = accessor_map_.find(resource_id);
3786
3.30k
    if (it == accessor_map_.end()) {
3787
400
        LOG_WARNING("instance has no such resource id")
3788
400
                .tag("instance_id", instance_id_)
3789
400
                .tag("resource_id", resource_id)
3790
400
                .tag("tablet_id", tablet_id)
3791
400
                .tag("rowset_id", rowset_id);
3792
400
        return -1;
3793
400
    }
3794
2.90k
    auto& accessor = it->second;
3795
2.90k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
3796
3.30k
}
3797
3798
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
3799
4
    if (key.empty()) {
3800
0
        return false;
3801
0
    }
3802
4
    std::string_view key_view = key;
3803
4
    key_view.remove_prefix(1); // remove keyspace prefix
3804
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
3805
4
    if (decode_key(&key_view, &decoded) != 0) {
3806
0
        return false;
3807
0
    }
3808
4
    if (decoded.size() < 4) {
3809
0
        return false;
3810
0
    }
3811
4
    try {
3812
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
3813
4
    } catch (const std::bad_variant_access&) {
3814
0
        return false;
3815
0
    }
3816
4
    return true;
3817
4
}
3818
3819
14
int InstanceRecycler::recycle_packed_files() {
3820
14
    const std::string task_name = "recycle_packed_files";
3821
14
    auto start_tp = steady_clock::now();
3822
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
3823
14
    int ret = 0;
3824
14
    PackedFileRecycleStats stats;
3825
3826
14
    register_recycle_task(task_name, start_time);
3827
14
    DORIS_CLOUD_DEFER {
3828
14
        unregister_recycle_task(task_name);
3829
14
        int64_t cost =
3830
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3831
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
3832
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
3833
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
3834
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
3835
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
3836
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
3837
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
3838
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
3839
14
                                                             stats.bytes_object_deleted);
3840
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
3841
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
3842
14
                .tag("instance_id", instance_id_)
3843
14
                .tag("num_scanned", stats.num_scanned)
3844
14
                .tag("num_corrected", stats.num_corrected)
3845
14
                .tag("num_deleted", stats.num_deleted)
3846
14
                .tag("num_failed", stats.num_failed)
3847
14
                .tag("num_objects_deleted", stats.num_object_deleted)
3848
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
3849
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
3850
14
                .tag("bytes_deleted", stats.bytes_deleted)
3851
14
                .tag("ret", ret);
3852
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
3827
14
    DORIS_CLOUD_DEFER {
3828
14
        unregister_recycle_task(task_name);
3829
14
        int64_t cost =
3830
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3831
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
3832
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
3833
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
3834
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
3835
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
3836
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
3837
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
3838
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
3839
14
                                                             stats.bytes_object_deleted);
3840
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
3841
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
3842
14
                .tag("instance_id", instance_id_)
3843
14
                .tag("num_scanned", stats.num_scanned)
3844
14
                .tag("num_corrected", stats.num_corrected)
3845
14
                .tag("num_deleted", stats.num_deleted)
3846
14
                .tag("num_failed", stats.num_failed)
3847
14
                .tag("num_objects_deleted", stats.num_object_deleted)
3848
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
3849
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
3850
14
                .tag("bytes_deleted", stats.bytes_deleted)
3851
14
                .tag("ret", ret);
3852
14
    };
3853
3854
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
3855
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
3856
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
3857
4
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_1clISt17basic_string_viewIcSt11char_traitsIcEES7_EEDaOT_OT0_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_1clISt17basic_string_viewIcSt11char_traitsIcEES7_EEDaOT_OT0_
Line
Count
Source
3854
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
3855
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
3856
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
3857
4
    };
3858
3859
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
3860
3861
14
    std::string begin = packed_file_key({instance_id_, ""});
3862
14
    std::string end = packed_file_key({instance_id_, "\xff"});
3863
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
3864
0
        ret = -1;
3865
0
    }
3866
3867
14
    return ret;
3868
14
}
3869
3870
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
3871
                                                  RecyclerMetricsContext& metrics_context,
3872
0
                                                  int64_t partition_id, bool is_empty_tablet) {
3873
0
    std::string tablet_key_begin, tablet_key_end;
3874
3875
0
    if (partition_id > 0) {
3876
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
3877
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
3878
0
    } else {
3879
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
3880
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
3881
0
    }
3882
    // for calculate the total num or bytes of recyled objects
3883
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
3884
0
                                                          std::string_view v) -> int {
3885
0
        doris::TabletMetaCloudPB tablet_meta_pb;
3886
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3887
0
            return 0;
3888
0
        }
3889
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3890
3891
0
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3892
0
            return 0;
3893
0
        }
3894
3895
0
        if (!is_empty_tablet) {
3896
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
3897
0
                return 0;
3898
0
            }
3899
0
            tablet_metrics_context_.total_need_recycle_num++;
3900
0
        }
3901
0
        return 0;
3902
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_tablets_and_statisticsEllRNS0_22RecyclerMetricsContextElbENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES8_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_tablets_and_statisticsEllRNS0_22RecyclerMetricsContextElbENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES8_
3903
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
3904
0
    metrics_context.report(true);
3905
0
    tablet_metrics_context_.report(true);
3906
0
    segment_metrics_context_.report(true);
3907
0
    return ret;
3908
0
}
3909
3910
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
3911
0
                                                 RecyclerMetricsContext& metrics_context) {
3912
0
    int ret = 0;
3913
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
3914
0
    std::unique_ptr<Transaction> txn;
3915
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3916
0
        LOG_WARNING("failed to recycle tablet ")
3917
0
                .tag("tablet id", tablet_id)
3918
0
                .tag("instance_id", instance_id_)
3919
0
                .tag("reason", "failed to create txn");
3920
0
        ret = -1;
3921
0
    }
3922
0
    GetRowsetResponse resp;
3923
0
    std::string msg;
3924
0
    MetaServiceCode code = MetaServiceCode::OK;
3925
    // get rowsets in tablet
3926
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
3927
0
                        tablet_id, code, msg, &resp);
3928
0
    if (code != MetaServiceCode::OK) {
3929
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
3930
0
                .tag("tablet id", tablet_id)
3931
0
                .tag("msg", msg)
3932
0
                .tag("code", code)
3933
0
                .tag("instance id", instance_id_);
3934
0
        ret = -1;
3935
0
    }
3936
0
    for (const auto& rs_meta : resp.rowset_meta()) {
3937
        /*
3938
        * For compatibility, we skip the loop for [0-1] here.
3939
        * The purpose of this loop is to delete object files,
3940
        * and since [0-1] only has meta and doesn't have object files,
3941
        * skipping it doesn't affect system correctness.
3942
        *
3943
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
3944
        * would return error -1 directly, causing the recycle operation to fail.
3945
        *
3946
        * [0-1] doesn't have resource id is a bug.
3947
        * In the future, we will fix this problem, after that,
3948
        * we can remove this if statement.
3949
        *
3950
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
3951
        */
3952
3953
0
        if (rs_meta.end_version() == 1) {
3954
            // Assert that [0-1] has no resource_id to make sure
3955
            // this if statement will not be forgetted to remove
3956
            // when the resource id bug is fixed
3957
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
3958
0
            continue;
3959
0
        }
3960
0
        if (!rs_meta.has_resource_id()) {
3961
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
3962
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
3963
0
                    .tag("instance_id", instance_id_)
3964
0
                    .tag("tablet_id", tablet_id);
3965
0
            continue;
3966
0
        }
3967
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
3968
0
        auto it = accessor_map_.find(rs_meta.resource_id());
3969
        // possible if the accessor is not initilized correctly
3970
0
        if (it == accessor_map_.end()) [[unlikely]] {
3971
0
            LOG_WARNING(
3972
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
3973
0
                    "recycle process")
3974
0
                    .tag("tablet id", tablet_id)
3975
0
                    .tag("instance_id", instance_id_)
3976
0
                    .tag("resource_id", rs_meta.resource_id())
3977
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
3978
0
            continue;
3979
0
        }
3980
3981
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
3982
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
3983
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
3984
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
3985
0
    }
3986
0
    return ret;
3987
0
}
3988
3989
4.25k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
3990
4.25k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
3991
4.25k
            .tag("instance_id", instance_id_)
3992
4.25k
            .tag("tablet_id", tablet_id);
3993
3994
4.25k
    if (should_recycle_versioned_keys()) {
3995
11
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
3996
11
        if (ret != 0) {
3997
0
            return ret;
3998
0
        }
3999
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
4000
        // during the recycle_versioned_tablet process.
4001
        //
4002
        // .. And remove restore job rowsets of this tablet too
4003
11
    }
4004
4005
4.25k
    int ret = 0;
4006
4.25k
    auto start_time = steady_clock::now();
4007
4008
4.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4009
4010
    // collect resource ids
4011
248
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4012
248
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4013
248
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4014
248
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4015
248
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
4016
248
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
4017
4018
248
    std::set<std::string> resource_ids;
4019
248
    int64_t recycle_rowsets_number = 0;
4020
248
    int64_t recycle_segments_number = 0;
4021
248
    int64_t recycle_rowsets_data_size = 0;
4022
248
    int64_t recycle_rowsets_index_size = 0;
4023
248
    int64_t recycle_restore_job_rowsets_number = 0;
4024
248
    int64_t recycle_restore_job_segments_number = 0;
4025
248
    int64_t recycle_restore_job_rowsets_data_size = 0;
4026
248
    int64_t recycle_restore_job_rowsets_index_size = 0;
4027
248
    int64_t max_rowset_version = 0;
4028
248
    int64_t min_rowset_creation_time = INT64_MAX;
4029
248
    int64_t max_rowset_creation_time = 0;
4030
248
    int64_t min_rowset_expiration_time = INT64_MAX;
4031
248
    int64_t max_rowset_expiration_time = 0;
4032
4033
248
    DORIS_CLOUD_DEFER {
4034
248
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4035
248
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4036
248
                .tag("instance_id", instance_id_)
4037
248
                .tag("tablet_id", tablet_id)
4038
248
                .tag("recycle rowsets number", recycle_rowsets_number)
4039
248
                .tag("recycle segments number", recycle_segments_number)
4040
248
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4041
248
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4042
248
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4043
248
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4044
248
                .tag("all restore job rowsets recycle data size",
4045
248
                     recycle_restore_job_rowsets_data_size)
4046
248
                .tag("all restore job rowsets recycle index size",
4047
248
                     recycle_restore_job_rowsets_index_size)
4048
248
                .tag("max rowset version", max_rowset_version)
4049
248
                .tag("min rowset creation time", min_rowset_creation_time)
4050
248
                .tag("max rowset creation time", max_rowset_creation_time)
4051
248
                .tag("min rowset expiration time", min_rowset_expiration_time)
4052
248
                .tag("max rowset expiration time", max_rowset_expiration_time)
4053
248
                .tag("task type", metrics_context.operation_type)
4054
248
                .tag("ret", ret);
4055
248
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4033
248
    DORIS_CLOUD_DEFER {
4034
248
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4035
248
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4036
248
                .tag("instance_id", instance_id_)
4037
248
                .tag("tablet_id", tablet_id)
4038
248
                .tag("recycle rowsets number", recycle_rowsets_number)
4039
248
                .tag("recycle segments number", recycle_segments_number)
4040
248
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4041
248
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4042
248
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4043
248
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4044
248
                .tag("all restore job rowsets recycle data size",
4045
248
                     recycle_restore_job_rowsets_data_size)
4046
248
                .tag("all restore job rowsets recycle index size",
4047
248
                     recycle_restore_job_rowsets_index_size)
4048
248
                .tag("max rowset version", max_rowset_version)
4049
248
                .tag("min rowset creation time", min_rowset_creation_time)
4050
248
                .tag("max rowset creation time", max_rowset_creation_time)
4051
248
                .tag("min rowset expiration time", min_rowset_expiration_time)
4052
248
                .tag("max rowset expiration time", max_rowset_expiration_time)
4053
248
                .tag("task type", metrics_context.operation_type)
4054
248
                .tag("ret", ret);
4055
248
    };
4056
4057
248
    std::unique_ptr<Transaction> txn;
4058
248
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4059
0
        LOG_WARNING("failed to recycle tablet ")
4060
0
                .tag("tablet id", tablet_id)
4061
0
                .tag("instance_id", instance_id_)
4062
0
                .tag("reason", "failed to create txn");
4063
0
        ret = -1;
4064
0
    }
4065
248
    GetRowsetResponse resp;
4066
248
    std::string msg;
4067
248
    MetaServiceCode code = MetaServiceCode::OK;
4068
    // get rowsets in tablet
4069
248
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4070
248
                        tablet_id, code, msg, &resp);
4071
248
    if (code != MetaServiceCode::OK) {
4072
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4073
0
                .tag("tablet id", tablet_id)
4074
0
                .tag("msg", msg)
4075
0
                .tag("code", code)
4076
0
                .tag("instance id", instance_id_);
4077
0
        ret = -1;
4078
0
    }
4079
248
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
4080
4081
2.51k
    for (const auto& rs_meta : resp.rowset_meta()) {
4082
        // The rowset has no resource id and segments when it was generated by compaction
4083
        // with multiple hole rowsets or it's version is [0-1], so we can skip it.
4084
2.51k
        if (!rs_meta.has_resource_id() && rs_meta.num_segments() == 0) {
4085
0
            LOG_INFO("rowset meta does not have a resource id and no segments, skip this rowset")
4086
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4087
0
                    .tag("instance_id", instance_id_)
4088
0
                    .tag("tablet_id", tablet_id);
4089
0
            recycle_rowsets_number += 1;
4090
0
            continue;
4091
0
        }
4092
2.51k
        if (!rs_meta.has_resource_id()) {
4093
1
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4094
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
4095
1
                    .tag("instance_id", instance_id_)
4096
1
                    .tag("tablet_id", tablet_id);
4097
1
            return -1;
4098
1
        }
4099
2.51k
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4100
2.51k
        auto it = accessor_map_.find(rs_meta.resource_id());
4101
        // possible if the accessor is not initilized correctly
4102
2.51k
        if (it == accessor_map_.end()) [[unlikely]] {
4103
1
            LOG_WARNING(
4104
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4105
1
                    "recycle process")
4106
1
                    .tag("tablet id", tablet_id)
4107
1
                    .tag("instance_id", instance_id_)
4108
1
                    .tag("resource_id", rs_meta.resource_id())
4109
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4110
1
            return -1;
4111
1
        }
4112
2.51k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4113
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
4114
0
                    .tag("instance_id", instance_id_)
4115
0
                    .tag("tablet_id", tablet_id)
4116
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4117
0
            return -1;
4118
0
        }
4119
2.51k
        recycle_rowsets_number += 1;
4120
2.51k
        recycle_segments_number += rs_meta.num_segments();
4121
2.51k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4122
2.51k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4123
2.51k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4124
2.51k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4125
2.51k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4126
2.51k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4127
2.51k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4128
2.51k
        resource_ids.emplace(rs_meta.resource_id());
4129
2.51k
    }
4130
4131
    // get restore job rowset in tablet
4132
246
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
4133
246
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
4134
246
    if (code != MetaServiceCode::OK) {
4135
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
4136
0
                .tag("tablet id", tablet_id)
4137
0
                .tag("msg", msg)
4138
0
                .tag("code", code)
4139
0
                .tag("instance id", instance_id_);
4140
0
        return -1;
4141
0
    }
4142
4143
246
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
4144
0
        if (!rs_meta.has_resource_id()) {
4145
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4146
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4147
0
                    .tag("instance_id", instance_id_)
4148
0
                    .tag("tablet_id", tablet_id);
4149
0
            return -1;
4150
0
        }
4151
4152
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4153
        // possible if the accessor is not initilized correctly
4154
0
        if (it == accessor_map_.end()) [[unlikely]] {
4155
0
            LOG_WARNING(
4156
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4157
0
                    "recycle process")
4158
0
                    .tag("tablet id", tablet_id)
4159
0
                    .tag("instance_id", instance_id_)
4160
0
                    .tag("resource_id", rs_meta.resource_id())
4161
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4162
0
            return -1;
4163
0
        }
4164
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4165
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
4166
0
                    .tag("instance_id", instance_id_)
4167
0
                    .tag("tablet_id", tablet_id)
4168
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4169
0
            return -1;
4170
0
        }
4171
0
        recycle_restore_job_rowsets_number += 1;
4172
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
4173
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
4174
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
4175
0
        resource_ids.emplace(rs_meta.resource_id());
4176
0
    }
4177
4178
246
    LOG_INFO("recycle tablet start to delete object")
4179
246
            .tag("instance id", instance_id_)
4180
246
            .tag("tablet id", tablet_id)
4181
246
            .tag("recycle tablet resource ids are",
4182
246
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
4183
246
                                 [](std::string rs_id, const auto& it) {
4184
206
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4185
206
                                 }));
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_1clINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEEEDaSB_RKT_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_1clINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEEEDaSB_RKT_
Line
Count
Source
4183
206
                                 [](std::string rs_id, const auto& it) {
4184
206
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4185
206
                                 }));
4186
4187
246
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
4188
246
            _thread_pool_group.s3_producer_pool,
4189
246
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4190
246
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKSt4pairIiNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKSt4pairIiNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE
Line
Count
Source
4190
206
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
4191
4192
    // delete all rowset data in this tablet
4193
    // ATTN: there may be data leak if not all accessor initilized successfully
4194
    //       partial data deleted if the tablet is stored cross-storage vault
4195
    //       vault id is not attached to TabletMeta...
4196
246
    for (const auto& resource_id : resource_ids) {
4197
206
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
4198
206
        concurrent_delete_executor.add(
4199
206
                [&, rs_id = resource_id,
4200
206
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4201
206
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4202
206
                    if (res != 0) {
4203
2
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4204
2
                                     << " path=" << accessor_ptr->uri()
4205
2
                                     << " task type=" << metrics_context.operation_type;
4206
2
                        return std::make_pair(-1, rs_id);
4207
2
                    }
4208
204
                    return std::make_pair(0, rs_id);
4209
206
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
4200
206
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4201
206
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4202
206
                    if (res != 0) {
4203
2
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4204
2
                                     << " path=" << accessor_ptr->uri()
4205
2
                                     << " task type=" << metrics_context.operation_type;
4206
2
                        return std::make_pair(-1, rs_id);
4207
2
                    }
4208
204
                    return std::make_pair(0, rs_id);
4209
206
                });
4210
206
    }
4211
4212
246
    bool finished = true;
4213
246
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
4214
246
    for (auto& r : rets) {
4215
206
        if (r.first != 0) {
4216
2
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
4217
2
            ret = -1;
4218
2
        }
4219
206
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
4220
206
    }
4221
246
    ret = finished ? ret : -1;
4222
4223
246
    if (ret != 0) { // failed recycle tablet data
4224
2
        LOG_WARNING("ret!=0")
4225
2
                .tag("finished", finished)
4226
2
                .tag("ret", ret)
4227
2
                .tag("instance_id", instance_id_)
4228
2
                .tag("tablet_id", tablet_id);
4229
2
        return ret;
4230
2
    }
4231
4232
244
    tablet_metrics_context_.total_recycled_data_size +=
4233
244
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4234
244
    tablet_metrics_context_.total_recycled_num += 1;
4235
244
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
4236
244
    segment_metrics_context_.total_recycled_data_size +=
4237
244
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4238
244
    metrics_context.total_recycled_data_size +=
4239
244
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4240
244
    tablet_metrics_context_.report();
4241
244
    segment_metrics_context_.report();
4242
244
    metrics_context.report();
4243
4244
244
    txn.reset();
4245
244
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4246
0
        LOG_WARNING("failed to recycle tablet ")
4247
0
                .tag("tablet id", tablet_id)
4248
0
                .tag("instance_id", instance_id_)
4249
0
                .tag("reason", "failed to create txn");
4250
0
        ret = -1;
4251
0
    }
4252
    // delete all rowset kv in this tablet
4253
244
    txn->remove(rs_key0, rs_key1);
4254
244
    txn->remove(recyc_rs_key0, recyc_rs_key1);
4255
244
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
4256
4257
    // remove delete bitmap for MoW table
4258
244
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
4259
244
    txn->remove(pending_key);
4260
244
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
4261
244
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
4262
244
    txn->remove(delete_bitmap_start, delete_bitmap_end);
4263
4264
244
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
4265
244
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
4266
244
    txn->remove(dbm_start_key, dbm_end_key);
4267
244
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
4268
244
              << " end=" << hex(dbm_end_key);
4269
4270
244
    TxnErrorCode err = txn->commit();
4271
244
    if (err != TxnErrorCode::TXN_OK) {
4272
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
4273
0
        ret = -1;
4274
0
    }
4275
4276
244
    if (ret == 0) {
4277
        // All object files under tablet have been deleted
4278
244
        std::lock_guard lock(recycled_tablets_mtx_);
4279
244
        recycled_tablets_.insert(tablet_id);
4280
244
    }
4281
4282
244
    return ret;
4283
246
}
4284
4285
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
4286
11
                                               RecyclerMetricsContext& metrics_context) {
4287
11
    int ret = 0;
4288
11
    auto start_time = steady_clock::now();
4289
4290
11
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4291
4292
    // collect resource ids
4293
11
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4294
11
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4295
11
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4296
11
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4297
4298
11
    int64_t recycle_rowsets_number = 0;
4299
11
    int64_t recycle_segments_number = 0;
4300
11
    int64_t recycle_rowsets_data_size = 0;
4301
11
    int64_t recycle_rowsets_index_size = 0;
4302
11
    int64_t max_rowset_version = 0;
4303
11
    int64_t min_rowset_creation_time = INT64_MAX;
4304
11
    int64_t max_rowset_creation_time = 0;
4305
11
    int64_t min_rowset_expiration_time = INT64_MAX;
4306
11
    int64_t max_rowset_expiration_time = 0;
4307
4308
11
    DORIS_CLOUD_DEFER {
4309
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4310
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4311
11
                .tag("instance_id", instance_id_)
4312
11
                .tag("tablet_id", tablet_id)
4313
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4314
11
                .tag("recycle segments number", recycle_segments_number)
4315
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4316
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4317
11
                .tag("max rowset version", max_rowset_version)
4318
11
                .tag("min rowset creation time", min_rowset_creation_time)
4319
11
                .tag("max rowset creation time", max_rowset_creation_time)
4320
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4321
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4322
11
                .tag("ret", ret);
4323
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4308
11
    DORIS_CLOUD_DEFER {
4309
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4310
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4311
11
                .tag("instance_id", instance_id_)
4312
11
                .tag("tablet_id", tablet_id)
4313
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4314
11
                .tag("recycle segments number", recycle_segments_number)
4315
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4316
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4317
11
                .tag("max rowset version", max_rowset_version)
4318
11
                .tag("min rowset creation time", min_rowset_creation_time)
4319
11
                .tag("max rowset creation time", max_rowset_creation_time)
4320
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4321
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4322
11
                .tag("ret", ret);
4323
11
    };
4324
4325
11
    std::unique_ptr<Transaction> txn;
4326
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4327
0
        LOG_WARNING("failed to recycle tablet ")
4328
0
                .tag("tablet id", tablet_id)
4329
0
                .tag("instance_id", instance_id_)
4330
0
                .tag("reason", "failed to create txn");
4331
0
        ret = -1;
4332
0
    }
4333
4334
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
4335
    // by the related operation logs.
4336
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
4337
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
4338
11
    MetaReader meta_reader(instance_id_);
4339
11
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
4340
11
    if (err == TxnErrorCode::TXN_OK) {
4341
11
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
4342
11
    }
4343
11
    if (err != TxnErrorCode::TXN_OK) {
4344
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4345
0
                .tag("tablet id", tablet_id)
4346
0
                .tag("err", err)
4347
0
                .tag("instance id", instance_id_);
4348
0
        ret = -1;
4349
0
    }
4350
4351
11
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
4352
11
             load_rowset_metas.size(), compact_rowset_metas.size())
4353
11
            .tag("instance_id", instance_id_)
4354
11
            .tag("tablet_id", tablet_id);
4355
4356
11
    SyncExecutor<int> concurrent_delete_executor(
4357
11
            _thread_pool_group.s3_producer_pool,
4358
11
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4359
11
            [](const int& ret) { return ret != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_1clERKi
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_1clERKi
4360
4361
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
4362
60
        recycle_rowsets_number += 1;
4363
60
        recycle_segments_number += rs_meta.num_segments();
4364
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4365
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4366
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4367
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4368
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4369
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4370
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4371
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
4361
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
4362
60
        recycle_rowsets_number += 1;
4363
60
        recycle_segments_number += rs_meta.num_segments();
4364
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4365
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4366
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4367
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4368
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4369
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4370
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4371
60
    };
4372
4373
11
    std::vector<RowsetDeleteTask> all_tasks;
4374
60
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
4375
60
        update_rowset_stats(rs_meta);
4376
        // Version 0-1 rowset has no resource_id and no actual data files,
4377
        // but still needs ref_count key cleanup, so we add it to all_tasks.
4378
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
4379
60
        RowsetDeleteTask task;
4380
60
        task.rowset_meta = rs_meta;
4381
60
        task.versioned_rowset_key =
4382
60
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
4383
60
        task.non_versioned_rowset_key =
4384
60
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
4385
60
        task.versionstamp = versionstamp;
4386
60
        all_tasks.push_back(std::move(task));
4387
60
    }
4388
4389
11
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
4390
0
        update_rowset_stats(rs_meta);
4391
        // Version 0-1 rowset has no resource_id and no actual data files,
4392
        // but still needs ref_count key cleanup, so we add it to all_tasks.
4393
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
4394
0
        RowsetDeleteTask task;
4395
0
        task.rowset_meta = rs_meta;
4396
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
4397
0
                {instance_id_, tablet_id, rs_meta.end_version()});
4398
0
        task.non_versioned_rowset_key =
4399
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
4400
0
        task.versionstamp = versionstamp;
4401
0
        all_tasks.push_back(std::move(task));
4402
0
    }
4403
4404
11
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
4405
0
        RecycleRowsetPB recycle_rowset;
4406
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
4407
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4408
0
            return -1;
4409
0
        }
4410
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
4411
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
4412
                // in old version, keep this key-value pair and it needs to be checked manually
4413
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4414
0
                return -1;
4415
0
            }
4416
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
4417
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
4418
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
4419
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
4420
0
                return -1;
4421
0
            }
4422
            // decode rowset_id
4423
0
            auto k1 = k;
4424
0
            k1.remove_prefix(1);
4425
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
4426
0
            decode_key(&k1, &out);
4427
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
4428
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
4429
0
            LOG_INFO("delete old-version rowset data")
4430
0
                    .tag("instance_id", instance_id_)
4431
0
                    .tag("tablet_id", tablet_id)
4432
0
                    .tag("rowset_id", rowset_id);
4433
4434
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
4435
            // so we must use prefix deletion directly instead of batch delete.
4436
0
            concurrent_delete_executor.add(
4437
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
4438
                        // delete by prefix, the recycle rowset key will be deleted by range later.
4439
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
4440
0
                    });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Unexecuted instantiation: recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
4441
0
        } else {
4442
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
4443
            // Version 0-1 rowset has no resource_id and no actual data files,
4444
            // but still needs ref_count key cleanup, so we add it to all_tasks.
4445
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
4446
0
            RowsetDeleteTask task;
4447
0
            task.rowset_meta = rowset_meta;
4448
0
            task.recycle_rowset_key = k;
4449
0
            all_tasks.push_back(std::move(task));
4450
0
        }
4451
0
        return 0;
4452
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
4453
4454
11
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
4455
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
4456
0
                .tag("tablet id", tablet_id)
4457
0
                .tag("instance_id", instance_id_)
4458
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
4459
0
        ret = -1;
4460
0
    }
4461
4462
    // Phase 1: Classify tasks by ref_count
4463
11
    std::vector<RowsetDeleteTask> batch_delete_tasks;
4464
60
    for (auto& task : all_tasks) {
4465
60
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
4466
60
        if (classify_ret < 0) {
4467
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
4468
0
                    .tag("instance_id", instance_id_)
4469
0
                    .tag("tablet_id", tablet_id)
4470
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
4471
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
4472
0
                return recycle_rowset_meta_and_data(t);
4473
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_4clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_4clEv
4474
0
        }
4475
60
    }
4476
4477
11
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
4478
4479
11
    LOG_INFO("batch delete plan created")
4480
11
            .tag("instance_id", instance_id_)
4481
11
            .tag("tablet_id", tablet_id)
4482
11
            .tag("plan_count", batch_delete_tasks.size());
4483
4484
    // Phase 2: Execute batch delete using existing delete_rowset_data
4485
11
    if (!batch_delete_tasks.empty()) {
4486
10
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
4487
49
        for (const auto& task : batch_delete_tasks) {
4488
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
4489
49
            if (task.rowset_meta.resource_id().empty()) {
4490
10
                LOG_INFO("skip rowset with empty resource_id in batch delete")
4491
10
                        .tag("instance_id", instance_id_)
4492
10
                        .tag("tablet_id", tablet_id)
4493
10
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
4494
10
                continue;
4495
10
            }
4496
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
4497
39
        }
4498
4499
        // Only call delete_rowset_data if there are rowsets with actual data to delete
4500
10
        bool delete_success = true;
4501
10
        if (!rowsets_to_delete.empty()) {
4502
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
4503
9
                                                         "batch_delete_versioned_tablet");
4504
9
            int delete_ret = delete_rowset_data(
4505
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
4506
9
            if (delete_ret != 0) {
4507
0
                LOG_WARNING("batch delete execution failed")
4508
0
                        .tag("instance_id", instance_id_)
4509
0
                        .tag("tablet_id", tablet_id);
4510
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
4511
0
                ret = -1;
4512
0
                delete_success = false;
4513
0
            }
4514
9
        }
4515
4516
        // Phase 3: Only cleanup metadata if data deletion succeeded.
4517
        // If deletion failed, keep recycle_rowset_key so next round will retry.
4518
10
        if (delete_success) {
4519
10
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
4520
10
            if (cleanup_ret != 0) {
4521
0
                LOG_WARNING("batch delete cleanup failed")
4522
0
                        .tag("instance_id", instance_id_)
4523
0
                        .tag("tablet_id", tablet_id);
4524
0
                ret = -1;
4525
0
            }
4526
10
        }
4527
10
    }
4528
4529
    // Always wait for fallback tasks to complete before returning
4530
11
    bool finished = true;
4531
11
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4532
11
    for (int r : rets) {
4533
0
        if (r != 0) {
4534
0
            ret = -1;
4535
0
        }
4536
0
    }
4537
4538
11
    ret = finished ? ret : -1;
4539
4540
11
    if (ret != 0) { // failed recycle tablet data
4541
0
        LOG_WARNING("recycle versioned tablet failed")
4542
0
                .tag("finished", finished)
4543
0
                .tag("ret", ret)
4544
0
                .tag("instance_id", instance_id_)
4545
0
                .tag("tablet_id", tablet_id);
4546
0
        return ret;
4547
0
    }
4548
4549
11
    tablet_metrics_context_.total_recycled_data_size +=
4550
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4551
11
    tablet_metrics_context_.total_recycled_num += 1;
4552
11
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
4553
11
    segment_metrics_context_.total_recycled_data_size +=
4554
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4555
11
    metrics_context.total_recycled_data_size +=
4556
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4557
11
    tablet_metrics_context_.report();
4558
11
    segment_metrics_context_.report();
4559
11
    metrics_context.report();
4560
4561
11
    txn.reset();
4562
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4563
0
        LOG_WARNING("failed to recycle tablet ")
4564
0
                .tag("tablet id", tablet_id)
4565
0
                .tag("instance_id", instance_id_)
4566
0
                .tag("reason", "failed to create txn");
4567
0
        ret = -1;
4568
0
    }
4569
    // delete all rowset kv in this tablet
4570
11
    txn->remove(rs_key0, rs_key1);
4571
11
    txn->remove(recyc_rs_key0, recyc_rs_key1);
4572
4573
    // remove delete bitmap for MoW table
4574
11
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
4575
11
    txn->remove(pending_key);
4576
11
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
4577
11
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
4578
11
    txn->remove(delete_bitmap_start, delete_bitmap_end);
4579
4580
11
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
4581
11
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
4582
11
    txn->remove(dbm_start_key, dbm_end_key);
4583
11
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
4584
11
              << " end=" << hex(dbm_end_key);
4585
4586
11
    std::string versioned_idx_key = versioned::tablet_index_key({instance_id_, tablet_id});
4587
11
    std::string tablet_index_val;
4588
11
    err = txn->get(versioned_idx_key, &tablet_index_val);
4589
11
    if (err != TxnErrorCode::TXN_KEY_NOT_FOUND && err != TxnErrorCode::TXN_OK) {
4590
0
        LOG_WARNING("failed to get tablet index kv")
4591
0
                .tag("instance_id", instance_id_)
4592
0
                .tag("tablet_id", tablet_id)
4593
0
                .tag("err", err);
4594
0
        ret = -1;
4595
11
    } else if (err == TxnErrorCode::TXN_OK) {
4596
        // If the tablet index kv exists, we need to delete it
4597
10
        TabletIndexPB tablet_index_pb;
4598
10
        if (!tablet_index_pb.ParseFromString(tablet_index_val)) {
4599
0
            LOG_WARNING("failed to parse tablet index pb")
4600
0
                    .tag("instance_id", instance_id_)
4601
0
                    .tag("tablet_id", tablet_id);
4602
0
            ret = -1;
4603
10
        } else {
4604
10
            std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
4605
10
                    {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
4606
10
                     tablet_index_pb.index_id(), tablet_index_pb.partition_id(), tablet_id});
4607
10
            txn->remove(versioned_inverted_idx_key);
4608
10
            txn->remove(versioned_idx_key);
4609
10
        }
4610
10
    }
4611
4612
11
    err = txn->commit();
4613
11
    if (err != TxnErrorCode::TXN_OK) {
4614
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
4615
0
        ret = -1;
4616
0
    }
4617
4618
11
    if (ret == 0) {
4619
        // All object files under tablet have been deleted
4620
11
        std::lock_guard lock(recycled_tablets_mtx_);
4621
11
        recycled_tablets_.insert(tablet_id);
4622
11
    }
4623
4624
11
    return ret;
4625
11
}
4626
4627
27
int InstanceRecycler::recycle_rowsets() {
4628
27
    if (should_recycle_versioned_keys()) {
4629
5
        return recycle_versioned_rowsets();
4630
5
    }
4631
4632
22
    const std::string task_name = "recycle_rowsets";
4633
22
    int64_t num_scanned = 0;
4634
22
    int64_t num_expired = 0;
4635
22
    int64_t num_prepare = 0;
4636
22
    int64_t num_compacted = 0;
4637
22
    int64_t num_empty_rowset = 0;
4638
22
    size_t total_rowset_key_size = 0;
4639
22
    size_t total_rowset_value_size = 0;
4640
22
    size_t expired_rowset_size = 0;
4641
22
    std::atomic_long num_recycled = 0;
4642
22
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
4643
4644
22
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
4645
22
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
4646
22
    std::string recyc_rs_key0;
4647
22
    std::string recyc_rs_key1;
4648
22
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
4649
22
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
4650
4651
22
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
4652
4653
22
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
4654
22
    register_recycle_task(task_name, start_time);
4655
4656
22
    DORIS_CLOUD_DEFER {
4657
22
        unregister_recycle_task(task_name);
4658
22
        int64_t cost =
4659
22
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4660
22
        metrics_context.finish_report();
4661
22
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
4662
22
                .tag("instance_id", instance_id_)
4663
22
                .tag("num_scanned", num_scanned)
4664
22
                .tag("num_expired", num_expired)
4665
22
                .tag("num_recycled", num_recycled)
4666
22
                .tag("num_recycled.prepare", num_prepare)
4667
22
                .tag("num_recycled.compacted", num_compacted)
4668
22
                .tag("num_recycled.empty_rowset", num_empty_rowset)
4669
22
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
4670
22
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
4671
22
                .tag("expired_rowset_meta_size", expired_rowset_size);
4672
22
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
4656
7
    DORIS_CLOUD_DEFER {
4657
7
        unregister_recycle_task(task_name);
4658
7
        int64_t cost =
4659
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4660
7
        metrics_context.finish_report();
4661
7
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
4662
7
                .tag("instance_id", instance_id_)
4663
7
                .tag("num_scanned", num_scanned)
4664
7
                .tag("num_expired", num_expired)
4665
7
                .tag("num_recycled", num_recycled)
4666
7
                .tag("num_recycled.prepare", num_prepare)
4667
7
                .tag("num_recycled.compacted", num_compacted)
4668
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
4669
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
4670
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
4671
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
4672
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
4656
15
    DORIS_CLOUD_DEFER {
4657
15
        unregister_recycle_task(task_name);
4658
15
        int64_t cost =
4659
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4660
15
        metrics_context.finish_report();
4661
15
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
4662
15
                .tag("instance_id", instance_id_)
4663
15
                .tag("num_scanned", num_scanned)
4664
15
                .tag("num_expired", num_expired)
4665
15
                .tag("num_recycled", num_recycled)
4666
15
                .tag("num_recycled.prepare", num_prepare)
4667
15
                .tag("num_recycled.compacted", num_compacted)
4668
15
                .tag("num_recycled.empty_rowset", num_empty_rowset)
4669
15
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
4670
15
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
4671
15
                .tag("expired_rowset_meta_size", expired_rowset_size);
4672
15
    };
4673
4674
22
    std::vector<std::string> rowset_keys;
4675
    // rowset_id -> rowset_meta
4676
    // store rowset id and meta for statistics rs size when delete
4677
22
    std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
4678
4679
    // Store keys of rowset recycled by background workers
4680
22
    std::mutex async_recycled_rowset_keys_mutex;
4681
22
    std::vector<std::string> async_recycled_rowset_keys;
4682
22
    auto worker_pool = std::make_unique<SimpleThreadPool>(
4683
22
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
4684
22
    worker_pool->start();
4685
    // TODO bacth delete
4686
4.00k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
4687
4.00k
        std::string dbm_start_key =
4688
4.00k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4689
4.00k
        std::string dbm_end_key = dbm_start_key;
4690
4.00k
        encode_int64(INT64_MAX, &dbm_end_key);
4691
4.00k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4692
4.00k
        if (ret != 0) {
4693
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
4694
0
                         << instance_id_;
4695
0
        }
4696
4.00k
        return ret;
4697
4.00k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
4686
2
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
4687
2
        std::string dbm_start_key =
4688
2
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4689
2
        std::string dbm_end_key = dbm_start_key;
4690
2
        encode_int64(INT64_MAX, &dbm_end_key);
4691
2
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4692
2
        if (ret != 0) {
4693
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
4694
0
                         << instance_id_;
4695
0
        }
4696
2
        return ret;
4697
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
4686
4.00k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
4687
4.00k
        std::string dbm_start_key =
4688
4.00k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4689
4.00k
        std::string dbm_end_key = dbm_start_key;
4690
4.00k
        encode_int64(INT64_MAX, &dbm_end_key);
4691
4.00k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4692
4.00k
        if (ret != 0) {
4693
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
4694
0
                         << instance_id_;
4695
0
        }
4696
4.00k
        return ret;
4697
4.00k
    };
4698
22
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
4699
902
                                            int64_t tablet_id, const std::string& rowset_id) {
4700
        // Try to delete rowset data in background thread
4701
902
        int ret = worker_pool->submit_with_timeout(
4702
902
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4703
811
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4704
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4705
0
                        return;
4706
0
                    }
4707
811
                    std::vector<std::string> keys;
4708
811
                    {
4709
811
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4710
811
                        async_recycled_rowset_keys.push_back(std::move(key));
4711
811
                        if (async_recycled_rowset_keys.size() > 100) {
4712
7
                            keys.swap(async_recycled_rowset_keys);
4713
7
                        }
4714
811
                    }
4715
811
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4716
811
                    if (keys.empty()) return;
4717
7
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4718
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4719
0
                                     << instance_id_;
4720
7
                    } else {
4721
7
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4722
7
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4723
7
                                           num_recycled, start_time);
4724
7
                    }
4725
7
                },
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
4702
2
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4703
2
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4704
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4705
0
                        return;
4706
0
                    }
4707
2
                    std::vector<std::string> keys;
4708
2
                    {
4709
2
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4710
2
                        async_recycled_rowset_keys.push_back(std::move(key));
4711
2
                        if (async_recycled_rowset_keys.size() > 100) {
4712
0
                            keys.swap(async_recycled_rowset_keys);
4713
0
                        }
4714
2
                    }
4715
2
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4716
2
                    if (keys.empty()) return;
4717
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4718
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4719
0
                                     << instance_id_;
4720
0
                    } else {
4721
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4722
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4723
0
                                           num_recycled, start_time);
4724
0
                    }
4725
0
                },
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
4702
809
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4703
809
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4704
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4705
0
                        return;
4706
0
                    }
4707
809
                    std::vector<std::string> keys;
4708
809
                    {
4709
809
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4710
809
                        async_recycled_rowset_keys.push_back(std::move(key));
4711
809
                        if (async_recycled_rowset_keys.size() > 100) {
4712
7
                            keys.swap(async_recycled_rowset_keys);
4713
7
                        }
4714
809
                    }
4715
809
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4716
809
                    if (keys.empty()) return;
4717
7
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4718
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4719
0
                                     << instance_id_;
4720
7
                    } else {
4721
7
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4722
7
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4723
7
                                           num_recycled, start_time);
4724
7
                    }
4725
7
                },
4726
902
                0);
4727
902
        if (ret == 0) return 0;
4728
        // Submit task failed, delete rowset data in current thread
4729
91
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4730
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4731
0
            return -1;
4732
0
        }
4733
91
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
4734
0
            return -1;
4735
0
        }
4736
91
        rowset_keys.push_back(std::move(key));
4737
91
        return 0;
4738
91
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
4699
2
                                            int64_t tablet_id, const std::string& rowset_id) {
4700
        // Try to delete rowset data in background thread
4701
2
        int ret = worker_pool->submit_with_timeout(
4702
2
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4703
2
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4704
2
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4705
2
                        return;
4706
2
                    }
4707
2
                    std::vector<std::string> keys;
4708
2
                    {
4709
2
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4710
2
                        async_recycled_rowset_keys.push_back(std::move(key));
4711
2
                        if (async_recycled_rowset_keys.size() > 100) {
4712
2
                            keys.swap(async_recycled_rowset_keys);
4713
2
                        }
4714
2
                    }
4715
2
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4716
2
                    if (keys.empty()) return;
4717
2
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4718
2
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4719
2
                                     << instance_id_;
4720
2
                    } else {
4721
2
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4722
2
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4723
2
                                           num_recycled, start_time);
4724
2
                    }
4725
2
                },
4726
2
                0);
4727
2
        if (ret == 0) return 0;
4728
        // Submit task failed, delete rowset data in current thread
4729
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4730
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4731
0
            return -1;
4732
0
        }
4733
0
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
4734
0
            return -1;
4735
0
        }
4736
0
        rowset_keys.push_back(std::move(key));
4737
0
        return 0;
4738
0
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
4699
900
                                            int64_t tablet_id, const std::string& rowset_id) {
4700
        // Try to delete rowset data in background thread
4701
900
        int ret = worker_pool->submit_with_timeout(
4702
900
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4703
900
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4704
900
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4705
900
                        return;
4706
900
                    }
4707
900
                    std::vector<std::string> keys;
4708
900
                    {
4709
900
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4710
900
                        async_recycled_rowset_keys.push_back(std::move(key));
4711
900
                        if (async_recycled_rowset_keys.size() > 100) {
4712
900
                            keys.swap(async_recycled_rowset_keys);
4713
900
                        }
4714
900
                    }
4715
900
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4716
900
                    if (keys.empty()) return;
4717
900
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4718
900
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4719
900
                                     << instance_id_;
4720
900
                    } else {
4721
900
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4722
900
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4723
900
                                           num_recycled, start_time);
4724
900
                    }
4725
900
                },
4726
900
                0);
4727
900
        if (ret == 0) return 0;
4728
        // Submit task failed, delete rowset data in current thread
4729
91
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4730
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4731
0
            return -1;
4732
0
        }
4733
91
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
4734
0
            return -1;
4735
0
        }
4736
91
        rowset_keys.push_back(std::move(key));
4737
91
        return 0;
4738
91
    };
4739
4740
22
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
4741
4742
7.75k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
4743
7.75k
        ++num_scanned;
4744
7.75k
        total_rowset_key_size += k.size();
4745
7.75k
        total_rowset_value_size += v.size();
4746
7.75k
        RecycleRowsetPB rowset;
4747
7.75k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
4748
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4749
0
            return -1;
4750
0
        }
4751
4752
7.75k
        int64_t current_time = ::time(nullptr);
4753
7.75k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
4754
4755
7.75k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
4756
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
4757
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
4758
7.75k
        if (current_time < expiration) { // not expired
4759
0
            return 0;
4760
0
        }
4761
7.75k
        ++num_expired;
4762
7.75k
        expired_rowset_size += v.size();
4763
4764
7.75k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
4765
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
4766
                // in old version, keep this key-value pair and it needs to be checked manually
4767
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4768
0
                return -1;
4769
0
            }
4770
250
            if (rowset.resource_id().empty()) [[unlikely]] {
4771
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
4772
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
4773
0
                          << hex(k) << " value=" << proto_to_json(rowset);
4774
0
                rowset_keys.emplace_back(k);
4775
0
                return -1;
4776
0
            }
4777
            // decode rowset_id
4778
250
            auto k1 = k;
4779
250
            k1.remove_prefix(1);
4780
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
4781
250
            decode_key(&k1, &out);
4782
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
4783
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
4784
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
4785
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
4786
250
                      << " task_type=" << metrics_context.operation_type;
4787
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
4788
250
                                             rowset.tablet_id(), rowset_id) != 0) {
4789
0
                return -1;
4790
0
            }
4791
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
4792
250
            metrics_context.total_recycled_num++;
4793
250
            segment_metrics_context_.total_recycled_data_size +=
4794
250
                    rowset.rowset_meta().total_disk_size();
4795
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
4796
250
            return 0;
4797
250
        }
4798
4799
7.50k
        auto* rowset_meta = rowset.mutable_rowset_meta();
4800
7.50k
        if (config::enable_mark_delete_rowset_before_recycle) {
4801
7.50k
            int mark_ret = mark_rowset_as_recycled(txn_kv_.get(), instance_id_, k, rowset);
4802
7.50k
            if (mark_ret == -1) {
4803
0
                LOG(WARNING) << "failed to mark rowset as recycled, instance_id=" << instance_id_
4804
0
                             << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4805
0
                             << rowset_meta->start_version() << '-' << rowset_meta->end_version()
4806
0
                             << "]";
4807
0
                return -1;
4808
7.50k
            } else if (mark_ret == 1) {
4809
3.75k
                LOG(INFO)
4810
3.75k
                        << "rowset already marked as recycled, recycler will delete data and kv at "
4811
3.75k
                           "next turn, instance_id="
4812
3.75k
                        << instance_id_ << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4813
3.75k
                        << rowset_meta->start_version() << '-' << rowset_meta->end_version() << "]";
4814
3.75k
                return 0;
4815
3.75k
            }
4816
7.50k
        }
4817
4818
3.75k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
4819
3.75k
            LOG(INFO) << "begin to abort txn or job for related rowset, instance_id="
4820
3.75k
                      << instance_id_ << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4821
3.75k
                      << rowset_meta->start_version() << '-' << rowset_meta->end_version() << "]";
4822
4823
3.75k
            if (rowset_meta->end_version() != 1) {
4824
3.75k
                int ret = abort_txn_or_job_for_recycle(rowset);
4825
4826
3.75k
                if (ret != 0) {
4827
0
                    LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
4828
0
                                 << instance_id_ << " tablet_id=" << rowset.tablet_id()
4829
0
                                 << " version=[" << rowset_meta->start_version() << '-'
4830
0
                                 << rowset_meta->end_version() << "]";
4831
0
                    return ret;
4832
0
                }
4833
3.75k
            }
4834
3.75k
        }
4835
4836
        // TODO(plat1ko): check rowset not referenced
4837
3.75k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
4838
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
4839
0
                LOG_INFO("recycle rowset that has empty resource id");
4840
0
            } else {
4841
                // other situations, keep this key-value pair and it needs to be checked manually
4842
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4843
0
                return -1;
4844
0
            }
4845
0
        }
4846
3.75k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
4847
3.75k
                  << " tablet_id=" << rowset_meta->tablet_id()
4848
3.75k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
4849
3.75k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
4850
3.75k
                  << "] txn_id=" << rowset_meta->txn_id()
4851
3.75k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
4852
3.75k
                  << " rowset_meta_size=" << v.size()
4853
3.75k
                  << " creation_time=" << rowset_meta->creation_time()
4854
3.75k
                  << " task_type=" << metrics_context.operation_type;
4855
3.75k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
4856
            // unable to calculate file path, can only be deleted by rowset id prefix
4857
652
            num_prepare += 1;
4858
652
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
4859
652
                                             rowset_meta->tablet_id(),
4860
652
                                             rowset_meta->rowset_id_v2()) != 0) {
4861
0
                return -1;
4862
0
            }
4863
3.10k
        } else {
4864
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
4865
3.10k
            rowset_keys.emplace_back(k);
4866
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
4867
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
4868
3.10k
                ++num_empty_rowset;
4869
3.10k
            }
4870
3.10k
        }
4871
3.75k
        return 0;
4872
3.75k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
4742
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
4743
7
        ++num_scanned;
4744
7
        total_rowset_key_size += k.size();
4745
7
        total_rowset_value_size += v.size();
4746
7
        RecycleRowsetPB rowset;
4747
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
4748
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4749
0
            return -1;
4750
0
        }
4751
4752
7
        int64_t current_time = ::time(nullptr);
4753
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
4754
4755
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
4756
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
4757
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
4758
7
        if (current_time < expiration) { // not expired
4759
0
            return 0;
4760
0
        }
4761
7
        ++num_expired;
4762
7
        expired_rowset_size += v.size();
4763
4764
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
4765
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
4766
                // in old version, keep this key-value pair and it needs to be checked manually
4767
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4768
0
                return -1;
4769
0
            }
4770
0
            if (rowset.resource_id().empty()) [[unlikely]] {
4771
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
4772
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
4773
0
                          << hex(k) << " value=" << proto_to_json(rowset);
4774
0
                rowset_keys.emplace_back(k);
4775
0
                return -1;
4776
0
            }
4777
            // decode rowset_id
4778
0
            auto k1 = k;
4779
0
            k1.remove_prefix(1);
4780
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
4781
0
            decode_key(&k1, &out);
4782
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
4783
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
4784
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
4785
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
4786
0
                      << " task_type=" << metrics_context.operation_type;
4787
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
4788
0
                                             rowset.tablet_id(), rowset_id) != 0) {
4789
0
                return -1;
4790
0
            }
4791
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
4792
0
            metrics_context.total_recycled_num++;
4793
0
            segment_metrics_context_.total_recycled_data_size +=
4794
0
                    rowset.rowset_meta().total_disk_size();
4795
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
4796
0
            return 0;
4797
0
        }
4798
4799
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
4800
7
        if (config::enable_mark_delete_rowset_before_recycle) {
4801
7
            int mark_ret = mark_rowset_as_recycled(txn_kv_.get(), instance_id_, k, rowset);
4802
7
            if (mark_ret == -1) {
4803
0
                LOG(WARNING) << "failed to mark rowset as recycled, instance_id=" << instance_id_
4804
0
                             << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4805
0
                             << rowset_meta->start_version() << '-' << rowset_meta->end_version()
4806
0
                             << "]";
4807
0
                return -1;
4808
7
            } else if (mark_ret == 1) {
4809
5
                LOG(INFO)
4810
5
                        << "rowset already marked as recycled, recycler will delete data and kv at "
4811
5
                           "next turn, instance_id="
4812
5
                        << instance_id_ << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4813
5
                        << rowset_meta->start_version() << '-' << rowset_meta->end_version() << "]";
4814
5
                return 0;
4815
5
            }
4816
7
        }
4817
4818
2
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
4819
2
            LOG(INFO) << "begin to abort txn or job for related rowset, instance_id="
4820
2
                      << instance_id_ << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4821
2
                      << rowset_meta->start_version() << '-' << rowset_meta->end_version() << "]";
4822
4823
2
            if (rowset_meta->end_version() != 1) {
4824
2
                int ret = abort_txn_or_job_for_recycle(rowset);
4825
4826
2
                if (ret != 0) {
4827
0
                    LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
4828
0
                                 << instance_id_ << " tablet_id=" << rowset.tablet_id()
4829
0
                                 << " version=[" << rowset_meta->start_version() << '-'
4830
0
                                 << rowset_meta->end_version() << "]";
4831
0
                    return ret;
4832
0
                }
4833
2
            }
4834
2
        }
4835
4836
        // TODO(plat1ko): check rowset not referenced
4837
2
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
4838
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
4839
0
                LOG_INFO("recycle rowset that has empty resource id");
4840
0
            } else {
4841
                // other situations, keep this key-value pair and it needs to be checked manually
4842
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4843
0
                return -1;
4844
0
            }
4845
0
        }
4846
2
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
4847
2
                  << " tablet_id=" << rowset_meta->tablet_id()
4848
2
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
4849
2
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
4850
2
                  << "] txn_id=" << rowset_meta->txn_id()
4851
2
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
4852
2
                  << " rowset_meta_size=" << v.size()
4853
2
                  << " creation_time=" << rowset_meta->creation_time()
4854
2
                  << " task_type=" << metrics_context.operation_type;
4855
2
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
4856
            // unable to calculate file path, can only be deleted by rowset id prefix
4857
2
            num_prepare += 1;
4858
2
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
4859
2
                                             rowset_meta->tablet_id(),
4860
2
                                             rowset_meta->rowset_id_v2()) != 0) {
4861
0
                return -1;
4862
0
            }
4863
2
        } else {
4864
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
4865
0
            rowset_keys.emplace_back(k);
4866
0
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
4867
0
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
4868
0
                ++num_empty_rowset;
4869
0
            }
4870
0
        }
4871
2
        return 0;
4872
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
4742
7.75k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
4743
7.75k
        ++num_scanned;
4744
7.75k
        total_rowset_key_size += k.size();
4745
7.75k
        total_rowset_value_size += v.size();
4746
7.75k
        RecycleRowsetPB rowset;
4747
7.75k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
4748
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4749
0
            return -1;
4750
0
        }
4751
4752
7.75k
        int64_t current_time = ::time(nullptr);
4753
7.75k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
4754
4755
7.75k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
4756
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
4757
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
4758
7.75k
        if (current_time < expiration) { // not expired
4759
0
            return 0;
4760
0
        }
4761
7.75k
        ++num_expired;
4762
7.75k
        expired_rowset_size += v.size();
4763
4764
7.75k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
4765
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
4766
                // in old version, keep this key-value pair and it needs to be checked manually
4767
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4768
0
                return -1;
4769
0
            }
4770
250
            if (rowset.resource_id().empty()) [[unlikely]] {
4771
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
4772
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
4773
0
                          << hex(k) << " value=" << proto_to_json(rowset);
4774
0
                rowset_keys.emplace_back(k);
4775
0
                return -1;
4776
0
            }
4777
            // decode rowset_id
4778
250
            auto k1 = k;
4779
250
            k1.remove_prefix(1);
4780
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
4781
250
            decode_key(&k1, &out);
4782
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
4783
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
4784
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
4785
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
4786
250
                      << " task_type=" << metrics_context.operation_type;
4787
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
4788
250
                                             rowset.tablet_id(), rowset_id) != 0) {
4789
0
                return -1;
4790
0
            }
4791
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
4792
250
            metrics_context.total_recycled_num++;
4793
250
            segment_metrics_context_.total_recycled_data_size +=
4794
250
                    rowset.rowset_meta().total_disk_size();
4795
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
4796
250
            return 0;
4797
250
        }
4798
4799
7.50k
        auto* rowset_meta = rowset.mutable_rowset_meta();
4800
7.50k
        if (config::enable_mark_delete_rowset_before_recycle) {
4801
7.50k
            int mark_ret = mark_rowset_as_recycled(txn_kv_.get(), instance_id_, k, rowset);
4802
7.50k
            if (mark_ret == -1) {
4803
0
                LOG(WARNING) << "failed to mark rowset as recycled, instance_id=" << instance_id_
4804
0
                             << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4805
0
                             << rowset_meta->start_version() << '-' << rowset_meta->end_version()
4806
0
                             << "]";
4807
0
                return -1;
4808
7.50k
            } else if (mark_ret == 1) {
4809
3.75k
                LOG(INFO)
4810
3.75k
                        << "rowset already marked as recycled, recycler will delete data and kv at "
4811
3.75k
                           "next turn, instance_id="
4812
3.75k
                        << instance_id_ << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4813
3.75k
                        << rowset_meta->start_version() << '-' << rowset_meta->end_version() << "]";
4814
3.75k
                return 0;
4815
3.75k
            }
4816
7.50k
        }
4817
4818
3.75k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
4819
3.75k
            LOG(INFO) << "begin to abort txn or job for related rowset, instance_id="
4820
3.75k
                      << instance_id_ << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4821
3.75k
                      << rowset_meta->start_version() << '-' << rowset_meta->end_version() << "]";
4822
4823
3.75k
            if (rowset_meta->end_version() != 1) {
4824
3.75k
                int ret = abort_txn_or_job_for_recycle(rowset);
4825
4826
3.75k
                if (ret != 0) {
4827
0
                    LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
4828
0
                                 << instance_id_ << " tablet_id=" << rowset.tablet_id()
4829
0
                                 << " version=[" << rowset_meta->start_version() << '-'
4830
0
                                 << rowset_meta->end_version() << "]";
4831
0
                    return ret;
4832
0
                }
4833
3.75k
            }
4834
3.75k
        }
4835
4836
        // TODO(plat1ko): check rowset not referenced
4837
3.75k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
4838
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
4839
0
                LOG_INFO("recycle rowset that has empty resource id");
4840
0
            } else {
4841
                // other situations, keep this key-value pair and it needs to be checked manually
4842
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4843
0
                return -1;
4844
0
            }
4845
0
        }
4846
3.75k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
4847
3.75k
                  << " tablet_id=" << rowset_meta->tablet_id()
4848
3.75k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
4849
3.75k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
4850
3.75k
                  << "] txn_id=" << rowset_meta->txn_id()
4851
3.75k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
4852
3.75k
                  << " rowset_meta_size=" << v.size()
4853
3.75k
                  << " creation_time=" << rowset_meta->creation_time()
4854
3.75k
                  << " task_type=" << metrics_context.operation_type;
4855
3.75k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
4856
            // unable to calculate file path, can only be deleted by rowset id prefix
4857
650
            num_prepare += 1;
4858
650
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
4859
650
                                             rowset_meta->tablet_id(),
4860
650
                                             rowset_meta->rowset_id_v2()) != 0) {
4861
0
                return -1;
4862
0
            }
4863
3.10k
        } else {
4864
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
4865
3.10k
            rowset_keys.emplace_back(k);
4866
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
4867
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
4868
3.10k
                ++num_empty_rowset;
4869
3.10k
            }
4870
3.10k
        }
4871
3.75k
        return 0;
4872
3.75k
    };
4873
4874
49
    auto loop_done = [&]() -> int {
4875
49
        std::vector<std::string> rowset_keys_to_delete;
4876
        // rowset_id -> rowset_meta
4877
        // store rowset id and meta for statistics rs size when delete
4878
49
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
4879
49
        rowset_keys_to_delete.swap(rowset_keys);
4880
49
        rowsets_to_delete.swap(rowsets);
4881
49
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
4882
49
                             rowsets_to_delete = std::move(rowsets_to_delete)]() {
4883
49
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
4884
49
                                   metrics_context) != 0) {
4885
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
4886
0
                return;
4887
0
            }
4888
3.10k
            for (const auto& [_, rs] : rowsets_to_delete) {
4889
3.10k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
4890
0
                    return;
4891
0
                }
4892
3.10k
            }
4893
49
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
4894
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
4895
0
                return;
4896
0
            }
4897
49
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
4898
49
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
4882
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() {
4883
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
4884
7
                                   metrics_context) != 0) {
4885
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
4886
0
                return;
4887
0
            }
4888
7
            for (const auto& [_, rs] : rowsets_to_delete) {
4889
0
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
4890
0
                    return;
4891
0
                }
4892
0
            }
4893
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
4894
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
4895
0
                return;
4896
0
            }
4897
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
4898
7
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
4882
42
                             rowsets_to_delete = std::move(rowsets_to_delete)]() {
4883
42
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
4884
42
                                   metrics_context) != 0) {
4885
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
4886
0
                return;
4887
0
            }
4888
3.10k
            for (const auto& [_, rs] : rowsets_to_delete) {
4889
3.10k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
4890
0
                    return;
4891
0
                }
4892
3.10k
            }
4893
42
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
4894
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
4895
0
                return;
4896
0
            }
4897
42
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
4898
42
        });
4899
49
        return 0;
4900
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
4874
7
    auto loop_done = [&]() -> int {
4875
7
        std::vector<std::string> rowset_keys_to_delete;
4876
        // rowset_id -> rowset_meta
4877
        // store rowset id and meta for statistics rs size when delete
4878
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
4879
7
        rowset_keys_to_delete.swap(rowset_keys);
4880
7
        rowsets_to_delete.swap(rowsets);
4881
7
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
4882
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() {
4883
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
4884
7
                                   metrics_context) != 0) {
4885
7
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
4886
7
                return;
4887
7
            }
4888
7
            for (const auto& [_, rs] : rowsets_to_delete) {
4889
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
4890
7
                    return;
4891
7
                }
4892
7
            }
4893
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
4894
7
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
4895
7
                return;
4896
7
            }
4897
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
4898
7
        });
4899
7
        return 0;
4900
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
4874
42
    auto loop_done = [&]() -> int {
4875
42
        std::vector<std::string> rowset_keys_to_delete;
4876
        // rowset_id -> rowset_meta
4877
        // store rowset id and meta for statistics rs size when delete
4878
42
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
4879
42
        rowset_keys_to_delete.swap(rowset_keys);
4880
42
        rowsets_to_delete.swap(rowsets);
4881
42
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
4882
42
                             rowsets_to_delete = std::move(rowsets_to_delete)]() {
4883
42
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
4884
42
                                   metrics_context) != 0) {
4885
42
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
4886
42
                return;
4887
42
            }
4888
42
            for (const auto& [_, rs] : rowsets_to_delete) {
4889
42
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
4890
42
                    return;
4891
42
                }
4892
42
            }
4893
42
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
4894
42
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
4895
42
                return;
4896
42
            }
4897
42
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
4898
42
        });
4899
42
        return 0;
4900
42
    };
4901
4902
22
    if (config::enable_recycler_stats_metrics) {
4903
0
        scan_and_statistics_rowsets();
4904
0
    }
4905
    // recycle_func and loop_done for scan and recycle
4906
22
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
4907
22
                               std::move(loop_done));
4908
4909
22
    worker_pool->stop();
4910
4911
22
    if (!async_recycled_rowset_keys.empty()) {
4912
5
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
4913
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
4914
0
            return -1;
4915
5
        } else {
4916
5
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
4917
5
        }
4918
5
    }
4919
4920
    // Report final metrics after all concurrent tasks completed
4921
22
    segment_metrics_context_.report();
4922
22
    metrics_context.report();
4923
4924
22
    return ret;
4925
22
}
4926
4927
13
int InstanceRecycler::recycle_restore_jobs() {
4928
13
    const std::string task_name = "recycle_restore_jobs";
4929
13
    int64_t num_scanned = 0;
4930
13
    int64_t num_expired = 0;
4931
13
    int64_t num_recycled = 0;
4932
13
    int64_t num_aborted = 0;
4933
4934
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
4935
4936
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
4937
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
4938
13
    std::string restore_job_key0;
4939
13
    std::string restore_job_key1;
4940
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
4941
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
4942
4943
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
4944
4945
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
4946
13
    register_recycle_task(task_name, start_time);
4947
4948
13
    DORIS_CLOUD_DEFER {
4949
13
        unregister_recycle_task(task_name);
4950
13
        int64_t cost =
4951
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4952
13
        metrics_context.finish_report();
4953
4954
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
4955
13
                .tag("instance_id", instance_id_)
4956
13
                .tag("num_scanned", num_scanned)
4957
13
                .tag("num_expired", num_expired)
4958
13
                .tag("num_recycled", num_recycled)
4959
13
                .tag("num_aborted", num_aborted);
4960
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
4948
13
    DORIS_CLOUD_DEFER {
4949
13
        unregister_recycle_task(task_name);
4950
13
        int64_t cost =
4951
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4952
13
        metrics_context.finish_report();
4953
4954
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
4955
13
                .tag("instance_id", instance_id_)
4956
13
                .tag("num_scanned", num_scanned)
4957
13
                .tag("num_expired", num_expired)
4958
13
                .tag("num_recycled", num_recycled)
4959
13
                .tag("num_aborted", num_aborted);
4960
13
    };
4961
4962
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
4963
4964
13
    std::vector<std::string_view> restore_job_keys;
4965
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
4966
41
        ++num_scanned;
4967
41
        RestoreJobCloudPB restore_job_pb;
4968
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
4969
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
4970
0
            return -1;
4971
0
        }
4972
41
        int64_t expiration =
4973
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
4974
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
4975
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
4976
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
4977
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
4978
0
                   << " state=" << restore_job_pb.state();
4979
41
        int64_t current_time = ::time(nullptr);
4980
41
        if (current_time < expiration) { // not expired
4981
0
            return 0;
4982
0
        }
4983
41
        ++num_expired;
4984
4985
41
        int64_t tablet_id = restore_job_pb.tablet_id();
4986
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
4987
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
4988
4989
41
        std::unique_ptr<Transaction> txn;
4990
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
4991
41
        if (err != TxnErrorCode::TXN_OK) {
4992
0
            LOG_WARNING("failed to recycle restore job")
4993
0
                    .tag("err", err)
4994
0
                    .tag("tablet id", tablet_id)
4995
0
                    .tag("instance_id", instance_id_)
4996
0
                    .tag("reason", "failed to create txn");
4997
0
            return -1;
4998
0
        }
4999
5000
41
        std::string val;
5001
41
        err = txn->get(k, &val);
5002
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5003
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5004
0
            return 0;
5005
0
        }
5006
41
        if (err != TxnErrorCode::TXN_OK) {
5007
0
            LOG_WARNING("failed to get kv");
5008
0
            return -1;
5009
0
        }
5010
41
        restore_job_pb.Clear();
5011
41
        if (!restore_job_pb.ParseFromString(val)) {
5012
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5013
0
            return -1;
5014
0
        }
5015
5016
        // PREPARED or COMMITTED, change state to DROPPED and return
5017
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5018
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5019
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5020
0
            restore_job_pb.set_need_recycle_data(true);
5021
0
            txn->put(k, restore_job_pb.SerializeAsString());
5022
0
            err = txn->commit();
5023
0
            if (err != TxnErrorCode::TXN_OK) {
5024
0
                LOG_WARNING("failed to commit txn: {}", err);
5025
0
                return -1;
5026
0
            }
5027
0
            num_aborted++;
5028
0
            return 0;
5029
0
        }
5030
5031
        // Change state to RECYCLING
5032
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5033
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5034
21
            txn->put(k, restore_job_pb.SerializeAsString());
5035
21
            err = txn->commit();
5036
21
            if (err != TxnErrorCode::TXN_OK) {
5037
0
                LOG_WARNING("failed to commit txn: {}", err);
5038
0
                return -1;
5039
0
            }
5040
21
            return 0;
5041
21
        }
5042
5043
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5044
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5045
5046
        // Recycle all data associated with the restore job.
5047
        // This includes rowsets, segments, and related resources.
5048
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5049
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5050
0
            LOG_WARNING("failed to recycle tablet")
5051
0
                    .tag("tablet_id", tablet_id)
5052
0
                    .tag("instance_id", instance_id_);
5053
0
            return -1;
5054
0
        }
5055
5056
        // delete all restore job rowset kv
5057
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5058
5059
20
        err = txn->commit();
5060
20
        if (err != TxnErrorCode::TXN_OK) {
5061
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5062
0
                    .tag("err", err)
5063
0
                    .tag("tablet id", tablet_id)
5064
0
                    .tag("instance_id", instance_id_)
5065
0
                    .tag("reason", "failed to commit txn");
5066
0
            return -1;
5067
0
        }
5068
5069
20
        metrics_context.total_recycled_num = ++num_recycled;
5070
20
        metrics_context.report();
5071
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5072
20
        restore_job_keys.push_back(k);
5073
5074
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5075
20
                  << " tablet_id=" << tablet_id;
5076
20
        return 0;
5077
20
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
4965
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
4966
41
        ++num_scanned;
4967
41
        RestoreJobCloudPB restore_job_pb;
4968
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
4969
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
4970
0
            return -1;
4971
0
        }
4972
41
        int64_t expiration =
4973
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
4974
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
4975
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
4976
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
4977
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
4978
0
                   << " state=" << restore_job_pb.state();
4979
41
        int64_t current_time = ::time(nullptr);
4980
41
        if (current_time < expiration) { // not expired
4981
0
            return 0;
4982
0
        }
4983
41
        ++num_expired;
4984
4985
41
        int64_t tablet_id = restore_job_pb.tablet_id();
4986
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
4987
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
4988
4989
41
        std::unique_ptr<Transaction> txn;
4990
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
4991
41
        if (err != TxnErrorCode::TXN_OK) {
4992
0
            LOG_WARNING("failed to recycle restore job")
4993
0
                    .tag("err", err)
4994
0
                    .tag("tablet id", tablet_id)
4995
0
                    .tag("instance_id", instance_id_)
4996
0
                    .tag("reason", "failed to create txn");
4997
0
            return -1;
4998
0
        }
4999
5000
41
        std::string val;
5001
41
        err = txn->get(k, &val);
5002
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5003
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5004
0
            return 0;
5005
0
        }
5006
41
        if (err != TxnErrorCode::TXN_OK) {
5007
0
            LOG_WARNING("failed to get kv");
5008
0
            return -1;
5009
0
        }
5010
41
        restore_job_pb.Clear();
5011
41
        if (!restore_job_pb.ParseFromString(val)) {
5012
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5013
0
            return -1;
5014
0
        }
5015
5016
        // PREPARED or COMMITTED, change state to DROPPED and return
5017
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5018
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5019
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5020
0
            restore_job_pb.set_need_recycle_data(true);
5021
0
            txn->put(k, restore_job_pb.SerializeAsString());
5022
0
            err = txn->commit();
5023
0
            if (err != TxnErrorCode::TXN_OK) {
5024
0
                LOG_WARNING("failed to commit txn: {}", err);
5025
0
                return -1;
5026
0
            }
5027
0
            num_aborted++;
5028
0
            return 0;
5029
0
        }
5030
5031
        // Change state to RECYCLING
5032
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5033
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5034
21
            txn->put(k, restore_job_pb.SerializeAsString());
5035
21
            err = txn->commit();
5036
21
            if (err != TxnErrorCode::TXN_OK) {
5037
0
                LOG_WARNING("failed to commit txn: {}", err);
5038
0
                return -1;
5039
0
            }
5040
21
            return 0;
5041
21
        }
5042
5043
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5044
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5045
5046
        // Recycle all data associated with the restore job.
5047
        // This includes rowsets, segments, and related resources.
5048
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5049
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5050
0
            LOG_WARNING("failed to recycle tablet")
5051
0
                    .tag("tablet_id", tablet_id)
5052
0
                    .tag("instance_id", instance_id_);
5053
0
            return -1;
5054
0
        }
5055
5056
        // delete all restore job rowset kv
5057
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5058
5059
20
        err = txn->commit();
5060
20
        if (err != TxnErrorCode::TXN_OK) {
5061
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5062
0
                    .tag("err", err)
5063
0
                    .tag("tablet id", tablet_id)
5064
0
                    .tag("instance_id", instance_id_)
5065
0
                    .tag("reason", "failed to commit txn");
5066
0
            return -1;
5067
0
        }
5068
5069
20
        metrics_context.total_recycled_num = ++num_recycled;
5070
20
        metrics_context.report();
5071
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5072
20
        restore_job_keys.push_back(k);
5073
5074
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5075
20
                  << " tablet_id=" << tablet_id;
5076
20
        return 0;
5077
20
    };
5078
5079
13
    auto loop_done = [&restore_job_keys, this]() -> int {
5080
3
        if (restore_job_keys.empty()) return 0;
5081
1
        DORIS_CLOUD_DEFER {
5082
1
            restore_job_keys.clear();
5083
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5081
1
        DORIS_CLOUD_DEFER {
5082
1
            restore_job_keys.clear();
5083
1
        };
5084
5085
1
        std::unique_ptr<Transaction> txn;
5086
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5087
1
        if (err != TxnErrorCode::TXN_OK) {
5088
0
            LOG_WARNING("failed to recycle restore job")
5089
0
                    .tag("err", err)
5090
0
                    .tag("instance_id", instance_id_)
5091
0
                    .tag("reason", "failed to create txn");
5092
0
            return -1;
5093
0
        }
5094
20
        for (auto& k : restore_job_keys) {
5095
20
            txn->remove(k);
5096
20
        }
5097
1
        err = txn->commit();
5098
1
        if (err != TxnErrorCode::TXN_OK) {
5099
0
            LOG_WARNING("failed to recycle restore job")
5100
0
                    .tag("err", err)
5101
0
                    .tag("instance_id", instance_id_)
5102
0
                    .tag("reason", "failed to commit txn");
5103
0
            return -1;
5104
0
        }
5105
1
        return 0;
5106
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
5079
3
    auto loop_done = [&restore_job_keys, this]() -> int {
5080
3
        if (restore_job_keys.empty()) return 0;
5081
1
        DORIS_CLOUD_DEFER {
5082
1
            restore_job_keys.clear();
5083
1
        };
5084
5085
1
        std::unique_ptr<Transaction> txn;
5086
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5087
1
        if (err != TxnErrorCode::TXN_OK) {
5088
0
            LOG_WARNING("failed to recycle restore job")
5089
0
                    .tag("err", err)
5090
0
                    .tag("instance_id", instance_id_)
5091
0
                    .tag("reason", "failed to create txn");
5092
0
            return -1;
5093
0
        }
5094
20
        for (auto& k : restore_job_keys) {
5095
20
            txn->remove(k);
5096
20
        }
5097
1
        err = txn->commit();
5098
1
        if (err != TxnErrorCode::TXN_OK) {
5099
0
            LOG_WARNING("failed to recycle restore job")
5100
0
                    .tag("err", err)
5101
0
                    .tag("instance_id", instance_id_)
5102
0
                    .tag("reason", "failed to commit txn");
5103
0
            return -1;
5104
0
        }
5105
1
        return 0;
5106
1
    };
5107
5108
13
    if (config::enable_recycler_stats_metrics) {
5109
0
        scan_and_statistics_restore_jobs();
5110
0
    }
5111
5112
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
5113
13
                            std::move(loop_done));
5114
13
}
5115
5116
9
int InstanceRecycler::recycle_versioned_rowsets() {
5117
9
    const std::string task_name = "recycle_rowsets";
5118
9
    int64_t num_scanned = 0;
5119
9
    int64_t num_expired = 0;
5120
9
    int64_t num_prepare = 0;
5121
9
    int64_t num_compacted = 0;
5122
9
    int64_t num_empty_rowset = 0;
5123
9
    size_t total_rowset_key_size = 0;
5124
9
    size_t total_rowset_value_size = 0;
5125
9
    size_t expired_rowset_size = 0;
5126
9
    std::atomic_long num_recycled = 0;
5127
9
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5128
5129
9
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5130
9
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5131
9
    std::string recyc_rs_key0;
5132
9
    std::string recyc_rs_key1;
5133
9
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5134
9
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5135
5136
9
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5137
5138
9
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5139
9
    register_recycle_task(task_name, start_time);
5140
5141
9
    DORIS_CLOUD_DEFER {
5142
9
        unregister_recycle_task(task_name);
5143
9
        int64_t cost =
5144
9
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5145
9
        metrics_context.finish_report();
5146
9
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5147
9
                .tag("instance_id", instance_id_)
5148
9
                .tag("num_scanned", num_scanned)
5149
9
                .tag("num_expired", num_expired)
5150
9
                .tag("num_recycled", num_recycled)
5151
9
                .tag("num_recycled.prepare", num_prepare)
5152
9
                .tag("num_recycled.compacted", num_compacted)
5153
9
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5154
9
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5155
9
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5156
9
                .tag("expired_rowset_meta_size", expired_rowset_size);
5157
9
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
5141
9
    DORIS_CLOUD_DEFER {
5142
9
        unregister_recycle_task(task_name);
5143
9
        int64_t cost =
5144
9
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5145
9
        metrics_context.finish_report();
5146
9
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5147
9
                .tag("instance_id", instance_id_)
5148
9
                .tag("num_scanned", num_scanned)
5149
9
                .tag("num_expired", num_expired)
5150
9
                .tag("num_recycled", num_recycled)
5151
9
                .tag("num_recycled.prepare", num_prepare)
5152
9
                .tag("num_recycled.compacted", num_compacted)
5153
9
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5154
9
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5155
9
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5156
9
                .tag("expired_rowset_meta_size", expired_rowset_size);
5157
9
    };
5158
5159
9
    std::vector<std::string> orphan_rowset_keys;
5160
5161
    // Store keys of rowset recycled by background workers
5162
9
    std::mutex async_recycled_rowset_keys_mutex;
5163
9
    std::vector<std::string> async_recycled_rowset_keys;
5164
9
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5165
9
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5166
9
    worker_pool->start();
5167
9
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5168
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5169
        // Try to delete rowset data in background thread
5170
400
        int ret = worker_pool->submit_with_timeout(
5171
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5172
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5173
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5174
400
                        return;
5175
400
                    }
5176
                    // The async recycled rowsets are staled format or has not been used,
5177
                    // so we don't need to check the rowset ref count key.
5178
0
                    std::vector<std::string> keys;
5179
0
                    {
5180
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5181
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5182
0
                        if (async_recycled_rowset_keys.size() > 100) {
5183
0
                            keys.swap(async_recycled_rowset_keys);
5184
0
                        }
5185
0
                    }
5186
0
                    if (keys.empty()) return;
5187
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5188
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5189
0
                                     << instance_id_;
5190
0
                    } else {
5191
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5192
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5193
0
                                           num_recycled, start_time);
5194
0
                    }
5195
0
                },
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
5171
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5172
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5173
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5174
400
                        return;
5175
400
                    }
5176
                    // The async recycled rowsets are staled format or has not been used,
5177
                    // so we don't need to check the rowset ref count key.
5178
0
                    std::vector<std::string> keys;
5179
0
                    {
5180
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5181
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5182
0
                        if (async_recycled_rowset_keys.size() > 100) {
5183
0
                            keys.swap(async_recycled_rowset_keys);
5184
0
                        }
5185
0
                    }
5186
0
                    if (keys.empty()) return;
5187
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5188
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5189
0
                                     << instance_id_;
5190
0
                    } else {
5191
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5192
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5193
0
                                           num_recycled, start_time);
5194
0
                    }
5195
0
                },
5196
400
                0);
5197
400
        if (ret == 0) return 0;
5198
        // Submit task failed, delete rowset data in current thread
5199
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5200
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5201
0
            return -1;
5202
0
        }
5203
0
        orphan_rowset_keys.push_back(std::move(key));
5204
0
        return 0;
5205
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
5168
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5169
        // Try to delete rowset data in background thread
5170
400
        int ret = worker_pool->submit_with_timeout(
5171
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5172
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5173
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5174
400
                        return;
5175
400
                    }
5176
                    // The async recycled rowsets are staled format or has not been used,
5177
                    // so we don't need to check the rowset ref count key.
5178
400
                    std::vector<std::string> keys;
5179
400
                    {
5180
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5181
400
                        async_recycled_rowset_keys.push_back(std::move(key));
5182
400
                        if (async_recycled_rowset_keys.size() > 100) {
5183
400
                            keys.swap(async_recycled_rowset_keys);
5184
400
                        }
5185
400
                    }
5186
400
                    if (keys.empty()) return;
5187
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5188
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5189
400
                                     << instance_id_;
5190
400
                    } else {
5191
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5192
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5193
400
                                           num_recycled, start_time);
5194
400
                    }
5195
400
                },
5196
400
                0);
5197
400
        if (ret == 0) return 0;
5198
        // Submit task failed, delete rowset data in current thread
5199
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5200
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5201
0
            return -1;
5202
0
        }
5203
0
        orphan_rowset_keys.push_back(std::move(key));
5204
0
        return 0;
5205
0
    };
5206
5207
9
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5208
5209
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
5210
2.01k
        ++num_scanned;
5211
2.01k
        total_rowset_key_size += k.size();
5212
2.01k
        total_rowset_value_size += v.size();
5213
2.01k
        RecycleRowsetPB rowset;
5214
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5215
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5216
0
            return -1;
5217
0
        }
5218
5219
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5220
5221
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5222
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
5223
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5224
2.01k
        int64_t current_time = ::time(nullptr);
5225
2.01k
        if (current_time < final_expiration) { // not expired
5226
0
            return 0;
5227
0
        }
5228
2.01k
        ++num_expired;
5229
2.01k
        expired_rowset_size += v.size();
5230
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5231
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5232
                // in old version, keep this key-value pair and it needs to be checked manually
5233
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5234
0
                return -1;
5235
0
            }
5236
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5237
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5238
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5239
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5240
0
                orphan_rowset_keys.emplace_back(k);
5241
0
                return -1;
5242
0
            }
5243
            // decode rowset_id
5244
0
            auto k1 = k;
5245
0
            k1.remove_prefix(1);
5246
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5247
0
            decode_key(&k1, &out);
5248
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5249
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5250
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5251
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
5252
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5253
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5254
0
                return -1;
5255
0
            }
5256
0
            return 0;
5257
0
        }
5258
        // TODO(plat1ko): check rowset not referenced
5259
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
5260
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5261
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5262
0
                LOG_INFO("recycle rowset that has empty resource id");
5263
0
            } else {
5264
                // other situations, keep this key-value pair and it needs to be checked manually
5265
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5266
0
                return -1;
5267
0
            }
5268
0
        }
5269
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5270
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
5271
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5272
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5273
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
5274
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5275
2.01k
                  << " rowset_meta_size=" << v.size()
5276
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
5277
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5278
            // unable to calculate file path, can only be deleted by rowset id prefix
5279
400
            num_prepare += 1;
5280
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5281
400
                                             rowset_meta->tablet_id(),
5282
400
                                             rowset_meta->rowset_id_v2()) != 0) {
5283
0
                return -1;
5284
0
            }
5285
1.61k
        } else {
5286
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
5287
1.61k
            worker_pool->submit(
5288
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5289
                        // The load & compact rowset keys are recycled during recycling operation logs.
5290
1.61k
                        RowsetDeleteTask task;
5291
1.61k
                        task.rowset_meta = rowset_meta;
5292
1.61k
                        task.recycle_rowset_key = k;
5293
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
5294
1.60k
                            return;
5295
1.60k
                        }
5296
13
                        num_compacted += is_compacted;
5297
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5298
13
                        if (rowset_meta.num_segments() == 0) {
5299
0
                            ++num_empty_rowset;
5300
0
                        }
5301
13
                    });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlvE_clEv
Line
Count
Source
5288
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5289
                        // The load & compact rowset keys are recycled during recycling operation logs.
5290
1.61k
                        RowsetDeleteTask task;
5291
1.61k
                        task.rowset_meta = rowset_meta;
5292
1.61k
                        task.recycle_rowset_key = k;
5293
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
5294
1.60k
                            return;
5295
1.60k
                        }
5296
13
                        num_compacted += is_compacted;
5297
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5298
13
                        if (rowset_meta.num_segments() == 0) {
5299
0
                            ++num_empty_rowset;
5300
0
                        }
5301
13
                    });
5302
1.61k
        }
5303
2.01k
        return 0;
5304
2.01k
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5209
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
5210
2.01k
        ++num_scanned;
5211
2.01k
        total_rowset_key_size += k.size();
5212
2.01k
        total_rowset_value_size += v.size();
5213
2.01k
        RecycleRowsetPB rowset;
5214
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5215
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5216
0
            return -1;
5217
0
        }
5218
5219
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5220
5221
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5222
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
5223
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5224
2.01k
        int64_t current_time = ::time(nullptr);
5225
2.01k
        if (current_time < final_expiration) { // not expired
5226
0
            return 0;
5227
0
        }
5228
2.01k
        ++num_expired;
5229
2.01k
        expired_rowset_size += v.size();
5230
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5231
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5232
                // in old version, keep this key-value pair and it needs to be checked manually
5233
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5234
0
                return -1;
5235
0
            }
5236
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5237
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5238
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5239
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5240
0
                orphan_rowset_keys.emplace_back(k);
5241
0
                return -1;
5242
0
            }
5243
            // decode rowset_id
5244
0
            auto k1 = k;
5245
0
            k1.remove_prefix(1);
5246
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5247
0
            decode_key(&k1, &out);
5248
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5249
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5250
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5251
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
5252
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5253
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5254
0
                return -1;
5255
0
            }
5256
0
            return 0;
5257
0
        }
5258
        // TODO(plat1ko): check rowset not referenced
5259
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
5260
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5261
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5262
0
                LOG_INFO("recycle rowset that has empty resource id");
5263
0
            } else {
5264
                // other situations, keep this key-value pair and it needs to be checked manually
5265
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5266
0
                return -1;
5267
0
            }
5268
0
        }
5269
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5270
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
5271
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5272
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5273
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
5274
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5275
2.01k
                  << " rowset_meta_size=" << v.size()
5276
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
5277
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5278
            // unable to calculate file path, can only be deleted by rowset id prefix
5279
400
            num_prepare += 1;
5280
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5281
400
                                             rowset_meta->tablet_id(),
5282
400
                                             rowset_meta->rowset_id_v2()) != 0) {
5283
0
                return -1;
5284
0
            }
5285
1.61k
        } else {
5286
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
5287
1.61k
            worker_pool->submit(
5288
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5289
                        // The load & compact rowset keys are recycled during recycling operation logs.
5290
1.61k
                        RowsetDeleteTask task;
5291
1.61k
                        task.rowset_meta = rowset_meta;
5292
1.61k
                        task.recycle_rowset_key = k;
5293
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
5294
1.61k
                            return;
5295
1.61k
                        }
5296
1.61k
                        num_compacted += is_compacted;
5297
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5298
1.61k
                        if (rowset_meta.num_segments() == 0) {
5299
1.61k
                            ++num_empty_rowset;
5300
1.61k
                        }
5301
1.61k
                    });
5302
1.61k
        }
5303
2.01k
        return 0;
5304
2.01k
    };
5305
5306
9
    if (config::enable_recycler_stats_metrics) {
5307
0
        scan_and_statistics_rowsets();
5308
0
    }
5309
5310
9
    auto loop_done = [&]() -> int {
5311
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
5312
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5313
0
        }
5314
6
        orphan_rowset_keys.clear();
5315
6
        return 0;
5316
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
Line
Count
Source
5310
6
    auto loop_done = [&]() -> int {
5311
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
5312
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5313
0
        }
5314
6
        orphan_rowset_keys.clear();
5315
6
        return 0;
5316
6
    };
5317
5318
    // recycle_func and loop_done for scan and recycle
5319
9
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
5320
9
                               std::move(loop_done));
5321
5322
9
    worker_pool->stop();
5323
5324
9
    if (!async_recycled_rowset_keys.empty()) {
5325
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5326
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5327
0
            return -1;
5328
0
        } else {
5329
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5330
0
        }
5331
0
    }
5332
5333
    // Report final metrics after all concurrent tasks completed
5334
9
    segment_metrics_context_.report();
5335
9
    metrics_context.report();
5336
5337
9
    return ret;
5338
9
}
5339
5340
1.61k
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task) {
5341
1.61k
    constexpr int MAX_RETRY = 10;
5342
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
5343
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
5344
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
5345
1.61k
    std::string_view reference_instance_id = instance_id_;
5346
1.61k
    if (rowset_meta.has_reference_instance_id()) {
5347
8
        reference_instance_id = rowset_meta.reference_instance_id();
5348
8
    }
5349
5350
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
5351
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
5352
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
5353
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
5354
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
5355
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
5356
1.61k
        std::unique_ptr<Transaction> txn;
5357
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5358
1.61k
        if (err != TxnErrorCode::TXN_OK) {
5359
0
            LOG_WARNING("failed to create txn").tag("err", err);
5360
0
            return -1;
5361
0
        }
5362
5363
1.61k
        std::string rowset_ref_count_key =
5364
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
5365
1.61k
        int64_t ref_count = 0;
5366
1.61k
        {
5367
1.61k
            std::string value;
5368
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
5369
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
5370
                // This is the old version rowset, we could recycle it directly.
5371
1.60k
                ref_count = 1;
5372
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
5373
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
5374
0
                return -1;
5375
10
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
5376
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
5377
0
                return -1;
5378
0
            }
5379
1.61k
        }
5380
5381
1.61k
        if (ref_count == 1) {
5382
            // It would not be added since it is recycling.
5383
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
5384
1.60k
                LOG_WARNING("failed to delete rowset data");
5385
1.60k
                return -1;
5386
1.60k
            }
5387
5388
            // Reset the transaction to avoid timeout.
5389
10
            err = txn_kv_->create_txn(&txn);
5390
10
            if (err != TxnErrorCode::TXN_OK) {
5391
0
                LOG_WARNING("failed to create txn").tag("err", err);
5392
0
                return -1;
5393
0
            }
5394
10
            txn->remove(rowset_ref_count_key);
5395
10
            LOG_INFO("delete rowset data ref count key")
5396
10
                    .tag("txn_id", rowset_meta.txn_id())
5397
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
5398
5399
10
            std::string dbm_start_key =
5400
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
5401
10
            std::string dbm_end_key = meta_delete_bitmap_key(
5402
10
                    {reference_instance_id, tablet_id, rowset_id,
5403
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
5404
10
            txn->remove(dbm_start_key, dbm_end_key);
5405
10
            LOG_INFO("remove delete bitmap kv")
5406
10
                    .tag("begin", hex(dbm_start_key))
5407
10
                    .tag("end", hex(dbm_end_key));
5408
5409
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
5410
10
                    {reference_instance_id, tablet_id, rowset_id});
5411
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
5412
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
5413
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
5414
10
            LOG_INFO("remove versioned delete bitmap kv")
5415
10
                    .tag("begin", hex(versioned_dbm_start_key))
5416
10
                    .tag("end", hex(versioned_dbm_end_key));
5417
10
        } else {
5418
            // Decrease the rowset ref count.
5419
            //
5420
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
5421
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
5422
2
            txn->atomic_add(rowset_ref_count_key, -1);
5423
2
            LOG_INFO("decrease rowset data ref count")
5424
2
                    .tag("txn_id", rowset_meta.txn_id())
5425
2
                    .tag("ref_count", ref_count - 1)
5426
2
                    .tag("ref_count_key", hex(rowset_ref_count_key));
5427
2
        }
5428
5429
12
        if (!task.versioned_rowset_key.empty()) {
5430
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
5431
0
                                                          task.versionstamp);
5432
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
5433
0
        }
5434
5435
12
        if (!task.non_versioned_rowset_key.empty()) {
5436
0
            txn->remove(task.non_versioned_rowset_key);
5437
0
            LOG_INFO("remove non versioned rowset key")
5438
0
                    .tag("key", hex(task.non_versioned_rowset_key));
5439
0
        }
5440
5441
        // empty when recycle ref rowsets for deleted instance
5442
13
        if (!task.recycle_rowset_key.empty()) {
5443
13
            txn->remove(task.recycle_rowset_key);
5444
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
5445
13
        }
5446
5447
12
        err = txn->commit();
5448
12
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
5449
            // The rowset ref count key has been changed, we need to retry.
5450
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
5451
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
5452
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
5453
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
5454
0
            continue;
5455
12
        } else if (err != TxnErrorCode::TXN_OK) {
5456
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
5457
0
            return -1;
5458
0
        }
5459
12
        LOG_INFO("recycle rowset meta and data success");
5460
12
        return 0;
5461
12
    }
5462
1
    LOG_WARNING("failed to recycle rowset meta and data after retry")
5463
1
            .tag("tablet_id", tablet_id)
5464
1
            .tag("rowset_id", rowset_id)
5465
1
            .tag("retry", MAX_RETRY);
5466
1
    return -1;
5467
1.61k
}
5468
5469
29
int InstanceRecycler::recycle_tmp_rowsets() {
5470
29
    const std::string task_name = "recycle_tmp_rowsets";
5471
29
    int64_t num_scanned = 0;
5472
29
    int64_t num_expired = 0;
5473
29
    std::atomic_long num_recycled = 0;
5474
29
    size_t expired_rowset_size = 0;
5475
29
    size_t total_rowset_key_size = 0;
5476
29
    size_t total_rowset_value_size = 0;
5477
29
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5478
5479
29
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
5480
29
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
5481
29
    std::string tmp_rs_key0;
5482
29
    std::string tmp_rs_key1;
5483
29
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
5484
29
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
5485
5486
29
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
5487
5488
29
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5489
29
    register_recycle_task(task_name, start_time);
5490
5491
29
    DORIS_CLOUD_DEFER {
5492
29
        unregister_recycle_task(task_name);
5493
29
        int64_t cost =
5494
29
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5495
29
        metrics_context.finish_report();
5496
29
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5497
29
                .tag("instance_id", instance_id_)
5498
29
                .tag("num_scanned", num_scanned)
5499
29
                .tag("num_expired", num_expired)
5500
29
                .tag("num_recycled", num_recycled)
5501
29
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5502
29
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5503
29
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5504
29
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
5491
12
    DORIS_CLOUD_DEFER {
5492
12
        unregister_recycle_task(task_name);
5493
12
        int64_t cost =
5494
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5495
12
        metrics_context.finish_report();
5496
12
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5497
12
                .tag("instance_id", instance_id_)
5498
12
                .tag("num_scanned", num_scanned)
5499
12
                .tag("num_expired", num_expired)
5500
12
                .tag("num_recycled", num_recycled)
5501
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5502
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5503
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5504
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
5491
17
    DORIS_CLOUD_DEFER {
5492
17
        unregister_recycle_task(task_name);
5493
17
        int64_t cost =
5494
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5495
17
        metrics_context.finish_report();
5496
17
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5497
17
                .tag("instance_id", instance_id_)
5498
17
                .tag("num_scanned", num_scanned)
5499
17
                .tag("num_expired", num_expired)
5500
17
                .tag("num_recycled", num_recycled)
5501
17
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5502
17
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5503
17
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5504
17
    };
5505
5506
    // Elements in `tmp_rowset_keys` has the same lifetime as `it`
5507
5508
29
    std::vector<std::string> tmp_rowset_keys;
5509
29
    std::vector<std::string> tmp_rowset_ref_count_keys;
5510
5511
    // rowset_id -> rowset_meta
5512
    // store tmp_rowset id and meta for statistics rs size when delete
5513
29
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
5514
29
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5515
29
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
5516
29
    worker_pool->start();
5517
5518
29
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5519
5520
29
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &tmp_rowsets,
5521
29
                             &expired_rowset_size, &total_rowset_key_size, &total_rowset_value_size,
5522
29
                             &earlest_ts, &tmp_rowset_ref_count_keys, this,
5523
102k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5524
102k
        ++num_scanned;
5525
102k
        total_rowset_key_size += k.size();
5526
102k
        total_rowset_value_size += v.size();
5527
102k
        doris::RowsetMetaCloudPB rowset;
5528
102k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5529
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5530
0
            return -1;
5531
0
        }
5532
102k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5533
102k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5534
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5535
0
                   << " txn_expiration=" << rowset.txn_expiration()
5536
0
                   << " rowset_creation_time=" << rowset.creation_time();
5537
102k
        int64_t current_time = ::time(nullptr);
5538
102k
        if (current_time < expiration) { // not expired
5539
0
            return 0;
5540
0
        }
5541
5542
102k
        if (config::enable_mark_delete_rowset_before_recycle) {
5543
102k
            int mark_ret = mark_rowset_as_recycled(txn_kv_.get(), instance_id_, k, rowset);
5544
102k
            if (mark_ret == -1) {
5545
0
                LOG(WARNING) << "failed to mark rowset as recycled, instance_id=" << instance_id_
5546
0
                             << " tablet_id=" << rowset.tablet_id() << " version=["
5547
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5548
0
                return -1;
5549
102k
            } else if (mark_ret == 1) {
5550
51.0k
                LOG(INFO)
5551
51.0k
                        << "rowset already marked as recycled, recycler will delete data and kv at "
5552
51.0k
                           "next turn, instance_id="
5553
51.0k
                        << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5554
51.0k
                        << rowset.start_version() << '-' << rowset.end_version() << "]";
5555
51.0k
                return 0;
5556
51.0k
            }
5557
102k
        }
5558
5559
51.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
5560
51.0k
            LOG(INFO) << "begin to abort txn or job for related rowset, instance_id="
5561
51.0k
                      << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5562
51.0k
                      << rowset.start_version() << '-' << rowset.end_version() << "]";
5563
5564
51.0k
            int ret = abort_txn_or_job_for_recycle(rowset);
5565
51.0k
            if (ret != 0) {
5566
0
                LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
5567
0
                             << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5568
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5569
0
                return ret;
5570
0
            }
5571
51.0k
        }
5572
5573
51.0k
        ++num_expired;
5574
51.0k
        expired_rowset_size += v.size();
5575
51.0k
        if (!rowset.has_resource_id()) {
5576
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
5577
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
5578
0
                return -1;
5579
0
            }
5580
            // might be a delete pred rowset
5581
0
            tmp_rowset_keys.emplace_back(k);
5582
0
            return 0;
5583
0
        }
5584
        // TODO(plat1ko): check rowset not referenced
5585
51.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5586
51.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
5587
51.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
5588
51.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
5589
51.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
5590
51.0k
                  << " num_expired=" << num_expired
5591
51.0k
                  << " task_type=" << metrics_context.operation_type;
5592
5593
51.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
5594
        // Remove the rowset ref count key directly since it has not been used.
5595
51.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
5596
51.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
5597
51.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
5598
51.0k
                  << "key=" << hex(rowset_ref_count_key);
5599
51.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
5600
5601
51.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
5602
51.0k
        return 0;
5603
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5523
16
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5524
16
        ++num_scanned;
5525
16
        total_rowset_key_size += k.size();
5526
16
        total_rowset_value_size += v.size();
5527
16
        doris::RowsetMetaCloudPB rowset;
5528
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5529
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5530
0
            return -1;
5531
0
        }
5532
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5533
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5534
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5535
0
                   << " txn_expiration=" << rowset.txn_expiration()
5536
0
                   << " rowset_creation_time=" << rowset.creation_time();
5537
16
        int64_t current_time = ::time(nullptr);
5538
16
        if (current_time < expiration) { // not expired
5539
0
            return 0;
5540
0
        }
5541
5542
16
        if (config::enable_mark_delete_rowset_before_recycle) {
5543
16
            int mark_ret = mark_rowset_as_recycled(txn_kv_.get(), instance_id_, k, rowset);
5544
16
            if (mark_ret == -1) {
5545
0
                LOG(WARNING) << "failed to mark rowset as recycled, instance_id=" << instance_id_
5546
0
                             << " tablet_id=" << rowset.tablet_id() << " version=["
5547
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5548
0
                return -1;
5549
16
            } else if (mark_ret == 1) {
5550
9
                LOG(INFO)
5551
9
                        << "rowset already marked as recycled, recycler will delete data and kv at "
5552
9
                           "next turn, instance_id="
5553
9
                        << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5554
9
                        << rowset.start_version() << '-' << rowset.end_version() << "]";
5555
9
                return 0;
5556
9
            }
5557
16
        }
5558
5559
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
5560
7
            LOG(INFO) << "begin to abort txn or job for related rowset, instance_id="
5561
7
                      << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5562
7
                      << rowset.start_version() << '-' << rowset.end_version() << "]";
5563
5564
7
            int ret = abort_txn_or_job_for_recycle(rowset);
5565
7
            if (ret != 0) {
5566
0
                LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
5567
0
                             << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5568
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5569
0
                return ret;
5570
0
            }
5571
7
        }
5572
5573
7
        ++num_expired;
5574
7
        expired_rowset_size += v.size();
5575
7
        if (!rowset.has_resource_id()) {
5576
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
5577
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
5578
0
                return -1;
5579
0
            }
5580
            // might be a delete pred rowset
5581
0
            tmp_rowset_keys.emplace_back(k);
5582
0
            return 0;
5583
0
        }
5584
        // TODO(plat1ko): check rowset not referenced
5585
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5586
7
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
5587
7
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
5588
7
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
5589
7
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
5590
7
                  << " num_expired=" << num_expired
5591
7
                  << " task_type=" << metrics_context.operation_type;
5592
5593
7
        tmp_rowset_keys.emplace_back(k.data(), k.size());
5594
        // Remove the rowset ref count key directly since it has not been used.
5595
7
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
5596
7
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
5597
7
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
5598
7
                  << "key=" << hex(rowset_ref_count_key);
5599
7
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
5600
5601
7
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
5602
7
        return 0;
5603
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5523
102k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5524
102k
        ++num_scanned;
5525
102k
        total_rowset_key_size += k.size();
5526
102k
        total_rowset_value_size += v.size();
5527
102k
        doris::RowsetMetaCloudPB rowset;
5528
102k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5529
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5530
0
            return -1;
5531
0
        }
5532
102k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5533
102k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5534
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5535
0
                   << " txn_expiration=" << rowset.txn_expiration()
5536
0
                   << " rowset_creation_time=" << rowset.creation_time();
5537
102k
        int64_t current_time = ::time(nullptr);
5538
102k
        if (current_time < expiration) { // not expired
5539
0
            return 0;
5540
0
        }
5541
5542
102k
        if (config::enable_mark_delete_rowset_before_recycle) {
5543
102k
            int mark_ret = mark_rowset_as_recycled(txn_kv_.get(), instance_id_, k, rowset);
5544
102k
            if (mark_ret == -1) {
5545
0
                LOG(WARNING) << "failed to mark rowset as recycled, instance_id=" << instance_id_
5546
0
                             << " tablet_id=" << rowset.tablet_id() << " version=["
5547
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5548
0
                return -1;
5549
102k
            } else if (mark_ret == 1) {
5550
51.0k
                LOG(INFO)
5551
51.0k
                        << "rowset already marked as recycled, recycler will delete data and kv at "
5552
51.0k
                           "next turn, instance_id="
5553
51.0k
                        << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5554
51.0k
                        << rowset.start_version() << '-' << rowset.end_version() << "]";
5555
51.0k
                return 0;
5556
51.0k
            }
5557
102k
        }
5558
5559
51.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
5560
51.0k
            LOG(INFO) << "begin to abort txn or job for related rowset, instance_id="
5561
51.0k
                      << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5562
51.0k
                      << rowset.start_version() << '-' << rowset.end_version() << "]";
5563
5564
51.0k
            int ret = abort_txn_or_job_for_recycle(rowset);
5565
51.0k
            if (ret != 0) {
5566
0
                LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
5567
0
                             << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5568
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5569
0
                return ret;
5570
0
            }
5571
51.0k
        }
5572
5573
51.0k
        ++num_expired;
5574
51.0k
        expired_rowset_size += v.size();
5575
51.0k
        if (!rowset.has_resource_id()) {
5576
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
5577
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
5578
0
                return -1;
5579
0
            }
5580
            // might be a delete pred rowset
5581
0
            tmp_rowset_keys.emplace_back(k);
5582
0
            return 0;
5583
0
        }
5584
        // TODO(plat1ko): check rowset not referenced
5585
51.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5586
51.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
5587
51.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
5588
51.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
5589
51.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
5590
51.0k
                  << " num_expired=" << num_expired
5591
51.0k
                  << " task_type=" << metrics_context.operation_type;
5592
5593
51.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
5594
        // Remove the rowset ref count key directly since it has not been used.
5595
51.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
5596
51.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
5597
51.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
5598
51.0k
                  << "key=" << hex(rowset_ref_count_key);
5599
51.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
5600
5601
51.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
5602
51.0k
        return 0;
5603
51.0k
    };
5604
5605
    // TODO bacth delete
5606
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5607
51.0k
        std::string dbm_start_key =
5608
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5609
51.0k
        std::string dbm_end_key = dbm_start_key;
5610
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
5611
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5612
51.0k
        if (ret != 0) {
5613
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5614
0
                         << instance_id_ << ", tablet_id=" << tablet_id
5615
0
                         << ", rowset_id=" << rowset_id;
5616
0
        }
5617
51.0k
        return ret;
5618
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5606
7
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5607
7
        std::string dbm_start_key =
5608
7
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5609
7
        std::string dbm_end_key = dbm_start_key;
5610
7
        encode_int64(INT64_MAX, &dbm_end_key);
5611
7
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5612
7
        if (ret != 0) {
5613
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5614
0
                         << instance_id_ << ", tablet_id=" << tablet_id
5615
0
                         << ", rowset_id=" << rowset_id;
5616
0
        }
5617
7
        return ret;
5618
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5606
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5607
51.0k
        std::string dbm_start_key =
5608
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5609
51.0k
        std::string dbm_end_key = dbm_start_key;
5610
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
5611
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5612
51.0k
        if (ret != 0) {
5613
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5614
0
                         << instance_id_ << ", tablet_id=" << tablet_id
5615
0
                         << ", rowset_id=" << rowset_id;
5616
0
        }
5617
51.0k
        return ret;
5618
51.0k
    };
5619
5620
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5621
51.0k
        auto delete_bitmap_start =
5622
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
5623
51.0k
        auto delete_bitmap_end =
5624
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
5625
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
5626
51.0k
        if (ret != 0) {
5627
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
5628
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
5629
0
        }
5630
51.0k
        return ret;
5631
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5620
7
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5621
7
        auto delete_bitmap_start =
5622
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
5623
7
        auto delete_bitmap_end =
5624
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
5625
7
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
5626
7
        if (ret != 0) {
5627
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
5628
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
5629
0
        }
5630
7
        return ret;
5631
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5620
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5621
51.0k
        auto delete_bitmap_start =
5622
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
5623
51.0k
        auto delete_bitmap_end =
5624
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
5625
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
5626
51.0k
        if (ret != 0) {
5627
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
5628
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
5629
0
        }
5630
51.0k
        return ret;
5631
51.0k
    };
5632
5633
29
    auto loop_done = [&]() -> int {
5634
26
        DORIS_CLOUD_DEFER {
5635
26
            tmp_rowset_keys.clear();
5636
26
            tmp_rowsets.clear();
5637
26
            tmp_rowset_ref_count_keys.clear();
5638
26
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5634
12
        DORIS_CLOUD_DEFER {
5635
12
            tmp_rowset_keys.clear();
5636
12
            tmp_rowsets.clear();
5637
12
            tmp_rowset_ref_count_keys.clear();
5638
12
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5634
14
        DORIS_CLOUD_DEFER {
5635
14
            tmp_rowset_keys.clear();
5636
14
            tmp_rowsets.clear();
5637
14
            tmp_rowset_ref_count_keys.clear();
5638
14
        };
5639
26
        worker_pool->submit([&, tmp_rowset_keys_to_delete = tmp_rowset_keys,
5640
26
                             tmp_rowsets_to_delete = tmp_rowsets,
5641
26
                             tmp_rowset_ref_count_keys_to_delete = tmp_rowset_ref_count_keys]() {
5642
26
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5643
26
                                   metrics_context) != 0) {
5644
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5645
0
                return;
5646
0
            }
5647
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5648
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5649
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5650
0
                                 << rs.ShortDebugString();
5651
0
                    return;
5652
0
                }
5653
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5654
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5655
0
                                 << rs.ShortDebugString();
5656
0
                    return;
5657
0
                }
5658
51.0k
            }
5659
26
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5660
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5661
0
                return;
5662
0
            }
5663
26
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5664
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5665
0
                return;
5666
0
            }
5667
26
            num_recycled += tmp_rowset_keys.size();
5668
26
            return;
5669
26
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
5641
12
                             tmp_rowset_ref_count_keys_to_delete = tmp_rowset_ref_count_keys]() {
5642
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5643
12
                                   metrics_context) != 0) {
5644
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5645
0
                return;
5646
0
            }
5647
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5648
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5649
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5650
0
                                 << rs.ShortDebugString();
5651
0
                    return;
5652
0
                }
5653
7
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5654
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5655
0
                                 << rs.ShortDebugString();
5656
0
                    return;
5657
0
                }
5658
7
            }
5659
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5660
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5661
0
                return;
5662
0
            }
5663
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5664
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5665
0
                return;
5666
0
            }
5667
12
            num_recycled += tmp_rowset_keys.size();
5668
12
            return;
5669
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
5641
14
                             tmp_rowset_ref_count_keys_to_delete = tmp_rowset_ref_count_keys]() {
5642
14
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5643
14
                                   metrics_context) != 0) {
5644
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5645
0
                return;
5646
0
            }
5647
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5648
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5649
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5650
0
                                 << rs.ShortDebugString();
5651
0
                    return;
5652
0
                }
5653
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5654
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5655
0
                                 << rs.ShortDebugString();
5656
0
                    return;
5657
0
                }
5658
51.0k
            }
5659
14
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5660
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5661
0
                return;
5662
0
            }
5663
14
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5664
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5665
0
                return;
5666
0
            }
5667
14
            num_recycled += tmp_rowset_keys.size();
5668
14
            return;
5669
14
        });
5670
26
        return 0;
5671
26
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
5633
12
    auto loop_done = [&]() -> int {
5634
12
        DORIS_CLOUD_DEFER {
5635
12
            tmp_rowset_keys.clear();
5636
12
            tmp_rowsets.clear();
5637
12
            tmp_rowset_ref_count_keys.clear();
5638
12
        };
5639
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = tmp_rowset_keys,
5640
12
                             tmp_rowsets_to_delete = tmp_rowsets,
5641
12
                             tmp_rowset_ref_count_keys_to_delete = tmp_rowset_ref_count_keys]() {
5642
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5643
12
                                   metrics_context) != 0) {
5644
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5645
12
                return;
5646
12
            }
5647
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5648
12
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5649
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5650
12
                                 << rs.ShortDebugString();
5651
12
                    return;
5652
12
                }
5653
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5654
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5655
12
                                 << rs.ShortDebugString();
5656
12
                    return;
5657
12
                }
5658
12
            }
5659
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5660
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5661
12
                return;
5662
12
            }
5663
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5664
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5665
12
                return;
5666
12
            }
5667
12
            num_recycled += tmp_rowset_keys.size();
5668
12
            return;
5669
12
        });
5670
12
        return 0;
5671
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
5633
14
    auto loop_done = [&]() -> int {
5634
14
        DORIS_CLOUD_DEFER {
5635
14
            tmp_rowset_keys.clear();
5636
14
            tmp_rowsets.clear();
5637
14
            tmp_rowset_ref_count_keys.clear();
5638
14
        };
5639
14
        worker_pool->submit([&, tmp_rowset_keys_to_delete = tmp_rowset_keys,
5640
14
                             tmp_rowsets_to_delete = tmp_rowsets,
5641
14
                             tmp_rowset_ref_count_keys_to_delete = tmp_rowset_ref_count_keys]() {
5642
14
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5643
14
                                   metrics_context) != 0) {
5644
14
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5645
14
                return;
5646
14
            }
5647
14
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5648
14
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5649
14
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5650
14
                                 << rs.ShortDebugString();
5651
14
                    return;
5652
14
                }
5653
14
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5654
14
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5655
14
                                 << rs.ShortDebugString();
5656
14
                    return;
5657
14
                }
5658
14
            }
5659
14
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5660
14
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5661
14
                return;
5662
14
            }
5663
14
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5664
14
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5665
14
                return;
5666
14
            }
5667
14
            num_recycled += tmp_rowset_keys.size();
5668
14
            return;
5669
14
        });
5670
14
        return 0;
5671
14
    };
5672
5673
29
    if (config::enable_recycler_stats_metrics) {
5674
0
        scan_and_statistics_tmp_rowsets();
5675
0
    }
5676
    // recycle_func and loop_done for scan and recycle
5677
29
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
5678
29
                               std::move(loop_done));
5679
5680
29
    worker_pool->stop();
5681
5682
    // Report final metrics after all concurrent tasks completed
5683
29
    segment_metrics_context_.report();
5684
29
    metrics_context.report();
5685
5686
29
    return ret;
5687
29
}
5688
5689
int InstanceRecycler::scan_and_recycle(
5690
        std::string begin, std::string_view end,
5691
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
5692
255
        std::function<int()> loop_done) {
5693
255
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
5694
255
    int ret = 0;
5695
255
    int64_t cnt = 0;
5696
255
    int get_range_retried = 0;
5697
255
    std::string err;
5698
256
    DORIS_CLOUD_DEFER_COPY(begin, end) {
5699
256
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
5700
256
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
5701
256
                  << " ret=" << ret << " err=" << err;
5702
256
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
5698
31
    DORIS_CLOUD_DEFER_COPY(begin, end) {
5699
31
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
5700
31
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
5701
31
                  << " ret=" << ret << " err=" << err;
5702
31
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
5698
225
    DORIS_CLOUD_DEFER_COPY(begin, end) {
5699
225
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
5700
225
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
5701
225
                  << " ret=" << ret << " err=" << err;
5702
225
    };
5703
5704
255
    std::unique_ptr<RangeGetIterator> it;
5705
308
    do {
5706
308
        if (get_range_retried > 1000) {
5707
0
            err = "txn_get exceeds max retry, may not scan all keys";
5708
0
            ret = -1;
5709
0
            return -1;
5710
0
        }
5711
308
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
5712
308
        if (get_ret != 0) { // txn kv may complain "Request for future version"
5713
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
5714
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
5715
0
                         << " get_range_retried=" << get_range_retried;
5716
0
            ++get_range_retried;
5717
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
5718
0
            continue; // try again
5719
0
        }
5720
308
        if (!it->has_next()) {
5721
134
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
5722
134
            break; // scan finished
5723
134
        }
5724
150k
        while (it->has_next()) {
5725
150k
            ++cnt;
5726
            // recycle corresponding resources
5727
150k
            auto [k, v] = it->next();
5728
150k
            if (!it->has_next()) {
5729
175
                begin = k;
5730
175
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
5731
175
            }
5732
            // if we want to continue scanning, the recycle_func should not return non-zero
5733
150k
            if (recycle_func(k, v) != 0) {
5734
4.00k
                err = "recycle_func error";
5735
4.00k
                ret = -1;
5736
4.00k
            }
5737
150k
        }
5738
174
        begin.push_back('\x00'); // Update to next smallest key for iteration
5739
        // if we want to continue scanning, the recycle_func should not return non-zero
5740
174
        if (loop_done && loop_done() != 0) {
5741
4
            err = "loop_done error";
5742
4
            ret = -1;
5743
4
        }
5744
174
    } while (it->more() && !stopped());
5745
255
    return ret;
5746
255
}
5747
5748
19
int InstanceRecycler::abort_timeout_txn() {
5749
19
    const std::string task_name = "abort_timeout_txn";
5750
19
    int64_t num_scanned = 0;
5751
19
    int64_t num_timeout = 0;
5752
19
    int64_t num_abort = 0;
5753
19
    int64_t num_advance = 0;
5754
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5755
5756
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
5757
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
5758
19
    std::string begin_txn_running_key;
5759
19
    std::string end_txn_running_key;
5760
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
5761
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
5762
5763
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
5764
5765
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5766
19
    register_recycle_task(task_name, start_time);
5767
5768
19
    DORIS_CLOUD_DEFER {
5769
19
        unregister_recycle_task(task_name);
5770
19
        int64_t cost =
5771
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5772
19
        metrics_context.finish_report();
5773
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
5774
19
                .tag("instance_id", instance_id_)
5775
19
                .tag("num_scanned", num_scanned)
5776
19
                .tag("num_timeout", num_timeout)
5777
19
                .tag("num_abort", num_abort)
5778
19
                .tag("num_advance", num_advance);
5779
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
5768
3
    DORIS_CLOUD_DEFER {
5769
3
        unregister_recycle_task(task_name);
5770
3
        int64_t cost =
5771
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5772
3
        metrics_context.finish_report();
5773
3
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
5774
3
                .tag("instance_id", instance_id_)
5775
3
                .tag("num_scanned", num_scanned)
5776
3
                .tag("num_timeout", num_timeout)
5777
3
                .tag("num_abort", num_abort)
5778
3
                .tag("num_advance", num_advance);
5779
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
5768
16
    DORIS_CLOUD_DEFER {
5769
16
        unregister_recycle_task(task_name);
5770
16
        int64_t cost =
5771
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5772
16
        metrics_context.finish_report();
5773
16
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
5774
16
                .tag("instance_id", instance_id_)
5775
16
                .tag("num_scanned", num_scanned)
5776
16
                .tag("num_timeout", num_timeout)
5777
16
                .tag("num_abort", num_abort)
5778
16
                .tag("num_advance", num_advance);
5779
16
    };
5780
5781
19
    int64_t current_time =
5782
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
5783
5784
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
5785
19
                                  &current_time, &metrics_context,
5786
19
                                  this](std::string_view k, std::string_view v) -> int {
5787
9
        ++num_scanned;
5788
5789
9
        std::unique_ptr<Transaction> txn;
5790
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5791
9
        if (err != TxnErrorCode::TXN_OK) {
5792
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
5793
0
            return -1;
5794
0
        }
5795
9
        std::string_view k1 = k;
5796
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
5797
9
        k1.remove_prefix(1); // Remove key space
5798
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5799
9
        if (decode_key(&k1, &out) != 0) {
5800
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
5801
0
            return -1;
5802
0
        }
5803
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
5804
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
5805
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
5806
        // Update txn_info
5807
9
        std::string txn_inf_key, txn_inf_val;
5808
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
5809
9
        err = txn->get(txn_inf_key, &txn_inf_val);
5810
9
        if (err != TxnErrorCode::TXN_OK) {
5811
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
5812
0
            return -1;
5813
0
        }
5814
9
        TxnInfoPB txn_info;
5815
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
5816
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
5817
0
            return -1;
5818
0
        }
5819
5820
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
5821
3
            txn.reset();
5822
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
5823
3
            std::shared_ptr<TxnLazyCommitTask> task =
5824
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
5825
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
5826
3
            if (ret.first != MetaServiceCode::OK) {
5827
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
5828
0
                             << "msg=" << ret.second;
5829
0
                return -1;
5830
0
            }
5831
3
            ++num_advance;
5832
3
            return 0;
5833
6
        } else {
5834
6
            TxnRunningPB txn_running_pb;
5835
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
5836
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
5837
0
                return -1;
5838
0
            }
5839
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
5840
4
                return 0;
5841
4
            }
5842
2
            ++num_timeout;
5843
5844
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
5845
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
5846
2
            txn_info.set_finish_time(current_time);
5847
2
            txn_info.set_reason("timeout");
5848
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
5849
2
            txn_inf_val.clear();
5850
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
5851
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
5852
0
                return -1;
5853
0
            }
5854
2
            txn->put(txn_inf_key, txn_inf_val);
5855
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
5856
            // Put recycle txn key
5857
2
            std::string recyc_txn_key, recyc_txn_val;
5858
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
5859
2
            RecycleTxnPB recycle_txn_pb;
5860
2
            recycle_txn_pb.set_creation_time(current_time);
5861
2
            recycle_txn_pb.set_label(txn_info.label());
5862
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
5863
0
                LOG_WARNING("failed to serialize txn recycle info")
5864
0
                        .tag("key", hex(k))
5865
0
                        .tag("db_id", db_id)
5866
0
                        .tag("txn_id", txn_id);
5867
0
                return -1;
5868
0
            }
5869
2
            txn->put(recyc_txn_key, recyc_txn_val);
5870
            // Remove txn running key
5871
2
            txn->remove(k);
5872
2
            err = txn->commit();
5873
2
            if (err != TxnErrorCode::TXN_OK) {
5874
0
                LOG_WARNING("failed to commit txn err={}", err)
5875
0
                        .tag("key", hex(k))
5876
0
                        .tag("db_id", db_id)
5877
0
                        .tag("txn_id", txn_id);
5878
0
                return -1;
5879
0
            }
5880
2
            metrics_context.total_recycled_num = ++num_abort;
5881
2
            metrics_context.report();
5882
2
        }
5883
5884
2
        return 0;
5885
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5786
3
                                  this](std::string_view k, std::string_view v) -> int {
5787
3
        ++num_scanned;
5788
5789
3
        std::unique_ptr<Transaction> txn;
5790
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5791
3
        if (err != TxnErrorCode::TXN_OK) {
5792
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
5793
0
            return -1;
5794
0
        }
5795
3
        std::string_view k1 = k;
5796
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
5797
3
        k1.remove_prefix(1); // Remove key space
5798
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5799
3
        if (decode_key(&k1, &out) != 0) {
5800
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
5801
0
            return -1;
5802
0
        }
5803
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
5804
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
5805
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
5806
        // Update txn_info
5807
3
        std::string txn_inf_key, txn_inf_val;
5808
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
5809
3
        err = txn->get(txn_inf_key, &txn_inf_val);
5810
3
        if (err != TxnErrorCode::TXN_OK) {
5811
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
5812
0
            return -1;
5813
0
        }
5814
3
        TxnInfoPB txn_info;
5815
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
5816
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
5817
0
            return -1;
5818
0
        }
5819
5820
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
5821
3
            txn.reset();
5822
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
5823
3
            std::shared_ptr<TxnLazyCommitTask> task =
5824
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
5825
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
5826
3
            if (ret.first != MetaServiceCode::OK) {
5827
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
5828
0
                             << "msg=" << ret.second;
5829
0
                return -1;
5830
0
            }
5831
3
            ++num_advance;
5832
3
            return 0;
5833
3
        } else {
5834
0
            TxnRunningPB txn_running_pb;
5835
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
5836
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
5837
0
                return -1;
5838
0
            }
5839
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
5840
0
                return 0;
5841
0
            }
5842
0
            ++num_timeout;
5843
5844
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
5845
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
5846
0
            txn_info.set_finish_time(current_time);
5847
0
            txn_info.set_reason("timeout");
5848
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
5849
0
            txn_inf_val.clear();
5850
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
5851
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
5852
0
                return -1;
5853
0
            }
5854
0
            txn->put(txn_inf_key, txn_inf_val);
5855
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
5856
            // Put recycle txn key
5857
0
            std::string recyc_txn_key, recyc_txn_val;
5858
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
5859
0
            RecycleTxnPB recycle_txn_pb;
5860
0
            recycle_txn_pb.set_creation_time(current_time);
5861
0
            recycle_txn_pb.set_label(txn_info.label());
5862
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
5863
0
                LOG_WARNING("failed to serialize txn recycle info")
5864
0
                        .tag("key", hex(k))
5865
0
                        .tag("db_id", db_id)
5866
0
                        .tag("txn_id", txn_id);
5867
0
                return -1;
5868
0
            }
5869
0
            txn->put(recyc_txn_key, recyc_txn_val);
5870
            // Remove txn running key
5871
0
            txn->remove(k);
5872
0
            err = txn->commit();
5873
0
            if (err != TxnErrorCode::TXN_OK) {
5874
0
                LOG_WARNING("failed to commit txn err={}", err)
5875
0
                        .tag("key", hex(k))
5876
0
                        .tag("db_id", db_id)
5877
0
                        .tag("txn_id", txn_id);
5878
0
                return -1;
5879
0
            }
5880
0
            metrics_context.total_recycled_num = ++num_abort;
5881
0
            metrics_context.report();
5882
0
        }
5883
5884
0
        return 0;
5885
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5786
6
                                  this](std::string_view k, std::string_view v) -> int {
5787
6
        ++num_scanned;
5788
5789
6
        std::unique_ptr<Transaction> txn;
5790
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5791
6
        if (err != TxnErrorCode::TXN_OK) {
5792
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
5793
0
            return -1;
5794
0
        }
5795
6
        std::string_view k1 = k;
5796
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
5797
6
        k1.remove_prefix(1); // Remove key space
5798
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5799
6
        if (decode_key(&k1, &out) != 0) {
5800
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
5801
0
            return -1;
5802
0
        }
5803
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
5804
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
5805
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
5806
        // Update txn_info
5807
6
        std::string txn_inf_key, txn_inf_val;
5808
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
5809
6
        err = txn->get(txn_inf_key, &txn_inf_val);
5810
6
        if (err != TxnErrorCode::TXN_OK) {
5811
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
5812
0
            return -1;
5813
0
        }
5814
6
        TxnInfoPB txn_info;
5815
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
5816
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
5817
0
            return -1;
5818
0
        }
5819
5820
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
5821
0
            txn.reset();
5822
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
5823
0
            std::shared_ptr<TxnLazyCommitTask> task =
5824
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
5825
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
5826
0
            if (ret.first != MetaServiceCode::OK) {
5827
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
5828
0
                             << "msg=" << ret.second;
5829
0
                return -1;
5830
0
            }
5831
0
            ++num_advance;
5832
0
            return 0;
5833
6
        } else {
5834
6
            TxnRunningPB txn_running_pb;
5835
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
5836
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
5837
0
                return -1;
5838
0
            }
5839
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
5840
4
                return 0;
5841
4
            }
5842
2
            ++num_timeout;
5843
5844
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
5845
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
5846
2
            txn_info.set_finish_time(current_time);
5847
2
            txn_info.set_reason("timeout");
5848
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
5849
2
            txn_inf_val.clear();
5850
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
5851
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
5852
0
                return -1;
5853
0
            }
5854
2
            txn->put(txn_inf_key, txn_inf_val);
5855
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
5856
            // Put recycle txn key
5857
2
            std::string recyc_txn_key, recyc_txn_val;
5858
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
5859
2
            RecycleTxnPB recycle_txn_pb;
5860
2
            recycle_txn_pb.set_creation_time(current_time);
5861
2
            recycle_txn_pb.set_label(txn_info.label());
5862
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
5863
0
                LOG_WARNING("failed to serialize txn recycle info")
5864
0
                        .tag("key", hex(k))
5865
0
                        .tag("db_id", db_id)
5866
0
                        .tag("txn_id", txn_id);
5867
0
                return -1;
5868
0
            }
5869
2
            txn->put(recyc_txn_key, recyc_txn_val);
5870
            // Remove txn running key
5871
2
            txn->remove(k);
5872
2
            err = txn->commit();
5873
2
            if (err != TxnErrorCode::TXN_OK) {
5874
0
                LOG_WARNING("failed to commit txn err={}", err)
5875
0
                        .tag("key", hex(k))
5876
0
                        .tag("db_id", db_id)
5877
0
                        .tag("txn_id", txn_id);
5878
0
                return -1;
5879
0
            }
5880
2
            metrics_context.total_recycled_num = ++num_abort;
5881
2
            metrics_context.report();
5882
2
        }
5883
5884
2
        return 0;
5885
6
    };
5886
5887
19
    if (config::enable_recycler_stats_metrics) {
5888
0
        scan_and_statistics_abort_timeout_txn();
5889
0
    }
5890
    // recycle_func and loop_done for scan and recycle
5891
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
5892
19
                            std::move(handle_txn_running_kv));
5893
19
}
5894
5895
19
int InstanceRecycler::recycle_expired_txn_label() {
5896
19
    const std::string task_name = "recycle_expired_txn_label";
5897
19
    int64_t num_scanned = 0;
5898
19
    int64_t num_expired = 0;
5899
19
    std::atomic_long num_recycled = 0;
5900
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5901
19
    int ret = 0;
5902
5903
19
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
5904
19
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
5905
19
    std::string begin_recycle_txn_key;
5906
19
    std::string end_recycle_txn_key;
5907
19
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
5908
19
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
5909
19
    std::vector<std::string> recycle_txn_info_keys;
5910
5911
19
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
5912
5913
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5914
19
    register_recycle_task(task_name, start_time);
5915
19
    DORIS_CLOUD_DEFER {
5916
19
        unregister_recycle_task(task_name);
5917
19
        int64_t cost =
5918
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5919
19
        metrics_context.finish_report();
5920
19
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
5921
19
                .tag("instance_id", instance_id_)
5922
19
                .tag("num_scanned", num_scanned)
5923
19
                .tag("num_expired", num_expired)
5924
19
                .tag("num_recycled", num_recycled);
5925
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
5915
1
    DORIS_CLOUD_DEFER {
5916
1
        unregister_recycle_task(task_name);
5917
1
        int64_t cost =
5918
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5919
1
        metrics_context.finish_report();
5920
1
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
5921
1
                .tag("instance_id", instance_id_)
5922
1
                .tag("num_scanned", num_scanned)
5923
1
                .tag("num_expired", num_expired)
5924
1
                .tag("num_recycled", num_recycled);
5925
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
5915
18
    DORIS_CLOUD_DEFER {
5916
18
        unregister_recycle_task(task_name);
5917
18
        int64_t cost =
5918
18
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5919
18
        metrics_context.finish_report();
5920
18
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
5921
18
                .tag("instance_id", instance_id_)
5922
18
                .tag("num_scanned", num_scanned)
5923
18
                .tag("num_expired", num_expired)
5924
18
                .tag("num_recycled", num_recycled);
5925
18
    };
5926
5927
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5928
5929
19
    SyncExecutor<int> concurrent_delete_executor(
5930
19
            _thread_pool_group.s3_producer_pool,
5931
19
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
5932
23.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
5932
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
5932
23.0k
            [](const int& ret) { return ret != 0; });
5933
5934
19
    int64_t current_time_ms =
5935
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
5936
5937
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
5938
30.0k
        ++num_scanned;
5939
30.0k
        RecycleTxnPB recycle_txn_pb;
5940
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
5941
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
5942
0
            return -1;
5943
0
        }
5944
30.0k
        if ((config::force_immediate_recycle) ||
5945
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
5946
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
5947
30.0k
             current_time_ms)) {
5948
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
5949
23.0k
            num_expired++;
5950
23.0k
            recycle_txn_info_keys.emplace_back(k);
5951
23.0k
        }
5952
30.0k
        return 0;
5953
30.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5937
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
5938
1
        ++num_scanned;
5939
1
        RecycleTxnPB recycle_txn_pb;
5940
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
5941
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
5942
0
            return -1;
5943
0
        }
5944
1
        if ((config::force_immediate_recycle) ||
5945
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
5946
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
5947
1
             current_time_ms)) {
5948
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
5949
1
            num_expired++;
5950
1
            recycle_txn_info_keys.emplace_back(k);
5951
1
        }
5952
1
        return 0;
5953
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5937
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
5938
30.0k
        ++num_scanned;
5939
30.0k
        RecycleTxnPB recycle_txn_pb;
5940
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
5941
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
5942
0
            return -1;
5943
0
        }
5944
30.0k
        if ((config::force_immediate_recycle) ||
5945
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
5946
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
5947
30.0k
             current_time_ms)) {
5948
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
5949
23.0k
            num_expired++;
5950
23.0k
            recycle_txn_info_keys.emplace_back(k);
5951
23.0k
        }
5952
30.0k
        return 0;
5953
30.0k
    };
5954
5955
    // int 0 for success, 1 for conflict, -1 for error
5956
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
5957
23.0k
        std::string_view k1 = k;
5958
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
5959
23.0k
        k1.remove_prefix(1); // Remove key space
5960
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5961
23.0k
        int ret = decode_key(&k1, &out);
5962
23.0k
        if (ret != 0) {
5963
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
5964
0
            return -1;
5965
0
        }
5966
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
5967
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
5968
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
5969
23.0k
        std::unique_ptr<Transaction> txn;
5970
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5971
23.0k
        if (err != TxnErrorCode::TXN_OK) {
5972
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
5973
0
            return -1;
5974
0
        }
5975
        // Remove txn index kv
5976
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
5977
23.0k
        txn->remove(index_key);
5978
        // Remove txn info kv
5979
23.0k
        std::string info_key, info_val;
5980
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
5981
23.0k
        err = txn->get(info_key, &info_val);
5982
23.0k
        if (err != TxnErrorCode::TXN_OK) {
5983
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
5984
0
            return -1;
5985
0
        }
5986
23.0k
        TxnInfoPB txn_info;
5987
23.0k
        if (!txn_info.ParseFromString(info_val)) {
5988
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
5989
0
            return -1;
5990
0
        }
5991
23.0k
        txn->remove(info_key);
5992
        // Remove sub txn index kvs
5993
23.0k
        std::vector<std::string> sub_txn_index_keys;
5994
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
5995
23.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
5996
23.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
5997
23.0k
        }
5998
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
5999
22.9k
            txn->remove(sub_txn_index_key);
6000
22.9k
        }
6001
        // Update txn label
6002
23.0k
        std::string label_key, label_val;
6003
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6004
23.0k
        err = txn->get(label_key, &label_val);
6005
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6006
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6007
0
                         << " err=" << err;
6008
0
            return -1;
6009
0
        }
6010
23.0k
        TxnLabelPB txn_label;
6011
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6012
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6013
0
            return -1;
6014
0
        }
6015
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6016
23.0k
        if (it != txn_label.txn_ids().end()) {
6017
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6018
23.0k
        }
6019
23.0k
        if (txn_label.txn_ids().empty()) {
6020
23.0k
            txn->remove(label_key);
6021
23.0k
            TEST_SYNC_POINT_CALLBACK(
6022
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6023
23.0k
        } else {
6024
73
            if (!txn_label.SerializeToString(&label_val)) {
6025
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6026
0
                return -1;
6027
0
            }
6028
73
            TEST_SYNC_POINT_CALLBACK(
6029
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6030
73
            txn->atomic_set_ver_value(label_key, label_val);
6031
73
            TEST_SYNC_POINT_CALLBACK(
6032
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6033
73
        }
6034
        // Remove recycle txn kv
6035
23.0k
        txn->remove(k);
6036
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6037
23.0k
        err = txn->commit();
6038
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6039
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6040
62
                TEST_SYNC_POINT_CALLBACK(
6041
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6042
                // log the txn_id and label
6043
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6044
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6045
62
                             << " txn_label=" << txn_info.label();
6046
62
                return 1;
6047
62
            }
6048
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6049
0
            return -1;
6050
62
        }
6051
23.0k
        ++num_recycled;
6052
6053
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6054
23.0k
        return 0;
6055
23.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5956
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
5957
1
        std::string_view k1 = k;
5958
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
5959
1
        k1.remove_prefix(1); // Remove key space
5960
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5961
1
        int ret = decode_key(&k1, &out);
5962
1
        if (ret != 0) {
5963
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
5964
0
            return -1;
5965
0
        }
5966
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
5967
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
5968
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
5969
1
        std::unique_ptr<Transaction> txn;
5970
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5971
1
        if (err != TxnErrorCode::TXN_OK) {
5972
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
5973
0
            return -1;
5974
0
        }
5975
        // Remove txn index kv
5976
1
        auto index_key = txn_index_key({instance_id_, txn_id});
5977
1
        txn->remove(index_key);
5978
        // Remove txn info kv
5979
1
        std::string info_key, info_val;
5980
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
5981
1
        err = txn->get(info_key, &info_val);
5982
1
        if (err != TxnErrorCode::TXN_OK) {
5983
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
5984
0
            return -1;
5985
0
        }
5986
1
        TxnInfoPB txn_info;
5987
1
        if (!txn_info.ParseFromString(info_val)) {
5988
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
5989
0
            return -1;
5990
0
        }
5991
1
        txn->remove(info_key);
5992
        // Remove sub txn index kvs
5993
1
        std::vector<std::string> sub_txn_index_keys;
5994
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
5995
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
5996
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
5997
0
        }
5998
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
5999
0
            txn->remove(sub_txn_index_key);
6000
0
        }
6001
        // Update txn label
6002
1
        std::string label_key, label_val;
6003
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6004
1
        err = txn->get(label_key, &label_val);
6005
1
        if (err != TxnErrorCode::TXN_OK) {
6006
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6007
0
                         << " err=" << err;
6008
0
            return -1;
6009
0
        }
6010
1
        TxnLabelPB txn_label;
6011
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6012
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6013
0
            return -1;
6014
0
        }
6015
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6016
1
        if (it != txn_label.txn_ids().end()) {
6017
1
            txn_label.mutable_txn_ids()->erase(it);
6018
1
        }
6019
1
        if (txn_label.txn_ids().empty()) {
6020
1
            txn->remove(label_key);
6021
1
            TEST_SYNC_POINT_CALLBACK(
6022
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6023
1
        } else {
6024
0
            if (!txn_label.SerializeToString(&label_val)) {
6025
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6026
0
                return -1;
6027
0
            }
6028
0
            TEST_SYNC_POINT_CALLBACK(
6029
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6030
0
            txn->atomic_set_ver_value(label_key, label_val);
6031
0
            TEST_SYNC_POINT_CALLBACK(
6032
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6033
0
        }
6034
        // Remove recycle txn kv
6035
1
        txn->remove(k);
6036
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6037
1
        err = txn->commit();
6038
1
        if (err != TxnErrorCode::TXN_OK) {
6039
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
6040
0
                TEST_SYNC_POINT_CALLBACK(
6041
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6042
                // log the txn_id and label
6043
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6044
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6045
0
                             << " txn_label=" << txn_info.label();
6046
0
                return 1;
6047
0
            }
6048
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6049
0
            return -1;
6050
0
        }
6051
1
        ++num_recycled;
6052
6053
1
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6054
1
        return 0;
6055
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5956
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
5957
23.0k
        std::string_view k1 = k;
5958
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
5959
23.0k
        k1.remove_prefix(1); // Remove key space
5960
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5961
23.0k
        int ret = decode_key(&k1, &out);
5962
23.0k
        if (ret != 0) {
5963
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
5964
0
            return -1;
5965
0
        }
5966
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
5967
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
5968
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
5969
23.0k
        std::unique_ptr<Transaction> txn;
5970
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5971
23.0k
        if (err != TxnErrorCode::TXN_OK) {
5972
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
5973
0
            return -1;
5974
0
        }
5975
        // Remove txn index kv
5976
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
5977
23.0k
        txn->remove(index_key);
5978
        // Remove txn info kv
5979
23.0k
        std::string info_key, info_val;
5980
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
5981
23.0k
        err = txn->get(info_key, &info_val);
5982
23.0k
        if (err != TxnErrorCode::TXN_OK) {
5983
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
5984
0
            return -1;
5985
0
        }
5986
23.0k
        TxnInfoPB txn_info;
5987
23.0k
        if (!txn_info.ParseFromString(info_val)) {
5988
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
5989
0
            return -1;
5990
0
        }
5991
23.0k
        txn->remove(info_key);
5992
        // Remove sub txn index kvs
5993
23.0k
        std::vector<std::string> sub_txn_index_keys;
5994
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
5995
23.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
5996
23.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
5997
23.0k
        }
5998
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
5999
22.9k
            txn->remove(sub_txn_index_key);
6000
22.9k
        }
6001
        // Update txn label
6002
23.0k
        std::string label_key, label_val;
6003
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6004
23.0k
        err = txn->get(label_key, &label_val);
6005
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6006
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6007
0
                         << " err=" << err;
6008
0
            return -1;
6009
0
        }
6010
23.0k
        TxnLabelPB txn_label;
6011
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6012
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6013
0
            return -1;
6014
0
        }
6015
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6016
23.0k
        if (it != txn_label.txn_ids().end()) {
6017
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6018
23.0k
        }
6019
23.0k
        if (txn_label.txn_ids().empty()) {
6020
23.0k
            txn->remove(label_key);
6021
23.0k
            TEST_SYNC_POINT_CALLBACK(
6022
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6023
23.0k
        } else {
6024
73
            if (!txn_label.SerializeToString(&label_val)) {
6025
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6026
0
                return -1;
6027
0
            }
6028
73
            TEST_SYNC_POINT_CALLBACK(
6029
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6030
73
            txn->atomic_set_ver_value(label_key, label_val);
6031
73
            TEST_SYNC_POINT_CALLBACK(
6032
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6033
73
        }
6034
        // Remove recycle txn kv
6035
23.0k
        txn->remove(k);
6036
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6037
23.0k
        err = txn->commit();
6038
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6039
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6040
62
                TEST_SYNC_POINT_CALLBACK(
6041
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6042
                // log the txn_id and label
6043
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6044
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6045
62
                             << " txn_label=" << txn_info.label();
6046
62
                return 1;
6047
62
            }
6048
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6049
0
            return -1;
6050
62
        }
6051
23.0k
        ++num_recycled;
6052
6053
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6054
23.0k
        return 0;
6055
23.0k
    };
6056
6057
19
    auto loop_done = [&]() -> int {
6058
10
        DORIS_CLOUD_DEFER {
6059
10
            recycle_txn_info_keys.clear();
6060
10
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6058
1
        DORIS_CLOUD_DEFER {
6059
1
            recycle_txn_info_keys.clear();
6060
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6058
9
        DORIS_CLOUD_DEFER {
6059
9
            recycle_txn_info_keys.clear();
6060
9
        };
6061
10
        TEST_SYNC_POINT_CALLBACK(
6062
10
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6063
10
                &recycle_txn_info_keys);
6064
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6065
23.0k
            concurrent_delete_executor.add([&]() {
6066
23.0k
                int ret = delete_recycle_txn_kv(k);
6067
23.0k
                if (ret == 1) {
6068
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6069
54
                    for (int i = 1; i <= max_retry; ++i) {
6070
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6071
54
                        ret = delete_recycle_txn_kv(k);
6072
                        // clang-format off
6073
54
                        TEST_SYNC_POINT_CALLBACK(
6074
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6075
                        // clang-format off
6076
54
                        if (ret != 1) {
6077
18
                            break;
6078
18
                        }
6079
                        // random sleep 0-100 ms to retry
6080
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6081
36
                    }
6082
18
                }
6083
23.0k
                if (ret != 0) {
6084
9
                    LOG_WARNING("failed to delete recycle txn kv")
6085
9
                            .tag("instance id", instance_id_)
6086
9
                            .tag("key", hex(k));
6087
9
                    return -1;
6088
9
                }
6089
23.0k
                return 0;
6090
23.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6065
1
            concurrent_delete_executor.add([&]() {
6066
1
                int ret = delete_recycle_txn_kv(k);
6067
1
                if (ret == 1) {
6068
0
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6069
0
                    for (int i = 1; i <= max_retry; ++i) {
6070
0
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6071
0
                        ret = delete_recycle_txn_kv(k);
6072
                        // clang-format off
6073
0
                        TEST_SYNC_POINT_CALLBACK(
6074
0
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6075
                        // clang-format off
6076
0
                        if (ret != 1) {
6077
0
                            break;
6078
0
                        }
6079
                        // random sleep 0-100 ms to retry
6080
0
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6081
0
                    }
6082
0
                }
6083
1
                if (ret != 0) {
6084
0
                    LOG_WARNING("failed to delete recycle txn kv")
6085
0
                            .tag("instance id", instance_id_)
6086
0
                            .tag("key", hex(k));
6087
0
                    return -1;
6088
0
                }
6089
1
                return 0;
6090
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6065
23.0k
            concurrent_delete_executor.add([&]() {
6066
23.0k
                int ret = delete_recycle_txn_kv(k);
6067
23.0k
                if (ret == 1) {
6068
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6069
54
                    for (int i = 1; i <= max_retry; ++i) {
6070
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6071
54
                        ret = delete_recycle_txn_kv(k);
6072
                        // clang-format off
6073
54
                        TEST_SYNC_POINT_CALLBACK(
6074
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6075
                        // clang-format off
6076
54
                        if (ret != 1) {
6077
18
                            break;
6078
18
                        }
6079
                        // random sleep 0-100 ms to retry
6080
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6081
36
                    }
6082
18
                }
6083
23.0k
                if (ret != 0) {
6084
9
                    LOG_WARNING("failed to delete recycle txn kv")
6085
9
                            .tag("instance id", instance_id_)
6086
9
                            .tag("key", hex(k));
6087
9
                    return -1;
6088
9
                }
6089
23.0k
                return 0;
6090
23.0k
            });
6091
23.0k
        }
6092
10
        bool finished = true;
6093
10
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6094
23.0k
        for (int r : rets) {
6095
23.0k
            if (r != 0) {
6096
9
                ret = -1;
6097
9
            }
6098
23.0k
        }
6099
6100
10
        ret = finished ? ret : -1;
6101
6102
        // Update metrics after all concurrent tasks completed
6103
10
        metrics_context.total_recycled_num = num_recycled.load();
6104
10
        metrics_context.report();
6105
6106
10
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6107
6108
10
        if (ret != 0) {
6109
3
            LOG_WARNING("recycle txn kv ret!=0")
6110
3
                    .tag("finished", finished)
6111
3
                    .tag("ret", ret)
6112
3
                    .tag("instance_id", instance_id_);
6113
3
            return ret;
6114
3
        }
6115
7
        return ret;
6116
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6057
1
    auto loop_done = [&]() -> int {
6058
1
        DORIS_CLOUD_DEFER {
6059
1
            recycle_txn_info_keys.clear();
6060
1
        };
6061
1
        TEST_SYNC_POINT_CALLBACK(
6062
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6063
1
                &recycle_txn_info_keys);
6064
1
        for (const auto& k : recycle_txn_info_keys) {
6065
1
            concurrent_delete_executor.add([&]() {
6066
1
                int ret = delete_recycle_txn_kv(k);
6067
1
                if (ret == 1) {
6068
1
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6069
1
                    for (int i = 1; i <= max_retry; ++i) {
6070
1
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6071
1
                        ret = delete_recycle_txn_kv(k);
6072
                        // clang-format off
6073
1
                        TEST_SYNC_POINT_CALLBACK(
6074
1
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6075
                        // clang-format off
6076
1
                        if (ret != 1) {
6077
1
                            break;
6078
1
                        }
6079
                        // random sleep 0-100 ms to retry
6080
1
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6081
1
                    }
6082
1
                }
6083
1
                if (ret != 0) {
6084
1
                    LOG_WARNING("failed to delete recycle txn kv")
6085
1
                            .tag("instance id", instance_id_)
6086
1
                            .tag("key", hex(k));
6087
1
                    return -1;
6088
1
                }
6089
1
                return 0;
6090
1
            });
6091
1
        }
6092
1
        bool finished = true;
6093
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6094
1
        for (int r : rets) {
6095
1
            if (r != 0) {
6096
0
                ret = -1;
6097
0
            }
6098
1
        }
6099
6100
1
        ret = finished ? ret : -1;
6101
6102
        // Update metrics after all concurrent tasks completed
6103
1
        metrics_context.total_recycled_num = num_recycled.load();
6104
1
        metrics_context.report();
6105
6106
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6107
6108
1
        if (ret != 0) {
6109
0
            LOG_WARNING("recycle txn kv ret!=0")
6110
0
                    .tag("finished", finished)
6111
0
                    .tag("ret", ret)
6112
0
                    .tag("instance_id", instance_id_);
6113
0
            return ret;
6114
0
        }
6115
1
        return ret;
6116
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6057
9
    auto loop_done = [&]() -> int {
6058
9
        DORIS_CLOUD_DEFER {
6059
9
            recycle_txn_info_keys.clear();
6060
9
        };
6061
9
        TEST_SYNC_POINT_CALLBACK(
6062
9
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6063
9
                &recycle_txn_info_keys);
6064
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6065
23.0k
            concurrent_delete_executor.add([&]() {
6066
23.0k
                int ret = delete_recycle_txn_kv(k);
6067
23.0k
                if (ret == 1) {
6068
23.0k
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6069
23.0k
                    for (int i = 1; i <= max_retry; ++i) {
6070
23.0k
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6071
23.0k
                        ret = delete_recycle_txn_kv(k);
6072
                        // clang-format off
6073
23.0k
                        TEST_SYNC_POINT_CALLBACK(
6074
23.0k
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6075
                        // clang-format off
6076
23.0k
                        if (ret != 1) {
6077
23.0k
                            break;
6078
23.0k
                        }
6079
                        // random sleep 0-100 ms to retry
6080
23.0k
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6081
23.0k
                    }
6082
23.0k
                }
6083
23.0k
                if (ret != 0) {
6084
23.0k
                    LOG_WARNING("failed to delete recycle txn kv")
6085
23.0k
                            .tag("instance id", instance_id_)
6086
23.0k
                            .tag("key", hex(k));
6087
23.0k
                    return -1;
6088
23.0k
                }
6089
23.0k
                return 0;
6090
23.0k
            });
6091
23.0k
        }
6092
9
        bool finished = true;
6093
9
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6094
23.0k
        for (int r : rets) {
6095
23.0k
            if (r != 0) {
6096
9
                ret = -1;
6097
9
            }
6098
23.0k
        }
6099
6100
9
        ret = finished ? ret : -1;
6101
6102
        // Update metrics after all concurrent tasks completed
6103
9
        metrics_context.total_recycled_num = num_recycled.load();
6104
9
        metrics_context.report();
6105
6106
9
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6107
6108
9
        if (ret != 0) {
6109
3
            LOG_WARNING("recycle txn kv ret!=0")
6110
3
                    .tag("finished", finished)
6111
3
                    .tag("ret", ret)
6112
3
                    .tag("instance_id", instance_id_);
6113
3
            return ret;
6114
3
        }
6115
6
        return ret;
6116
9
    };
6117
6118
19
    if (config::enable_recycler_stats_metrics) {
6119
0
        scan_and_statistics_expired_txn_label();
6120
0
    }
6121
    // recycle_func and loop_done for scan and recycle
6122
19
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
6123
19
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
6124
19
}
6125
6126
struct CopyJobIdTuple {
6127
    std::string instance_id;
6128
    std::string stage_id;
6129
    long table_id;
6130
    std::string copy_id;
6131
    std::string stage_path;
6132
};
6133
struct BatchObjStoreAccessor {
6134
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
6135
                          TxnKv* txn_kv)
6136
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
6137
3
    ~BatchObjStoreAccessor() {
6138
3
        if (!paths_.empty()) {
6139
3
            consume();
6140
3
        }
6141
3
    }
6142
6143
    /**
6144
    * To implicitely do batch work and submit the batch delete task to s3
6145
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
6146
    *
6147
    * @param copy_job The protubuf struct consists of the copy job files.
6148
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
6149
    *            it would last until we finish the delete task, here we need pass one string value
6150
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
6151
    */
6152
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
6153
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
6154
5
        auto& file_keys = copy_file_keys_[key];
6155
5
        file_keys.log_trace =
6156
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
6157
5
                            instance_id, stage_id, table_id, copy_id, path);
6158
5
        std::string_view log_trace = file_keys.log_trace;
6159
2.03k
        for (const auto& file : copy_job.object_files()) {
6160
2.03k
            auto relative_path = file.relative_path();
6161
2.03k
            paths_.push_back(relative_path);
6162
2.03k
            file_keys.keys.push_back(copy_file_key(
6163
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
6164
2.03k
            LOG_INFO(log_trace)
6165
2.03k
                    .tag("relative_path", relative_path)
6166
2.03k
                    .tag("batch_count", batch_count_);
6167
2.03k
        }
6168
5
        LOG_INFO(log_trace)
6169
5
                .tag("objects_num", copy_job.object_files().size())
6170
5
                .tag("batch_count", batch_count_);
6171
        // 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
6172
        // recommend using delete objects when objects num is less than 10)
6173
5
        if (paths_.size() < 1000) {
6174
3
            return;
6175
3
        }
6176
2
        consume();
6177
2
    }
6178
6179
private:
6180
5
    void consume() {
6181
5
        DORIS_CLOUD_DEFER {
6182
5
            paths_.clear();
6183
5
            copy_file_keys_.clear();
6184
5
            batch_count_++;
6185
6186
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
6187
5
                        batch_count_);
6188
5
        };
6189
6190
5
        StopWatch sw;
6191
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
6192
5
        if (0 != accessor_->delete_files(paths_)) {
6193
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
6194
2
                        paths_.size(), batch_count_, sw.elapsed_us());
6195
2
            return;
6196
2
        }
6197
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
6198
3
                    paths_.size(), batch_count_, sw.elapsed_us());
6199
        // delete fdb's keys
6200
3
        for (auto& file_keys : copy_file_keys_) {
6201
3
            auto& [log_trace, keys] = file_keys.second;
6202
3
            std::unique_ptr<Transaction> txn;
6203
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
6204
0
                LOG(WARNING) << "failed to create txn";
6205
0
                continue;
6206
0
            }
6207
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6208
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6209
            // limited, should not cause the txn commit failed.
6210
1.02k
            for (const auto& key : keys) {
6211
1.02k
                txn->remove(key);
6212
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
6213
1.02k
            }
6214
3
            txn->remove(file_keys.first);
6215
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
6216
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
6217
0
                continue;
6218
0
            }
6219
3
        }
6220
3
    }
6221
    std::shared_ptr<StorageVaultAccessor> accessor_;
6222
    // the path of the s3 files to be deleted
6223
    std::vector<std::string> paths_;
6224
    struct CopyFiles {
6225
        std::string log_trace;
6226
        std::vector<std::string> keys;
6227
    };
6228
    // pair<std::string, std::vector<std::string>>
6229
    // first: instance_id_ stage_id table_id query_id
6230
    // second: keys to be deleted
6231
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
6232
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
6233
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
6234
    // which can together uniquely identifies different tasks for tracing log
6235
    uint64_t& batch_count_;
6236
    TxnKv* txn_kv_;
6237
};
6238
6239
13
int InstanceRecycler::recycle_copy_jobs() {
6240
13
    int64_t num_scanned = 0;
6241
13
    int64_t num_finished = 0;
6242
13
    int64_t num_expired = 0;
6243
13
    int64_t num_recycled = 0;
6244
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
6245
13
    uint64_t batch_count = 0;
6246
13
    const std::string task_name = "recycle_copy_jobs";
6247
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6248
6249
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
6250
6251
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6252
13
    register_recycle_task(task_name, start_time);
6253
6254
13
    DORIS_CLOUD_DEFER {
6255
12
        unregister_recycle_task(task_name);
6256
12
        int64_t cost =
6257
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6258
12
        metrics_context.finish_report();
6259
12
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
6260
12
                .tag("instance_id", instance_id_)
6261
12
                .tag("num_scanned", num_scanned)
6262
12
                .tag("num_finished", num_finished)
6263
12
                .tag("num_expired", num_expired)
6264
12
                .tag("num_recycled", num_recycled);
6265
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
6254
12
    DORIS_CLOUD_DEFER {
6255
12
        unregister_recycle_task(task_name);
6256
12
        int64_t cost =
6257
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6258
12
        metrics_context.finish_report();
6259
12
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
6260
12
                .tag("instance_id", instance_id_)
6261
12
                .tag("num_scanned", num_scanned)
6262
12
                .tag("num_finished", num_finished)
6263
12
                .tag("num_expired", num_expired)
6264
12
                .tag("num_recycled", num_recycled);
6265
12
    };
6266
6267
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
6268
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
6269
13
    std::string key0;
6270
13
    std::string key1;
6271
13
    copy_job_key(key_info0, &key0);
6272
13
    copy_job_key(key_info1, &key1);
6273
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
6274
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
6275
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
6276
16
                         this](std::string_view k, std::string_view v) -> int {
6277
16
        ++num_scanned;
6278
16
        CopyJobPB copy_job;
6279
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
6280
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
6281
0
            return -1;
6282
0
        }
6283
6284
        // decode copy job key
6285
16
        auto k1 = k;
6286
16
        k1.remove_prefix(1);
6287
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6288
16
        decode_key(&k1, &out);
6289
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
6290
        // -> CopyJobPB
6291
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
6292
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
6293
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
6294
6295
16
        bool check_storage = true;
6296
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
6297
12
            ++num_finished;
6298
6299
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
6300
7
                auto it = stage_accessor_map.find(stage_id);
6301
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
6302
7
                std::string_view path;
6303
7
                if (it != stage_accessor_map.end()) {
6304
2
                    accessor = it->second;
6305
5
                } else {
6306
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
6307
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
6308
5
                                                      &inner_accessor);
6309
5
                    if (ret < 0) { // error
6310
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
6311
0
                        return -1;
6312
5
                    } else if (ret == 0) {
6313
3
                        path = inner_accessor->uri();
6314
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
6315
3
                                inner_accessor, batch_count, txn_kv_.get());
6316
3
                        stage_accessor_map.emplace(stage_id, accessor);
6317
3
                    } else { // stage not found, skip check storage
6318
2
                        check_storage = false;
6319
2
                    }
6320
5
                }
6321
7
                if (check_storage) {
6322
                    // TODO delete objects with key and etag is not supported
6323
5
                    accessor->add(std::move(copy_job), std::string(k),
6324
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
6325
5
                    return 0;
6326
5
                }
6327
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
6328
5
                int64_t current_time =
6329
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6330
5
                if (copy_job.finish_time_ms() > 0) {
6331
2
                    if (!config::force_immediate_recycle &&
6332
2
                        current_time < copy_job.finish_time_ms() +
6333
2
                                               config::copy_job_max_retention_second * 1000) {
6334
1
                        return 0;
6335
1
                    }
6336
3
                } else {
6337
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
6338
3
                    if (!config::force_immediate_recycle &&
6339
3
                        current_time < copy_job.start_time_ms() +
6340
3
                                               config::copy_job_max_retention_second * 1000) {
6341
1
                        return 0;
6342
1
                    }
6343
3
                }
6344
5
            }
6345
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
6346
4
            int64_t current_time =
6347
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6348
            // if copy job is timeout: delete all copy file kvs and copy job kv
6349
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
6350
2
                return 0;
6351
2
            }
6352
2
            ++num_expired;
6353
2
        }
6354
6355
        // delete all copy files
6356
7
        std::vector<std::string> copy_file_keys;
6357
70
        for (auto& file : copy_job.object_files()) {
6358
70
            copy_file_keys.push_back(copy_file_key(
6359
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
6360
70
        }
6361
7
        std::unique_ptr<Transaction> txn;
6362
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
6363
0
            LOG(WARNING) << "failed to create txn";
6364
0
            return -1;
6365
0
        }
6366
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6367
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6368
        // limited, should not cause the txn commit failed.
6369
70
        for (const auto& key : copy_file_keys) {
6370
70
            txn->remove(key);
6371
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
6372
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
6373
70
                      << ", query_id=" << copy_id;
6374
70
        }
6375
7
        txn->remove(k);
6376
7
        TxnErrorCode err = txn->commit();
6377
7
        if (err != TxnErrorCode::TXN_OK) {
6378
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
6379
0
            return -1;
6380
0
        }
6381
6382
7
        metrics_context.total_recycled_num = ++num_recycled;
6383
7
        metrics_context.report();
6384
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6385
7
        return 0;
6386
7
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6276
16
                         this](std::string_view k, std::string_view v) -> int {
6277
16
        ++num_scanned;
6278
16
        CopyJobPB copy_job;
6279
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
6280
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
6281
0
            return -1;
6282
0
        }
6283
6284
        // decode copy job key
6285
16
        auto k1 = k;
6286
16
        k1.remove_prefix(1);
6287
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6288
16
        decode_key(&k1, &out);
6289
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
6290
        // -> CopyJobPB
6291
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
6292
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
6293
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
6294
6295
16
        bool check_storage = true;
6296
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
6297
12
            ++num_finished;
6298
6299
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
6300
7
                auto it = stage_accessor_map.find(stage_id);
6301
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
6302
7
                std::string_view path;
6303
7
                if (it != stage_accessor_map.end()) {
6304
2
                    accessor = it->second;
6305
5
                } else {
6306
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
6307
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
6308
5
                                                      &inner_accessor);
6309
5
                    if (ret < 0) { // error
6310
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
6311
0
                        return -1;
6312
5
                    } else if (ret == 0) {
6313
3
                        path = inner_accessor->uri();
6314
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
6315
3
                                inner_accessor, batch_count, txn_kv_.get());
6316
3
                        stage_accessor_map.emplace(stage_id, accessor);
6317
3
                    } else { // stage not found, skip check storage
6318
2
                        check_storage = false;
6319
2
                    }
6320
5
                }
6321
7
                if (check_storage) {
6322
                    // TODO delete objects with key and etag is not supported
6323
5
                    accessor->add(std::move(copy_job), std::string(k),
6324
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
6325
5
                    return 0;
6326
5
                }
6327
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
6328
5
                int64_t current_time =
6329
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6330
5
                if (copy_job.finish_time_ms() > 0) {
6331
2
                    if (!config::force_immediate_recycle &&
6332
2
                        current_time < copy_job.finish_time_ms() +
6333
2
                                               config::copy_job_max_retention_second * 1000) {
6334
1
                        return 0;
6335
1
                    }
6336
3
                } else {
6337
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
6338
3
                    if (!config::force_immediate_recycle &&
6339
3
                        current_time < copy_job.start_time_ms() +
6340
3
                                               config::copy_job_max_retention_second * 1000) {
6341
1
                        return 0;
6342
1
                    }
6343
3
                }
6344
5
            }
6345
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
6346
4
            int64_t current_time =
6347
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6348
            // if copy job is timeout: delete all copy file kvs and copy job kv
6349
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
6350
2
                return 0;
6351
2
            }
6352
2
            ++num_expired;
6353
2
        }
6354
6355
        // delete all copy files
6356
7
        std::vector<std::string> copy_file_keys;
6357
70
        for (auto& file : copy_job.object_files()) {
6358
70
            copy_file_keys.push_back(copy_file_key(
6359
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
6360
70
        }
6361
7
        std::unique_ptr<Transaction> txn;
6362
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
6363
0
            LOG(WARNING) << "failed to create txn";
6364
0
            return -1;
6365
0
        }
6366
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6367
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6368
        // limited, should not cause the txn commit failed.
6369
70
        for (const auto& key : copy_file_keys) {
6370
70
            txn->remove(key);
6371
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
6372
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
6373
70
                      << ", query_id=" << copy_id;
6374
70
        }
6375
7
        txn->remove(k);
6376
7
        TxnErrorCode err = txn->commit();
6377
7
        if (err != TxnErrorCode::TXN_OK) {
6378
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
6379
0
            return -1;
6380
0
        }
6381
6382
7
        metrics_context.total_recycled_num = ++num_recycled;
6383
7
        metrics_context.report();
6384
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6385
7
        return 0;
6386
7
    };
6387
6388
13
    if (config::enable_recycler_stats_metrics) {
6389
0
        scan_and_statistics_copy_jobs();
6390
0
    }
6391
    // recycle_func and loop_done for scan and recycle
6392
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
6393
13
}
6394
6395
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
6396
                                             const StagePB::StageType& stage_type,
6397
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
6398
5
#ifdef UNIT_TEST
6399
    // In unit test, external use the same accessor as the internal stage
6400
5
    auto it = accessor_map_.find(stage_id);
6401
5
    if (it != accessor_map_.end()) {
6402
3
        *accessor = it->second;
6403
3
    } else {
6404
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
6405
2
        return 1;
6406
2
    }
6407
#else
6408
    // init s3 accessor and add to accessor map
6409
    auto stage_it =
6410
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
6411
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
6412
6413
    if (stage_it == instance_info_.stages().end()) {
6414
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
6415
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
6416
        return 1;
6417
    }
6418
6419
    const auto& object_store_info = stage_it->obj_info();
6420
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
6421
6422
    S3Conf s3_conf;
6423
    if (stage_type == StagePB::EXTERNAL) {
6424
        if (stage_access_type == StagePB::AKSK) {
6425
            auto conf = S3Conf::from_obj_store_info(object_store_info);
6426
            if (!conf) {
6427
                return -1;
6428
            }
6429
6430
            s3_conf = std::move(*conf);
6431
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
6432
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
6433
            if (!conf) {
6434
                return -1;
6435
            }
6436
6437
            s3_conf = std::move(*conf);
6438
            if (instance_info_.ram_user().has_encryption_info()) {
6439
                AkSkPair plain_ak_sk_pair;
6440
                int ret = decrypt_ak_sk_helper(
6441
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
6442
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
6443
                if (ret != 0) {
6444
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
6445
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
6446
                    return -1;
6447
                }
6448
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
6449
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
6450
            } else {
6451
                s3_conf.ak = instance_info_.ram_user().ak();
6452
                s3_conf.sk = instance_info_.ram_user().sk();
6453
            }
6454
        } else {
6455
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
6456
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
6457
            return -1;
6458
        }
6459
    } else if (stage_type == StagePB::INTERNAL) {
6460
        int idx = stoi(object_store_info.id());
6461
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6462
            LOG(WARNING) << "invalid idx: " << idx;
6463
            return -1;
6464
        }
6465
6466
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
6467
        auto conf = S3Conf::from_obj_store_info(old_obj);
6468
        if (!conf) {
6469
            return -1;
6470
        }
6471
6472
        s3_conf = std::move(*conf);
6473
        s3_conf.prefix = object_store_info.prefix();
6474
    } else {
6475
        LOG(WARNING) << "unknown stage type " << stage_type;
6476
        return -1;
6477
    }
6478
6479
    std::shared_ptr<S3Accessor> s3_accessor;
6480
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
6481
    if (ret != 0) {
6482
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
6483
        return -1;
6484
    }
6485
6486
    *accessor = std::move(s3_accessor);
6487
#endif
6488
3
    return 0;
6489
5
}
6490
6491
11
int InstanceRecycler::recycle_stage() {
6492
11
    int64_t num_scanned = 0;
6493
11
    int64_t num_recycled = 0;
6494
11
    const std::string task_name = "recycle_stage";
6495
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6496
6497
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
6498
6499
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6500
11
    register_recycle_task(task_name, start_time);
6501
6502
11
    DORIS_CLOUD_DEFER {
6503
11
        unregister_recycle_task(task_name);
6504
11
        int64_t cost =
6505
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6506
11
        metrics_context.finish_report();
6507
11
        LOG_WARNING("recycle stage, cost={}s", cost)
6508
11
                .tag("instance_id", instance_id_)
6509
11
                .tag("num_scanned", num_scanned)
6510
11
                .tag("num_recycled", num_recycled);
6511
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
6502
11
    DORIS_CLOUD_DEFER {
6503
11
        unregister_recycle_task(task_name);
6504
11
        int64_t cost =
6505
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6506
11
        metrics_context.finish_report();
6507
11
        LOG_WARNING("recycle stage, cost={}s", cost)
6508
11
                .tag("instance_id", instance_id_)
6509
11
                .tag("num_scanned", num_scanned)
6510
11
                .tag("num_recycled", num_recycled);
6511
11
    };
6512
6513
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
6514
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
6515
11
    std::string key0 = recycle_stage_key(key_info0);
6516
11
    std::string key1 = recycle_stage_key(key_info1);
6517
6518
11
    std::vector<std::string_view> stage_keys;
6519
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
6520
11
                         this](std::string_view k, std::string_view v) -> int {
6521
1
        ++num_scanned;
6522
1
        RecycleStagePB recycle_stage;
6523
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
6524
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
6525
0
            return -1;
6526
0
        }
6527
6528
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
6529
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6530
0
            LOG(WARNING) << "invalid idx: " << idx;
6531
0
            return -1;
6532
0
        }
6533
6534
1
        std::shared_ptr<StorageVaultAccessor> accessor;
6535
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
6536
1
                [&] {
6537
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
6538
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
6539
1
                    if (!s3_conf) {
6540
1
                        return -1;
6541
1
                    }
6542
6543
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
6544
1
                    std::shared_ptr<S3Accessor> s3_accessor;
6545
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
6546
1
                    if (ret != 0) {
6547
1
                        return -1;
6548
1
                    }
6549
6550
1
                    accessor = std::move(s3_accessor);
6551
1
                    return 0;
6552
1
                }(),
6553
1
                "recycle_stage:get_accessor", &accessor);
6554
6555
1
        if (ret != 0) {
6556
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
6557
0
            return ret;
6558
0
        }
6559
6560
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
6561
1
                .tag("instance_id", instance_id_)
6562
1
                .tag("stage_id", recycle_stage.stage().stage_id())
6563
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
6564
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
6565
1
                .tag("obj_info_id", idx)
6566
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
6567
1
        ret = accessor->delete_all();
6568
1
        if (ret != 0) {
6569
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
6570
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
6571
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
6572
0
                         << ", ret=" << ret;
6573
0
            return -1;
6574
0
        }
6575
1
        metrics_context.total_recycled_num = ++num_recycled;
6576
1
        metrics_context.report();
6577
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
6578
1
        stage_keys.push_back(k);
6579
1
        return 0;
6580
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6520
1
                         this](std::string_view k, std::string_view v) -> int {
6521
1
        ++num_scanned;
6522
1
        RecycleStagePB recycle_stage;
6523
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
6524
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
6525
0
            return -1;
6526
0
        }
6527
6528
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
6529
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6530
0
            LOG(WARNING) << "invalid idx: " << idx;
6531
0
            return -1;
6532
0
        }
6533
6534
1
        std::shared_ptr<StorageVaultAccessor> accessor;
6535
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
6536
1
                [&] {
6537
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
6538
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
6539
1
                    if (!s3_conf) {
6540
1
                        return -1;
6541
1
                    }
6542
6543
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
6544
1
                    std::shared_ptr<S3Accessor> s3_accessor;
6545
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
6546
1
                    if (ret != 0) {
6547
1
                        return -1;
6548
1
                    }
6549
6550
1
                    accessor = std::move(s3_accessor);
6551
1
                    return 0;
6552
1
                }(),
6553
1
                "recycle_stage:get_accessor", &accessor);
6554
6555
1
        if (ret != 0) {
6556
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
6557
0
            return ret;
6558
0
        }
6559
6560
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
6561
1
                .tag("instance_id", instance_id_)
6562
1
                .tag("stage_id", recycle_stage.stage().stage_id())
6563
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
6564
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
6565
1
                .tag("obj_info_id", idx)
6566
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
6567
1
        ret = accessor->delete_all();
6568
1
        if (ret != 0) {
6569
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
6570
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
6571
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
6572
0
                         << ", ret=" << ret;
6573
0
            return -1;
6574
0
        }
6575
1
        metrics_context.total_recycled_num = ++num_recycled;
6576
1
        metrics_context.report();
6577
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
6578
1
        stage_keys.push_back(k);
6579
1
        return 0;
6580
1
    };
6581
6582
11
    auto loop_done = [&stage_keys, this]() -> int {
6583
1
        if (stage_keys.empty()) return 0;
6584
1
        DORIS_CLOUD_DEFER {
6585
1
            stage_keys.clear();
6586
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6584
1
        DORIS_CLOUD_DEFER {
6585
1
            stage_keys.clear();
6586
1
        };
6587
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
6588
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
6589
0
            return -1;
6590
0
        }
6591
1
        return 0;
6592
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
6582
1
    auto loop_done = [&stage_keys, this]() -> int {
6583
1
        if (stage_keys.empty()) return 0;
6584
1
        DORIS_CLOUD_DEFER {
6585
1
            stage_keys.clear();
6586
1
        };
6587
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
6588
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
6589
0
            return -1;
6590
0
        }
6591
1
        return 0;
6592
1
    };
6593
11
    if (config::enable_recycler_stats_metrics) {
6594
0
        scan_and_statistics_stage();
6595
0
    }
6596
    // recycle_func and loop_done for scan and recycle
6597
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
6598
11
}
6599
6600
10
int InstanceRecycler::recycle_expired_stage_objects() {
6601
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
6602
6603
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6604
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
6605
6606
10
    DORIS_CLOUD_DEFER {
6607
10
        int64_t cost =
6608
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6609
10
        metrics_context.finish_report();
6610
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
6611
10
                .tag("instance_id", instance_id_);
6612
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
6606
10
    DORIS_CLOUD_DEFER {
6607
10
        int64_t cost =
6608
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6609
10
        metrics_context.finish_report();
6610
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
6611
10
                .tag("instance_id", instance_id_);
6612
10
    };
6613
6614
10
    int ret = 0;
6615
6616
10
    if (config::enable_recycler_stats_metrics) {
6617
0
        scan_and_statistics_expired_stage_objects();
6618
0
    }
6619
6620
10
    for (const auto& stage : instance_info_.stages()) {
6621
0
        std::stringstream ss;
6622
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
6623
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
6624
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
6625
0
           << ", prefix=" << stage.obj_info().prefix();
6626
6627
0
        if (stopped()) {
6628
0
            break;
6629
0
        }
6630
0
        if (stage.type() == StagePB::EXTERNAL) {
6631
0
            continue;
6632
0
        }
6633
0
        int idx = stoi(stage.obj_info().id());
6634
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6635
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
6636
0
            continue;
6637
0
        }
6638
6639
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
6640
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
6641
0
        if (!s3_conf) {
6642
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
6643
0
            continue;
6644
0
        }
6645
6646
0
        s3_conf->prefix = stage.obj_info().prefix();
6647
0
        std::shared_ptr<S3Accessor> accessor;
6648
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
6649
0
        if (ret1 != 0) {
6650
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
6651
0
            ret = -1;
6652
0
            continue;
6653
0
        }
6654
6655
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
6656
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
6657
0
            ret = -1;
6658
0
            continue;
6659
0
        }
6660
6661
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
6662
0
        int64_t expiration_time =
6663
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
6664
0
                config::internal_stage_objects_expire_time_second;
6665
0
        if (config::force_immediate_recycle) {
6666
0
            expiration_time = INT64_MAX;
6667
0
        }
6668
0
        ret1 = accessor->delete_all(expiration_time);
6669
0
        if (ret1 != 0) {
6670
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
6671
0
                         << ss.str();
6672
0
            ret = -1;
6673
0
            continue;
6674
0
        }
6675
0
        metrics_context.total_recycled_num++;
6676
0
        metrics_context.report();
6677
0
    }
6678
10
    return ret;
6679
10
}
6680
6681
181
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
6682
181
    std::lock_guard lock(recycle_tasks_mutex);
6683
181
    running_recycle_tasks[task_name] = start_time;
6684
181
}
6685
6686
181
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
6687
181
    std::lock_guard lock(recycle_tasks_mutex);
6688
181
    DCHECK(running_recycle_tasks[task_name] > 0);
6689
181
    running_recycle_tasks.erase(task_name);
6690
181
}
6691
6692
21
bool InstanceRecycler::check_recycle_tasks() {
6693
21
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
6694
21
    {
6695
21
        std::lock_guard lock(recycle_tasks_mutex);
6696
21
        tmp_running_recycle_tasks = running_recycle_tasks;
6697
21
    }
6698
6699
21
    bool found = false;
6700
21
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6701
21
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
6702
20
        int64_t cost = now - start_time;
6703
20
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
6704
20
            LOG_INFO("recycle task cost too much time cost={}s", cost)
6705
20
                    .tag("instance_id", instance_id_)
6706
20
                    .tag("task", task_name);
6707
20
            found = true;
6708
20
        }
6709
20
    }
6710
6711
21
    return found;
6712
21
}
6713
6714
// Scan and statistics indexes that need to be recycled
6715
0
int InstanceRecycler::scan_and_statistics_indexes() {
6716
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
6717
6718
0
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
6719
0
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
6720
0
    std::string index_key0;
6721
0
    std::string index_key1;
6722
0
    recycle_index_key(index_key_info0, &index_key0);
6723
0
    recycle_index_key(index_key_info1, &index_key1);
6724
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6725
6726
0
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
6727
0
        RecycleIndexPB index_pb;
6728
0
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
6729
0
            return 0;
6730
0
        }
6731
0
        int64_t current_time = ::time(nullptr);
6732
0
        if (current_time <
6733
0
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
6734
0
            return 0;
6735
0
        }
6736
        // decode index_id
6737
0
        auto k1 = k;
6738
0
        k1.remove_prefix(1);
6739
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6740
0
        decode_key(&k1, &out);
6741
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
6742
0
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
6743
0
        std::unique_ptr<Transaction> txn;
6744
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6745
0
        if (err != TxnErrorCode::TXN_OK) {
6746
0
            return 0;
6747
0
        }
6748
0
        std::string val;
6749
0
        err = txn->get(k, &val);
6750
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6751
0
            return 0;
6752
0
        }
6753
0
        if (err != TxnErrorCode::TXN_OK) {
6754
0
            return 0;
6755
0
        }
6756
0
        index_pb.Clear();
6757
0
        if (!index_pb.ParseFromString(val)) {
6758
0
            return 0;
6759
0
        }
6760
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
6761
0
            return 0;
6762
0
        }
6763
0
        metrics_context.total_need_recycle_num++;
6764
0
        return 0;
6765
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
6766
6767
0
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
6768
0
    metrics_context.report(true);
6769
0
    segment_metrics_context_.report(true);
6770
0
    tablet_metrics_context_.report(true);
6771
0
    return ret;
6772
0
}
6773
6774
// Scan and statistics partitions that need to be recycled
6775
0
int InstanceRecycler::scan_and_statistics_partitions() {
6776
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
6777
6778
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
6779
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
6780
0
    std::string part_key0;
6781
0
    std::string part_key1;
6782
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6783
6784
0
    recycle_partition_key(part_key_info0, &part_key0);
6785
0
    recycle_partition_key(part_key_info1, &part_key1);
6786
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
6787
0
        RecyclePartitionPB part_pb;
6788
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
6789
0
            return 0;
6790
0
        }
6791
0
        int64_t current_time = ::time(nullptr);
6792
0
        if (current_time <
6793
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
6794
0
            return 0;
6795
0
        }
6796
        // decode partition_id
6797
0
        auto k1 = k;
6798
0
        k1.remove_prefix(1);
6799
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6800
0
        decode_key(&k1, &out);
6801
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
6802
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
6803
        // Change state to RECYCLING
6804
0
        std::unique_ptr<Transaction> txn;
6805
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6806
0
        if (err != TxnErrorCode::TXN_OK) {
6807
0
            return 0;
6808
0
        }
6809
0
        std::string val;
6810
0
        err = txn->get(k, &val);
6811
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6812
0
            return 0;
6813
0
        }
6814
0
        if (err != TxnErrorCode::TXN_OK) {
6815
0
            return 0;
6816
0
        }
6817
0
        part_pb.Clear();
6818
0
        if (!part_pb.ParseFromString(val)) {
6819
0
            return 0;
6820
0
        }
6821
        // Partitions with PREPARED state MUST have no data
6822
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
6823
0
        int ret = 0;
6824
0
        for (int64_t index_id : part_pb.index_id()) {
6825
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
6826
0
                                            partition_id, is_empty_tablet) != 0) {
6827
0
                ret = 0;
6828
0
            }
6829
0
        }
6830
0
        metrics_context.total_need_recycle_num++;
6831
0
        return ret;
6832
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler30scan_and_statistics_partitionsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler30scan_and_statistics_partitionsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
6833
6834
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
6835
0
    metrics_context.report(true);
6836
0
    segment_metrics_context_.report(true);
6837
0
    tablet_metrics_context_.report(true);
6838
0
    return ret;
6839
0
}
6840
6841
// Scan and statistics rowsets that need to be recycled
6842
0
int InstanceRecycler::scan_and_statistics_rowsets() {
6843
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
6844
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
6845
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
6846
0
    std::string recyc_rs_key0;
6847
0
    std::string recyc_rs_key1;
6848
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
6849
0
                recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
6850
0
       int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6851
6852
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6853
0
        RecycleRowsetPB rowset;
6854
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6855
0
            return 0;
6856
0
        }
6857
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
6858
0
        int64_t current_time = ::time(nullptr);
6859
0
        if (current_time <
6860
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
6861
0
            return 0;
6862
0
        }
6863
6864
0
        if (!rowset.has_type()) {
6865
0
            if (!rowset.has_resource_id()) [[unlikely]] {
6866
0
                return 0;
6867
0
            }
6868
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6869
0
                return 0;
6870
0
            }
6871
0
            metrics_context.total_need_recycle_num++;
6872
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
6873
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
6874
0
            segment_metrics_context_.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
6875
0
            return 0;
6876
0
        }
6877
6878
0
        if(!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled()) {
6879
0
            return 0;
6880
0
        }
6881
6882
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
6883
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
6884
0
                return 0;
6885
0
            }
6886
0
        }
6887
0
        metrics_context.total_need_recycle_num++;
6888
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
6889
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
6890
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
6891
0
        return 0;
6892
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_rowsetsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_rowsetsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
6893
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
6894
0
    metrics_context.report(true);
6895
0
    segment_metrics_context_.report(true);
6896
0
    return ret;
6897
0
}
6898
6899
// Scan and statistics tmp_rowsets that need to be recycled
6900
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
6901
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
6902
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
6903
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
6904
0
    std::string tmp_rs_key0;
6905
0
    std::string tmp_rs_key1;
6906
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
6907
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
6908
6909
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6910
6911
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
6912
0
        doris::RowsetMetaCloudPB rowset;
6913
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6914
0
            return 0;
6915
0
        }
6916
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6917
0
        int64_t current_time = ::time(nullptr);
6918
0
        if (current_time < expiration) {
6919
0
            return 0;
6920
0
        }
6921
6922
0
        DCHECK_GT(rowset.txn_id(), 0)
6923
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
6924
6925
0
        if(!rowset.has_is_recycled() || !rowset.is_recycled()) {
6926
0
            return 0;
6927
0
        }
6928
6929
0
        if (!rowset.has_resource_id()) {
6930
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6931
0
                return 0;
6932
0
            }
6933
0
            return 0;
6934
0
        }
6935
6936
0
        metrics_context.total_need_recycle_num++;
6937
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
6938
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
6939
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
6940
0
        return 0;
6941
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler31scan_and_statistics_tmp_rowsetsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler31scan_and_statistics_tmp_rowsetsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
6942
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
6943
0
    metrics_context.report(true);
6944
0
    segment_metrics_context_.report(true);
6945
0
    return ret;
6946
0
}
6947
6948
// Scan and statistics abort_timeout_txn that need to be recycled
6949
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
6950
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
6951
6952
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6953
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6954
0
    std::string begin_txn_running_key;
6955
0
    std::string end_txn_running_key;
6956
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6957
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6958
6959
0
    int64_t current_time =
6960
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6961
6962
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
6963
0
                                               std::string_view k, std::string_view v) -> int {
6964
0
        std::unique_ptr<Transaction> txn;
6965
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6966
0
        if (err != TxnErrorCode::TXN_OK) {
6967
0
            return 0;
6968
0
        }
6969
0
        std::string_view k1 = k;
6970
0
        k1.remove_prefix(1);
6971
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6972
0
        if (decode_key(&k1, &out) != 0) {
6973
0
            return 0;
6974
0
        }
6975
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6976
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6977
        // Update txn_info
6978
0
        std::string txn_inf_key, txn_inf_val;
6979
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6980
0
        err = txn->get(txn_inf_key, &txn_inf_val);
6981
0
        if (err != TxnErrorCode::TXN_OK) {
6982
0
            return 0;
6983
0
        }
6984
0
        TxnInfoPB txn_info;
6985
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
6986
0
            return 0;
6987
0
        }
6988
6989
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
6990
0
            TxnRunningPB txn_running_pb;
6991
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6992
0
                return 0;
6993
0
            }
6994
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6995
0
                return 0;
6996
0
            }
6997
0
            metrics_context.total_need_recycle_num++;
6998
0
        }
6999
0
        return 0;
7000
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler37scan_and_statistics_abort_timeout_txnEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler37scan_and_statistics_abort_timeout_txnEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
7001
7002
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key, std::move(handle_abort_timeout_txn_kv));
7003
0
    metrics_context.report(true);
7004
0
    return ret;
7005
0
}
7006
7007
// Scan and statistics expired_txn_label that need to be recycled
7008
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
7009
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
7010
7011
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7012
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7013
0
    std::string begin_recycle_txn_key;
7014
0
    std::string end_recycle_txn_key;
7015
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7016
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7017
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7018
0
    int64_t current_time_ms =
7019
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7020
7021
    // for calculate the total num or bytes of recyled objects
7022
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
7023
0
        RecycleTxnPB recycle_txn_pb;
7024
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7025
0
            return 0;
7026
0
        }
7027
0
        if ((config::force_immediate_recycle) ||
7028
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7029
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7030
0
             current_time_ms)) {
7031
0
            metrics_context.total_need_recycle_num++;
7032
0
        }
7033
0
        return 0;
7034
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler37scan_and_statistics_expired_txn_labelEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler37scan_and_statistics_expired_txn_labelEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
7035
7036
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key, std::move(handle_expired_txn_label_kv));
7037
0
    metrics_context.report(true);
7038
0
    return ret;
7039
0
}
7040
7041
// Scan and statistics copy_jobs that need to be recycled
7042
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
7043
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
7044
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7045
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7046
0
    std::string key0;
7047
0
    std::string key1;
7048
0
    copy_job_key(key_info0, &key0);
7049
0
    copy_job_key(key_info1, &key1);
7050
7051
    // for calculate the total num or bytes of recyled objects
7052
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
7053
0
        CopyJobPB copy_job;
7054
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7055
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7056
0
            return 0;
7057
0
        }
7058
7059
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7060
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
7061
0
                int64_t current_time =
7062
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7063
0
                if (copy_job.finish_time_ms() > 0) {
7064
0
                    if (!config::force_immediate_recycle &&
7065
0
                        current_time < copy_job.finish_time_ms() +
7066
0
                                               config::copy_job_max_retention_second * 1000) {
7067
0
                        return 0;
7068
0
                    }
7069
0
                } else {
7070
0
                    if (!config::force_immediate_recycle &&
7071
0
                        current_time < copy_job.start_time_ms() +
7072
0
                                               config::copy_job_max_retention_second * 1000) {
7073
0
                        return 0;
7074
0
                    }
7075
0
                }
7076
0
            }
7077
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7078
0
            int64_t current_time =
7079
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7080
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7081
0
                return 0;
7082
0
            }
7083
0
        }
7084
0
        metrics_context.total_need_recycle_num++;
7085
0
        return 0;
7086
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29scan_and_statistics_copy_jobsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29scan_and_statistics_copy_jobsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
7087
7088
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7089
0
    metrics_context.report(true);
7090
0
    return ret;
7091
0
}
7092
7093
// Scan and statistics stage that need to be recycled
7094
0
int InstanceRecycler::scan_and_statistics_stage() {
7095
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
7096
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7097
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7098
0
    std::string key0 = recycle_stage_key(key_info0);
7099
0
    std::string key1 = recycle_stage_key(key_info1);
7100
7101
    // for calculate the total num or bytes of recyled objects
7102
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
7103
0
                                                        std::string_view v) -> int {
7104
0
        RecycleStagePB recycle_stage;
7105
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7106
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7107
0
            return 0;
7108
0
        }
7109
7110
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
7111
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7112
0
            LOG(WARNING) << "invalid idx: " << idx;
7113
0
            return 0;
7114
0
        }
7115
7116
0
        std::shared_ptr<StorageVaultAccessor> accessor;
7117
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7118
0
                [&] {
7119
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7120
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7121
0
                    if (!s3_conf) {
7122
0
                        return 0;
7123
0
                    }
7124
7125
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7126
0
                    std::shared_ptr<S3Accessor> s3_accessor;
7127
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7128
0
                    if (ret != 0) {
7129
0
                        return 0;
7130
0
                    }
7131
7132
0
                    accessor = std::move(s3_accessor);
7133
0
                    return 0;
7134
0
                }(),
7135
0
                "recycle_stage:get_accessor", &accessor);
7136
7137
0
        if (ret != 0) {
7138
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7139
0
            return 0;
7140
0
        }
7141
7142
0
        metrics_context.total_need_recycle_num++;
7143
0
        return 0;
7144
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25scan_and_statistics_stageEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25scan_and_statistics_stageEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
7145
7146
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7147
0
    metrics_context.report(true);
7148
0
    return ret;
7149
0
}
7150
7151
// Scan and statistics expired_stage_objects that need to be recycled
7152
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
7153
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7154
7155
    // for calculate the total num or bytes of recyled objects
7156
0
    auto scan_and_statistics = [&metrics_context, this]() {
7157
0
        for (const auto& stage : instance_info_.stages()) {
7158
0
            if (stopped()) {
7159
0
                break;
7160
0
            }
7161
0
            if (stage.type() == StagePB::EXTERNAL) {
7162
0
                continue;
7163
0
            }
7164
0
            int idx = stoi(stage.obj_info().id());
7165
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
7166
0
                continue;
7167
0
            }
7168
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
7169
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7170
0
            if (!s3_conf) {
7171
0
                continue;
7172
0
            }
7173
0
            s3_conf->prefix = stage.obj_info().prefix();
7174
0
            std::shared_ptr<S3Accessor> accessor;
7175
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
7176
0
            if (ret1 != 0) {
7177
0
                continue;
7178
0
            }
7179
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7180
0
                continue;
7181
0
            }
7182
0
            metrics_context.total_need_recycle_num++;
7183
0
        }
7184
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
7185
7186
0
    scan_and_statistics();
7187
0
    metrics_context.report(true);
7188
0
    return 0;
7189
0
}
7190
7191
// Scan and statistics versions that need to be recycled
7192
0
int InstanceRecycler::scan_and_statistics_versions() {
7193
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
7194
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
7195
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
7196
7197
0
    int64_t last_scanned_table_id = 0;
7198
0
    bool is_recycled = false; // Is last scanned kv recycled
7199
    // for calculate the total num or bytes of recyled objects
7200
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
7201
0
                                       std::string_view k, std::string_view) {
7202
0
        auto k1 = k;
7203
0
        k1.remove_prefix(1);
7204
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
7205
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7206
0
        decode_key(&k1, &out);
7207
0
        DCHECK_EQ(out.size(), 6) << k;
7208
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
7209
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
7210
0
            metrics_context.total_need_recycle_num +=
7211
0
                    is_recycled; // Version kv of this table has been recycled
7212
0
            return 0;
7213
0
        }
7214
0
        last_scanned_table_id = table_id;
7215
0
        is_recycled = false;
7216
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
7217
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
7218
0
        std::unique_ptr<Transaction> txn;
7219
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7220
0
        if (err != TxnErrorCode::TXN_OK) {
7221
0
            return 0;
7222
0
        }
7223
0
        std::unique_ptr<RangeGetIterator> iter;
7224
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
7225
0
        if (err != TxnErrorCode::TXN_OK) {
7226
0
            return 0;
7227
0
        }
7228
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
7229
0
            return 0;
7230
0
        }
7231
0
        metrics_context.total_need_recycle_num++;
7232
0
        is_recycled = true;
7233
0
        return 0;
7234
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler28scan_and_statistics_versionsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler28scan_and_statistics_versionsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
7235
7236
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
7237
0
    metrics_context.report(true);
7238
0
    return ret;
7239
0
}
7240
7241
// Scan and statistics restore jobs that need to be recycled
7242
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
7243
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
7244
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
7245
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
7246
0
    std::string restore_job_key0;
7247
0
    std::string restore_job_key1;
7248
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
7249
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
7250
7251
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7252
7253
    // for calculate the total num or bytes of recyled objects
7254
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
7255
0
        RestoreJobCloudPB restore_job_pb;
7256
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
7257
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
7258
0
            return 0;
7259
0
        }
7260
0
        int64_t expiration =
7261
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
7262
0
        int64_t current_time = ::time(nullptr);
7263
0
        if (current_time < expiration) { // not expired
7264
0
            return 0;
7265
0
        }
7266
0
        metrics_context.total_need_recycle_num++;
7267
0
        if(restore_job_pb.need_recycle_data()) {
7268
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
7269
0
        }
7270
0
        return 0;
7271
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler32scan_and_statistics_restore_jobsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler32scan_and_statistics_restore_jobsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
7272
7273
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
7274
0
    metrics_context.report(true);
7275
0
    return ret;
7276
0
}
7277
7278
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
7279
3
    if (!should_recycle_versioned_keys()) {
7280
0
        return;
7281
0
    }
7282
7283
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
7284
7285
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
7286
3
    if (recycle_checker.init() != 0) {
7287
0
        return;
7288
0
    }
7289
7290
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
7291
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
7292
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
7293
7294
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
7295
8
    for (; iter->valid(); iter->next()) {
7296
5
        OperationLogPB operation_log;
7297
5
        if (!iter->parse_value(&operation_log)) {
7298
0
            continue;
7299
0
        }
7300
7301
5
        std::string_view key = iter->key();
7302
5
        Versionstamp log_versionstamp;
7303
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
7304
0
            continue;
7305
0
        }
7306
7307
5
        OperationLogReferenceInfo ref_info;
7308
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
7309
5
                                         &ref_info)) {
7310
4
            metrics_context.total_need_recycle_num++;
7311
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
7312
4
        }
7313
5
    }
7314
7315
3
    metrics_context.report(true);
7316
3
}
7317
7318
int InstanceRecycler::classify_rowset_task_by_ref_count(
7319
60
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
7320
60
    constexpr int MAX_RETRY = 10;
7321
60
    const auto& rowset_meta = task.rowset_meta;
7322
60
    int64_t tablet_id = rowset_meta.tablet_id();
7323
60
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
7324
60
    std::string_view reference_instance_id = instance_id_;
7325
60
    if (rowset_meta.has_reference_instance_id()) {
7326
5
        reference_instance_id = rowset_meta.reference_instance_id();
7327
5
    }
7328
7329
61
    for (int i = 0; i < MAX_RETRY; ++i) {
7330
61
        std::unique_ptr<Transaction> txn;
7331
61
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7332
61
        if (err != TxnErrorCode::TXN_OK) {
7333
0
            LOG_WARNING("failed to create txn when classifying rowset task")
7334
0
                    .tag("instance_id", instance_id_)
7335
0
                    .tag("tablet_id", tablet_id)
7336
0
                    .tag("rowset_id", rowset_id)
7337
0
                    .tag("err", err);
7338
0
            return -1;
7339
0
        }
7340
7341
61
        std::string rowset_ref_count_key =
7342
61
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
7343
61
        task.rowset_ref_count_key = rowset_ref_count_key;
7344
7345
61
        int64_t ref_count = 0;
7346
61
        {
7347
61
            std::string value;
7348
61
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
7349
61
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7350
0
                ref_count = 1;
7351
61
            } else if (err != TxnErrorCode::TXN_OK) {
7352
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
7353
0
                        .tag("instance_id", instance_id_)
7354
0
                        .tag("tablet_id", tablet_id)
7355
0
                        .tag("rowset_id", rowset_id)
7356
0
                        .tag("err", err);
7357
0
                return -1;
7358
61
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
7359
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
7360
0
                        .tag("instance_id", instance_id_)
7361
0
                        .tag("tablet_id", tablet_id)
7362
0
                        .tag("rowset_id", rowset_id)
7363
0
                        .tag("value", hex(value));
7364
0
                return -1;
7365
0
            }
7366
61
        }
7367
7368
61
        if (ref_count > 1) {
7369
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
7370
12
            txn->atomic_add(rowset_ref_count_key, -1);
7371
12
            LOG_INFO("decrease rowset data ref count in classification phase")
7372
12
                    .tag("instance_id", instance_id_)
7373
12
                    .tag("tablet_id", tablet_id)
7374
12
                    .tag("rowset_id", rowset_id)
7375
12
                    .tag("ref_count", ref_count - 1)
7376
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
7377
7378
12
            if (!task.recycle_rowset_key.empty()) {
7379
0
                txn->remove(task.recycle_rowset_key);
7380
0
                LOG_INFO("remove recycle rowset key in classification phase")
7381
0
                        .tag("key", hex(task.recycle_rowset_key));
7382
0
            }
7383
12
            if (!task.non_versioned_rowset_key.empty()) {
7384
12
                txn->remove(task.non_versioned_rowset_key);
7385
12
                LOG_INFO("remove non versioned rowset key in classification phase")
7386
12
                        .tag("key", hex(task.non_versioned_rowset_key));
7387
12
            }
7388
7389
12
            err = txn->commit();
7390
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
7391
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
7392
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
7393
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
7394
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
7395
1
                continue;
7396
11
            } else if (err != TxnErrorCode::TXN_OK) {
7397
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
7398
0
                        .tag("instance_id", instance_id_)
7399
0
                        .tag("tablet_id", tablet_id)
7400
0
                        .tag("rowset_id", rowset_id)
7401
0
                        .tag("err", err);
7402
0
                return -1;
7403
0
            }
7404
11
            return 1; // handled, not added to batch delete
7405
49
        } else {
7406
            // ref_count == 1: Add to batch delete plan without modifying any KV.
7407
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
7408
49
            LOG_INFO("add rowset to batch delete plan")
7409
49
                    .tag("instance_id", instance_id_)
7410
49
                    .tag("tablet_id", tablet_id)
7411
49
                    .tag("rowset_id", rowset_id)
7412
49
                    .tag("resource_id", rowset_meta.resource_id())
7413
49
                    .tag("ref_count", ref_count);
7414
7415
49
            batch_delete_tasks.push_back(std::move(task));
7416
49
            return 0; // added to batch delete
7417
49
        }
7418
61
    }
7419
7420
0
    LOG_WARNING("failed to classify rowset task after retry")
7421
0
            .tag("instance_id", instance_id_)
7422
0
            .tag("tablet_id", tablet_id)
7423
0
            .tag("rowset_id", rowset_id)
7424
0
            .tag("retry", MAX_RETRY);
7425
0
    return -1;
7426
60
}
7427
7428
10
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
7429
10
    int ret = 0;
7430
49
    for (const auto& task : tasks) {
7431
49
        int64_t tablet_id = task.rowset_meta.tablet_id();
7432
49
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
7433
7434
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
7435
        // so we don't need to call it again here.
7436
7437
        // Remove all metadata keys in one transaction
7438
49
        std::unique_ptr<Transaction> txn;
7439
49
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7440
49
        if (err != TxnErrorCode::TXN_OK) {
7441
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
7442
0
                    .tag("instance_id", instance_id_)
7443
0
                    .tag("tablet_id", tablet_id)
7444
0
                    .tag("rowset_id", rowset_id)
7445
0
                    .tag("err", err);
7446
0
            ret = -1;
7447
0
            continue;
7448
0
        }
7449
7450
49
        std::string_view reference_instance_id = instance_id_;
7451
49
        if (task.rowset_meta.has_reference_instance_id()) {
7452
0
            reference_instance_id = task.rowset_meta.reference_instance_id();
7453
0
        }
7454
7455
49
        txn->remove(task.rowset_ref_count_key);
7456
49
        LOG_INFO("delete rowset data ref count key in cleanup phase")
7457
49
                .tag("instance_id", instance_id_)
7458
49
                .tag("tablet_id", tablet_id)
7459
49
                .tag("rowset_id", rowset_id)
7460
49
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
7461
7462
49
        std::string dbm_start_key =
7463
49
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
7464
49
        std::string dbm_end_key = meta_delete_bitmap_key(
7465
49
                {reference_instance_id, tablet_id, rowset_id,
7466
49
                 std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
7467
49
        txn->remove(dbm_start_key, dbm_end_key);
7468
49
        LOG_INFO("remove delete bitmap kv in cleanup phase")
7469
49
                .tag("instance_id", instance_id_)
7470
49
                .tag("tablet_id", tablet_id)
7471
49
                .tag("rowset_id", rowset_id)
7472
49
                .tag("begin", hex(dbm_start_key))
7473
49
                .tag("end", hex(dbm_end_key));
7474
7475
49
        std::string versioned_dbm_start_key =
7476
49
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
7477
49
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
7478
49
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
7479
49
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
7480
49
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
7481
49
                .tag("instance_id", instance_id_)
7482
49
                .tag("tablet_id", tablet_id)
7483
49
                .tag("rowset_id", rowset_id)
7484
49
                .tag("begin", hex(versioned_dbm_start_key))
7485
49
                .tag("end", hex(versioned_dbm_end_key));
7486
7487
        // Remove versioned meta rowset key
7488
49
        if (!task.versioned_rowset_key.empty()) {
7489
49
            versioned::document_remove<RowsetMetaCloudPB>(
7490
49
                txn.get(), task.versioned_rowset_key, task.versionstamp);
7491
49
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
7492
49
                    .tag("instance_id", instance_id_)
7493
49
                    .tag("tablet_id", tablet_id)
7494
49
                    .tag("rowset_id", rowset_id)
7495
49
                    .tag("key_prefix", hex(task.versioned_rowset_key));
7496
49
        }
7497
7498
49
        if (!task.non_versioned_rowset_key.empty()) {
7499
49
            txn->remove(task.non_versioned_rowset_key);
7500
49
            LOG_INFO("remove non versioned rowset key in cleanup phase")
7501
49
                    .tag("instance_id", instance_id_)
7502
49
                    .tag("tablet_id", tablet_id)
7503
49
                    .tag("rowset_id", rowset_id)
7504
49
                    .tag("key", hex(task.non_versioned_rowset_key));
7505
49
        }
7506
7507
        // Remove recycle_rowset_key last to ensure retry safety:
7508
        // if cleanup fails, this key remains and triggers next round retry.
7509
49
        if (!task.recycle_rowset_key.empty()) {
7510
0
            txn->remove(task.recycle_rowset_key);
7511
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
7512
0
                    .tag("instance_id", instance_id_)
7513
0
                    .tag("tablet_id", tablet_id)
7514
0
                    .tag("rowset_id", rowset_id)
7515
0
                    .tag("key", hex(task.recycle_rowset_key));
7516
0
        }
7517
7518
49
        err = txn->commit();
7519
49
        if (err != TxnErrorCode::TXN_OK) {
7520
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
7521
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
7522
0
                    .tag("instance_id", instance_id_)
7523
0
                    .tag("tablet_id", tablet_id)
7524
0
                    .tag("rowset_id", rowset_id)
7525
0
                    .tag("err", err);
7526
0
            ret = -1;
7527
0
            continue;
7528
0
        }
7529
7530
49
        LOG_INFO("cleanup rowset metadata success")
7531
49
                .tag("instance_id", instance_id_)
7532
49
                .tag("tablet_id", tablet_id)
7533
49
                .tag("rowset_id", rowset_id);
7534
49
    }
7535
10
    return ret;
7536
10
}
7537
7538
} // namespace doris::cloud