Coverage Report

Created: 2026-04-01 15:48

/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/kv_cache.h"
49
#include "common/stopwatch.h"
50
#include "meta-service/meta_service.h"
51
#include "meta-service/meta_service_helper.h"
52
#include "meta-service/meta_service_schema.h"
53
#include "meta-store/blob_message.h"
54
#include "meta-store/meta_reader.h"
55
#include "meta-store/txn_kv.h"
56
#include "meta-store/txn_kv_error.h"
57
#include "meta-store/versioned_value.h"
58
#include "recycler/checker.h"
59
#ifdef ENABLE_HDFS_STORAGE_VAULT
60
#include "recycler/hdfs_accessor.h"
61
#endif
62
#include "recycler/s3_accessor.h"
63
#include "recycler/storage_vault_accessor.h"
64
#ifdef UNIT_TEST
65
#include "../test/mock_accessor.h"
66
#endif
67
#include "common/bvars.h"
68
#include "common/config.h"
69
#include "common/encryption_util.h"
70
#include "common/logging.h"
71
#include "common/simple_thread_pool.h"
72
#include "common/util.h"
73
#include "cpp/sync_point.h"
74
#include "meta-store/codec.h"
75
#include "meta-store/document_message.h"
76
#include "meta-store/keys.h"
77
#include "recycler/recycler_service.h"
78
#include "recycler/sync_executor.h"
79
#include "recycler/util.h"
80
81
namespace doris::cloud {
82
83
using namespace std::chrono;
84
85
namespace {
86
87
0
int64_t packed_file_retry_sleep_ms() {
88
0
    const int64_t min_ms = std::max<int64_t>(0, config::packed_file_txn_retry_sleep_min_ms);
89
0
    const int64_t max_ms = std::max<int64_t>(min_ms, config::packed_file_txn_retry_sleep_max_ms);
90
0
    thread_local std::mt19937_64 gen(std::random_device {}());
91
0
    std::uniform_int_distribution<int64_t> dist(min_ms, max_ms);
92
0
    return dist(gen);
93
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
94
95
0
void sleep_for_packed_file_retry() {
96
0
    std::this_thread::sleep_for(std::chrono::milliseconds(packed_file_retry_sleep_ms()));
97
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
98
99
} // namespace
100
101
// return 0 for success get a key, 1 for key not found, negative for error
102
0
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
103
0
    std::unique_ptr<Transaction> txn;
104
0
    TxnErrorCode err = txn_kv->create_txn(&txn);
105
0
    if (err != TxnErrorCode::TXN_OK) {
106
0
        return -1;
107
0
    }
108
0
    switch (txn->get(key, &val, true)) {
109
0
    case TxnErrorCode::TXN_OK:
110
0
        return 0;
111
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
112
0
        return 1;
113
0
    default:
114
0
        return -1;
115
0
    };
116
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
117
118
// 0 for success, negative for error
119
static int txn_get(TxnKv* txn_kv, std::string_view begin, std::string_view end,
120
337
                   std::unique_ptr<RangeGetIterator>& it) {
121
337
    std::unique_ptr<Transaction> txn;
122
337
    TxnErrorCode err = txn_kv->create_txn(&txn);
123
337
    if (err != TxnErrorCode::TXN_OK) {
124
0
        return -1;
125
0
    }
126
337
    switch (txn->get(begin, end, &it, true)) {
127
337
    case TxnErrorCode::TXN_OK:
128
337
        return 0;
129
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
130
0
        return 1;
131
0
    default:
132
0
        return -1;
133
337
    };
134
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
120
31
                   std::unique_ptr<RangeGetIterator>& it) {
121
31
    std::unique_ptr<Transaction> txn;
122
31
    TxnErrorCode err = txn_kv->create_txn(&txn);
123
31
    if (err != TxnErrorCode::TXN_OK) {
124
0
        return -1;
125
0
    }
126
31
    switch (txn->get(begin, end, &it, true)) {
127
31
    case TxnErrorCode::TXN_OK:
128
31
        return 0;
129
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
130
0
        return 1;
131
0
    default:
132
0
        return -1;
133
31
    };
134
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
120
306
                   std::unique_ptr<RangeGetIterator>& it) {
121
306
    std::unique_ptr<Transaction> txn;
122
306
    TxnErrorCode err = txn_kv->create_txn(&txn);
123
306
    if (err != TxnErrorCode::TXN_OK) {
124
0
        return -1;
125
0
    }
126
306
    switch (txn->get(begin, end, &it, true)) {
127
306
    case TxnErrorCode::TXN_OK:
128
306
        return 0;
129
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
130
0
        return 1;
131
0
    default:
132
0
        return -1;
133
306
    };
134
0
}
135
136
// return 0 for success otherwise error
137
6
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
138
6
    std::unique_ptr<Transaction> txn;
139
6
    TxnErrorCode err = txn_kv->create_txn(&txn);
140
6
    if (err != TxnErrorCode::TXN_OK) {
141
0
        return -1;
142
0
    }
143
10
    for (auto k : keys) {
144
10
        txn->remove(k);
145
10
    }
146
6
    switch (txn->commit()) {
147
6
    case TxnErrorCode::TXN_OK:
148
6
        return 0;
149
0
    case TxnErrorCode::TXN_CONFLICT:
150
0
        return -1;
151
0
    default:
152
0
        return -1;
153
6
    }
154
6
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
137
1
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
138
1
    std::unique_ptr<Transaction> txn;
139
1
    TxnErrorCode err = txn_kv->create_txn(&txn);
140
1
    if (err != TxnErrorCode::TXN_OK) {
141
0
        return -1;
142
0
    }
143
1
    for (auto k : keys) {
144
1
        txn->remove(k);
145
1
    }
146
1
    switch (txn->commit()) {
147
1
    case TxnErrorCode::TXN_OK:
148
1
        return 0;
149
0
    case TxnErrorCode::TXN_CONFLICT:
150
0
        return -1;
151
0
    default:
152
0
        return -1;
153
1
    }
154
1
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
137
5
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
138
5
    std::unique_ptr<Transaction> txn;
139
5
    TxnErrorCode err = txn_kv->create_txn(&txn);
140
5
    if (err != TxnErrorCode::TXN_OK) {
141
0
        return -1;
142
0
    }
143
9
    for (auto k : keys) {
144
9
        txn->remove(k);
145
9
    }
146
5
    switch (txn->commit()) {
147
5
    case TxnErrorCode::TXN_OK:
148
5
        return 0;
149
0
    case TxnErrorCode::TXN_CONFLICT:
150
0
        return -1;
151
0
    default:
152
0
        return -1;
153
5
    }
154
5
}
155
156
// return 0 for success otherwise error
157
125
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
158
125
    std::unique_ptr<Transaction> txn;
159
125
    TxnErrorCode err = txn_kv->create_txn(&txn);
160
125
    if (err != TxnErrorCode::TXN_OK) {
161
0
        return -1;
162
0
    }
163
106k
    for (auto& k : keys) {
164
106k
        txn->remove(k);
165
106k
    }
166
125
    switch (txn->commit()) {
167
125
    case TxnErrorCode::TXN_OK:
168
125
        return 0;
169
0
    case TxnErrorCode::TXN_CONFLICT:
170
0
        return -1;
171
0
    default:
172
0
        return -1;
173
125
    }
174
125
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
157
33
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
158
33
    std::unique_ptr<Transaction> txn;
159
33
    TxnErrorCode err = txn_kv->create_txn(&txn);
160
33
    if (err != TxnErrorCode::TXN_OK) {
161
0
        return -1;
162
0
    }
163
33
    for (auto& k : keys) {
164
16
        txn->remove(k);
165
16
    }
166
33
    switch (txn->commit()) {
167
33
    case TxnErrorCode::TXN_OK:
168
33
        return 0;
169
0
    case TxnErrorCode::TXN_CONFLICT:
170
0
        return -1;
171
0
    default:
172
0
        return -1;
173
33
    }
174
33
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
157
92
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
158
92
    std::unique_ptr<Transaction> txn;
159
92
    TxnErrorCode err = txn_kv->create_txn(&txn);
160
92
    if (err != TxnErrorCode::TXN_OK) {
161
0
        return -1;
162
0
    }
163
106k
    for (auto& k : keys) {
164
106k
        txn->remove(k);
165
106k
    }
166
92
    switch (txn->commit()) {
167
92
    case TxnErrorCode::TXN_OK:
168
92
        return 0;
169
0
    case TxnErrorCode::TXN_CONFLICT:
170
0
        return -1;
171
0
    default:
172
0
        return -1;
173
92
    }
174
92
}
175
176
// return 0 for success otherwise error
177
[[maybe_unused]] static int txn_remove(TxnKv* txn_kv, std::string_view begin,
178
106k
                                       std::string_view end) {
179
106k
    std::unique_ptr<Transaction> txn;
180
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
181
106k
    if (err != TxnErrorCode::TXN_OK) {
182
0
        return -1;
183
0
    }
184
106k
    txn->remove(begin, end);
185
106k
    switch (txn->commit()) {
186
106k
    case TxnErrorCode::TXN_OK:
187
106k
        return 0;
188
0
    case TxnErrorCode::TXN_CONFLICT:
189
0
        return -1;
190
0
    default:
191
0
        return -1;
192
106k
    }
193
106k
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
178
16
                                       std::string_view end) {
179
16
    std::unique_ptr<Transaction> txn;
180
16
    TxnErrorCode err = txn_kv->create_txn(&txn);
181
16
    if (err != TxnErrorCode::TXN_OK) {
182
0
        return -1;
183
0
    }
184
16
    txn->remove(begin, end);
185
16
    switch (txn->commit()) {
186
16
    case TxnErrorCode::TXN_OK:
187
16
        return 0;
188
0
    case TxnErrorCode::TXN_CONFLICT:
189
0
        return -1;
190
0
    default:
191
0
        return -1;
192
16
    }
193
16
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
178
106k
                                       std::string_view end) {
179
106k
    std::unique_ptr<Transaction> txn;
180
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
181
106k
    if (err != TxnErrorCode::TXN_OK) {
182
0
        return -1;
183
0
    }
184
106k
    txn->remove(begin, end);
185
106k
    switch (txn->commit()) {
186
106k
    case TxnErrorCode::TXN_OK:
187
106k
        return 0;
188
0
    case TxnErrorCode::TXN_CONFLICT:
189
0
        return -1;
190
0
    default:
191
0
        return -1;
192
106k
    }
193
106k
}
194
195
void scan_restore_job_rowset(
196
        Transaction* txn, const std::string& instance_id, int64_t tablet_id, MetaServiceCode& code,
197
        std::string& msg,
198
        std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>* restore_job_rs_metas);
199
200
static inline void check_recycle_task(const std::string& instance_id, const std::string& task_name,
201
                                      int64_t num_scanned, int64_t num_recycled,
202
52
                                      int64_t start_time) {
203
52
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
204
0
        int64_t cost =
205
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
206
0
        if (cost > config::recycle_task_threshold_seconds) {
207
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
208
0
                    .tag("instance_id", instance_id)
209
0
                    .tag("task", task_name)
210
0
                    .tag("num_scanned", num_scanned)
211
0
                    .tag("num_recycled", num_recycled);
212
0
        }
213
0
    }
214
52
    return;
215
52
}
recycler.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
202
2
                                      int64_t start_time) {
203
2
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
204
0
        int64_t cost =
205
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
206
0
        if (cost > config::recycle_task_threshold_seconds) {
207
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
208
0
                    .tag("instance_id", instance_id)
209
0
                    .tag("task", task_name)
210
0
                    .tag("num_scanned", num_scanned)
211
0
                    .tag("num_recycled", num_recycled);
212
0
        }
213
0
    }
214
2
    return;
215
2
}
recycler_test.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
202
50
                                      int64_t start_time) {
203
50
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
204
0
        int64_t cost =
205
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
206
0
        if (cost > config::recycle_task_threshold_seconds) {
207
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
208
0
                    .tag("instance_id", instance_id)
209
0
                    .tag("task", task_name)
210
0
                    .tag("num_scanned", num_scanned)
211
0
                    .tag("num_recycled", num_recycled);
212
0
        }
213
0
    }
214
50
    return;
215
50
}
216
217
4
Recycler::Recycler(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
218
4
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
219
220
4
    auto s3_producer_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
221
4
                                                               "s3_producer_pool");
222
4
    s3_producer_pool->start();
223
4
    auto recycle_tablet_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
224
4
                                                                  "recycle_tablet_pool");
225
4
    recycle_tablet_pool->start();
226
4
    auto group_recycle_function_pool = std::make_shared<SimpleThreadPool>(
227
4
            config::recycle_pool_parallelism, "group_recycle_function_pool");
228
4
    group_recycle_function_pool->start();
229
4
    _thread_pool_group =
230
4
            RecyclerThreadPoolGroup(std::move(s3_producer_pool), std::move(recycle_tablet_pool),
231
4
                                    std::move(group_recycle_function_pool));
232
233
4
    auto resource_mgr = std::make_shared<ResourceManager>(txn_kv_);
234
4
    txn_lazy_committer_ = std::make_shared<TxnLazyCommitter>(txn_kv_, std::move(resource_mgr));
235
4
    snapshot_manager_ = std::make_shared<SnapshotManager>(txn_kv_);
236
4
}
237
238
4
Recycler::~Recycler() {
239
4
    if (!stopped()) {
240
0
        stop();
241
0
    }
242
4
}
243
244
4
void Recycler::instance_scanner_callback() {
245
    // sleep 60 seconds before scheduling for the launch procedure to complete:
246
    // some bad hdfs connection may cause some log to stdout stderr
247
    // which may pollute .out file and affect the script to check success
248
4
    std::this_thread::sleep_for(
249
4
            std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
250
8
    while (!stopped()) {
251
4
        std::vector<InstanceInfoPB> instances;
252
4
        get_all_instances(txn_kv_.get(), instances);
253
        // TODO(plat1ko): delete job recycle kv of non-existent instances
254
4
        LOG(INFO) << "Recycler get instances: " << [&instances] {
255
4
            std::stringstream ss;
256
30
            for (auto& i : instances) ss << ' ' << i.instance_id();
257
4
            return ss.str();
258
4
        }();
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
Line
Count
Source
254
4
        LOG(INFO) << "Recycler get instances: " << [&instances] {
255
4
            std::stringstream ss;
256
30
            for (auto& i : instances) ss << ' ' << i.instance_id();
257
4
            return ss.str();
258
4
        }();
259
4
        if (!instances.empty()) {
260
            // enqueue instances
261
3
            std::lock_guard lock(mtx_);
262
30
            for (auto& instance : instances) {
263
30
                if (instance_filter_.filter_out(instance.instance_id())) continue;
264
30
                auto [_, success] = pending_instance_set_.insert(instance.instance_id());
265
                // skip instance already in pending queue
266
30
                if (success) {
267
30
                    pending_instance_queue_.push_back(std::move(instance));
268
30
                }
269
30
            }
270
3
            pending_instance_cond_.notify_all();
271
3
        }
272
4
        {
273
4
            std::unique_lock lock(mtx_);
274
4
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
275
7
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
275
7
                               [&]() { return stopped(); });
276
4
        }
277
4
    }
278
4
}
279
280
8
void Recycler::recycle_callback() {
281
38
    while (!stopped()) {
282
38
        InstanceInfoPB instance;
283
38
        {
284
38
            std::unique_lock lock(mtx_);
285
38
            pending_instance_cond_.wait(
286
50
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
286
50
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
287
38
            if (stopped()) {
288
8
                return;
289
8
            }
290
30
            instance = std::move(pending_instance_queue_.front());
291
30
            pending_instance_queue_.pop_front();
292
30
            pending_instance_set_.erase(instance.instance_id());
293
30
        }
294
0
        auto& instance_id = instance.instance_id();
295
30
        {
296
30
            std::lock_guard lock(mtx_);
297
            // skip instance in recycling
298
30
            if (recycling_instance_map_.count(instance_id)) continue;
299
30
        }
300
30
        auto instance_recycler = std::make_shared<InstanceRecycler>(
301
30
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
302
303
30
        if (int r = instance_recycler->init(); r != 0) {
304
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
305
0
                         << " ret=" << r;
306
0
            continue;
307
0
        }
308
30
        std::string recycle_job_key;
309
30
        job_recycle_key({instance_id}, &recycle_job_key);
310
30
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
311
30
                                               ip_port_, config::recycle_interval_seconds * 1000);
312
30
        if (ret != 0) { // Prepare failed
313
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
314
20
                         << " ret=" << ret;
315
20
            continue;
316
20
        } else {
317
10
            std::lock_guard lock(mtx_);
318
10
            recycling_instance_map_.emplace(instance_id, instance_recycler);
319
10
        }
320
10
        if (stopped()) return;
321
10
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
322
10
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
323
10
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
324
10
        g_bvar_recycler_instance_recycle_task_status.put({"submitted"}, 1);
325
10
        ret = instance_recycler->do_recycle();
326
        // If instance recycler has been aborted, don't finish this job
327
328
10
        if (!instance_recycler->stopped()) {
329
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
330
10
                                        ret == 0, ctime_ms);
331
10
        }
332
10
        if (instance_recycler->stopped() || ret != 0) {
333
0
            g_bvar_recycler_instance_recycle_task_status.put({"error"}, 1);
334
0
        }
335
10
        {
336
10
            std::lock_guard lock(mtx_);
337
10
            recycling_instance_map_.erase(instance_id);
338
10
        }
339
340
10
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
341
10
        auto elpased_ms = now - ctime_ms;
342
10
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
343
10
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
344
10
        g_bvar_recycler_instance_next_ts.put({instance_id},
345
10
                                             now + config::recycle_interval_seconds * 1000);
346
10
        g_bvar_recycler_instance_recycle_task_status.put({"completed"}, 1);
347
10
        LOG(INFO) << "recycle instance done, "
348
10
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
349
10
                  << " now: " << now;
350
351
10
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
352
353
10
        LOG_WARNING("finish recycle instance")
354
10
                .tag("instance_id", instance_id)
355
10
                .tag("cost_ms", elpased_ms);
356
10
    }
357
8
}
358
359
4
void Recycler::lease_recycle_jobs() {
360
54
    while (!stopped()) {
361
50
        std::vector<std::string> instances;
362
50
        instances.reserve(recycling_instance_map_.size());
363
50
        {
364
50
            std::lock_guard lock(mtx_);
365
50
            for (auto& [id, _] : recycling_instance_map_) {
366
30
                instances.push_back(id);
367
30
            }
368
50
        }
369
50
        for (auto& i : instances) {
370
30
            std::string recycle_job_key;
371
30
            job_recycle_key({i}, &recycle_job_key);
372
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
373
30
            if (ret == 1) {
374
0
                std::lock_guard lock(mtx_);
375
0
                if (auto it = recycling_instance_map_.find(i);
376
0
                    it != recycling_instance_map_.end()) {
377
0
                    it->second->stop();
378
0
                }
379
0
            }
380
30
        }
381
50
        {
382
50
            std::unique_lock lock(mtx_);
383
50
            notifier_.wait_for(lock,
384
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
385
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
385
100
                               [&]() { return stopped(); });
386
50
        }
387
50
    }
388
4
}
389
390
4
void Recycler::check_recycle_tasks() {
391
7
    while (!stopped()) {
392
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
393
3
        {
394
3
            std::lock_guard lock(mtx_);
395
3
            recycling_instance_map = recycling_instance_map_;
396
3
        }
397
3
        for (auto& entry : recycling_instance_map) {
398
0
            entry.second->check_recycle_tasks();
399
0
        }
400
401
3
        std::unique_lock lock(mtx_);
402
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
403
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
403
6
                           [&]() { return stopped(); });
404
3
    }
405
4
}
406
407
4
int Recycler::start(brpc::Server* server) {
408
4
    instance_filter_.reset(config::recycle_whitelist, config::recycle_blacklist);
409
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
410
4
    S3Environment::getInstance();
411
4
    recycler_cache_manager();
412
413
4
    if (config::enable_checker) {
414
0
        checker_ = std::make_unique<Checker>(txn_kv_);
415
0
        int ret = checker_->start();
416
0
        std::string msg;
417
0
        if (ret != 0) {
418
0
            msg = "failed to start checker";
419
0
            LOG(ERROR) << msg;
420
0
            std::cerr << msg << std::endl;
421
0
            return ret;
422
0
        }
423
0
        msg = "checker started";
424
0
        LOG(INFO) << msg;
425
0
        std::cout << msg << std::endl;
426
0
    }
427
428
4
    if (server) {
429
        // Add service
430
1
        auto recycler_service =
431
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
432
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
433
1
    }
434
435
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
435
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
436
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
437
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
437
8
        workers_.emplace_back([this] { recycle_callback(); });
438
8
    }
439
440
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
441
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
442
443
4
    if (config::enable_snapshot_data_migrator) {
444
0
        snapshot_data_migrator_ = std::make_shared<SnapshotDataMigrator>(txn_kv_);
445
0
        int ret = snapshot_data_migrator_->start();
446
0
        if (ret != 0) {
447
0
            LOG(ERROR) << "failed to start snapshot data migrator";
448
0
            return ret;
449
0
        }
450
0
        LOG(INFO) << "snapshot data migrator started";
451
0
    }
452
453
4
    if (config::enable_snapshot_chain_compactor) {
454
0
        snapshot_chain_compactor_ = std::make_shared<SnapshotChainCompactor>(txn_kv_);
455
0
        int ret = snapshot_chain_compactor_->start();
456
0
        if (ret != 0) {
457
0
            LOG(ERROR) << "failed to start snapshot chain compactor";
458
0
            return ret;
459
0
        }
460
0
        LOG(INFO) << "snapshot chain compactor started";
461
0
    }
462
463
4
    return 0;
464
4
}
465
466
4
void Recycler::stop() {
467
4
    stopped_ = true;
468
4
    notifier_.notify_all();
469
4
    pending_instance_cond_.notify_all();
470
4
    {
471
4
        std::lock_guard lock(mtx_);
472
4
        for (auto& [_, recycler] : recycling_instance_map_) {
473
0
            recycler->stop();
474
0
        }
475
4
    }
476
20
    for (auto& w : workers_) {
477
20
        if (w.joinable()) w.join();
478
20
    }
479
4
    if (checker_) {
480
0
        checker_->stop();
481
0
    }
482
4
    if (snapshot_data_migrator_) {
483
0
        snapshot_data_migrator_->stop();
484
0
    }
485
4
    if (snapshot_chain_compactor_) {
486
0
        snapshot_chain_compactor_->stop();
487
0
    }
488
4
}
489
490
class InstanceRecycler::InvertedIndexIdCache {
491
public:
492
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
493
131
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
494
495
    // Return 0 if success, 1 if schema kv not found, negative for error
496
    // For the same index_id, schema_version, res, since `get` is not completely atomic
497
    // one thread has not finished inserting, and another thread has not get the index_id and schema_version,
498
    // resulting in repeated addition and inaccuracy.
499
    // however, this approach can reduce the lock range and sacrifice a bit of meta repeated get to improve concurrency performance.
500
    // repeated addition does not affect correctness.
501
28.4k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
502
28.4k
        {
503
28.4k
            std::lock_guard lock(mtx_);
504
28.4k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
505
3.96k
                return 0;
506
3.96k
            }
507
24.4k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
508
24.4k
                it != inverted_index_id_map_.end()) {
509
16.9k
                res = it->second;
510
16.9k
                return 0;
511
16.9k
            }
512
24.4k
        }
513
        // Get schema from kv
514
        // TODO(plat1ko): Single flight
515
7.47k
        std::unique_ptr<Transaction> txn;
516
7.47k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
517
7.47k
        if (err != TxnErrorCode::TXN_OK) {
518
0
            LOG(WARNING) << "failed to create txn, err=" << err;
519
0
            return -1;
520
0
        }
521
7.47k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
522
7.47k
        ValueBuf val_buf;
523
7.47k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
524
7.47k
        if (err != TxnErrorCode::TXN_OK) {
525
504
            LOG(WARNING) << "failed to get schema, err=" << err;
526
504
            return static_cast<int>(err);
527
504
        }
528
6.97k
        doris::TabletSchemaCloudPB schema;
529
6.97k
        if (!parse_schema_value(val_buf, &schema)) {
530
0
            LOG(WARNING) << "malformed schema value, key=" << hex(schema_key);
531
0
            return -1;
532
0
        }
533
6.97k
        if (schema.index_size() > 0) {
534
5.23k
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
535
5.23k
            if (schema.has_inverted_index_storage_format()) {
536
5.22k
                index_format = schema.inverted_index_storage_format();
537
5.22k
            }
538
5.23k
            res.first = index_format;
539
5.23k
            res.second.reserve(schema.index_size());
540
13.0k
            for (auto& i : schema.index()) {
541
13.0k
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
542
13.0k
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
543
13.0k
                }
544
13.0k
            }
545
5.23k
        }
546
6.97k
        insert(index_id, schema_version, res);
547
6.97k
        return 0;
548
6.97k
    }
549
550
    // Empty `ids` means this schema has no inverted index
551
6.97k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
552
6.97k
        if (index_info.second.empty()) {
553
1.74k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
554
1.74k
            std::lock_guard lock(mtx_);
555
1.74k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
556
5.23k
        } else {
557
5.23k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
558
5.23k
            std::lock_guard lock(mtx_);
559
5.23k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
560
5.23k
        }
561
6.97k
    }
562
563
private:
564
    std::string instance_id_;
565
    std::shared_ptr<TxnKv> txn_kv_;
566
567
    std::mutex mtx_;
568
    using Key = std::pair<int64_t, int32_t>; // <index_id, schema_version>
569
    struct HashOfKey {
570
59.8k
        size_t operator()(const Key& key) const {
571
59.8k
            size_t seed = 0;
572
59.8k
            seed = std::hash<int64_t> {}(key.first);
573
59.8k
            seed = std::hash<int32_t> {}(key.second);
574
59.8k
            return seed;
575
59.8k
        }
576
    };
577
    // <index_id, schema_version> -> inverted_index_ids
578
    std::unordered_map<Key, InvertedIndexInfo, HashOfKey> inverted_index_id_map_;
579
    // Store <index_id, schema_version> of schema which doesn't have inverted index
580
    std::unordered_set<Key, HashOfKey> schemas_without_inverted_index_;
581
};
582
583
InstanceRecycler::InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
584
                                   RecyclerThreadPoolGroup thread_pool_group,
585
                                   std::shared_ptr<TxnLazyCommitter> txn_lazy_committer)
586
        : txn_kv_(std::move(txn_kv)),
587
          instance_id_(instance.instance_id()),
588
          instance_info_(instance),
589
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
590
          _thread_pool_group(std::move(thread_pool_group)),
591
          txn_lazy_committer_(std::move(txn_lazy_committer)),
592
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
593
131
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
594
131
    delete_bitmap_lock_white_list_->init();
595
131
    resource_mgr_->init();
596
131
    snapshot_manager_ = std::make_shared<SnapshotManager>(txn_kv_);
597
598
    // Since the recycler's resource manager could not be notified when instance info changes,
599
    // we need to refresh the instance info here to ensure the resource manager has the latest info.
600
131
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
601
131
};
602
603
131
InstanceRecycler::~InstanceRecycler() = default;
604
605
115
int InstanceRecycler::init_obj_store_accessors() {
606
115
    for (const auto& obj_info : instance_info_.obj_info()) {
607
75
#ifdef UNIT_TEST
608
75
        auto accessor = std::make_shared<MockAccessor>();
609
#else
610
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
611
        if (!s3_conf) {
612
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
613
            return -1;
614
        }
615
616
        std::shared_ptr<S3Accessor> accessor;
617
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
618
        if (ret != 0) {
619
            LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
620
                         << " resource_id=" << obj_info.id();
621
            return ret;
622
        }
623
#endif
624
75
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
625
75
    }
626
627
115
    return 0;
628
115
}
629
630
115
int InstanceRecycler::init_storage_vault_accessors() {
631
115
    if (instance_info_.resource_ids().empty()) {
632
108
        return 0;
633
108
    }
634
635
7
    FullRangeGetOptions opts(txn_kv_);
636
7
    opts.prefetch = true;
637
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
638
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
639
640
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
641
18
        auto [k, v] = *kv;
642
18
        StorageVaultPB vault;
643
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
644
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
645
0
            return -1;
646
0
        }
647
18
        std::string recycler_storage_vault_white_list = accumulate(
648
18
                config::recycler_storage_vault_white_list.begin(),
649
18
                config::recycler_storage_vault_white_list.end(), std::string(),
650
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
650
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
651
18
        LOG_INFO("config::recycler_storage_vault_white_list")
652
18
                .tag("", recycler_storage_vault_white_list);
653
18
        if (!config::recycler_storage_vault_white_list.empty()) {
654
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
655
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
656
8
                it == config::recycler_storage_vault_white_list.end()) {
657
2
                LOG_WARNING(
658
2
                        "failed to init accessor for vault because this vault is not in "
659
2
                        "config::recycler_storage_vault_white_list. ")
660
2
                        .tag(" vault name:", vault.name())
661
2
                        .tag(" config::recycler_storage_vault_white_list:",
662
2
                             recycler_storage_vault_white_list);
663
2
                continue;
664
2
            }
665
8
        }
666
16
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
667
16
                                 &accessor_map_, &vault);
668
16
        if (vault.has_hdfs_info()) {
669
9
#ifdef ENABLE_HDFS_STORAGE_VAULT
670
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
671
9
            int ret = accessor->init();
672
9
            if (ret != 0) {
673
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
674
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
675
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
676
4
                continue;
677
4
            }
678
5
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
679
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
680
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
681
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
682
#else
683
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
684
                       << "but HDFS storage vaults were detected";
685
#endif
686
7
        } else if (vault.has_obj_info()) {
687
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
688
7
            if (!s3_conf) {
689
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
690
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
691
1
                continue;
692
1
            }
693
694
6
            std::shared_ptr<S3Accessor> accessor;
695
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
696
6
            if (ret != 0) {
697
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
698
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
699
0
                             << " ret=" << ret
700
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
701
0
                continue;
702
0
            }
703
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
704
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
705
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
706
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
707
6
        }
708
16
    }
709
710
7
    if (!it->is_valid()) {
711
0
        LOG_WARNING("failed to get storage vault kv");
712
0
        return -1;
713
0
    }
714
715
7
    if (accessor_map_.empty()) {
716
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
717
1
        return -2;
718
1
    }
719
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
720
6
             instance_id_);
721
722
6
    return 0;
723
7
}
724
725
115
int InstanceRecycler::init() {
726
115
    int ret = init_obj_store_accessors();
727
115
    if (ret != 0) {
728
0
        return ret;
729
0
    }
730
731
115
    return init_storage_vault_accessors();
732
115
}
733
734
template <typename... Func>
735
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
736
120
    return [funcs...]() {
737
120
        return [](std::initializer_list<int> ret_vals) {
738
120
            int i = 0;
739
140
            for (int ret : ret_vals) {
740
140
                if (ret != 0) {
741
0
                    i = ret;
742
0
                }
743
140
            }
744
120
            return i;
745
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
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
0
                    i = ret;
742
0
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
0
                    i = ret;
742
0
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
20
            for (int ret : ret_vals) {
740
20
                if (ret != 0) {
741
0
                    i = ret;
742
0
                }
743
20
            }
744
10
            return i;
745
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
0
                    i = ret;
742
0
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
0
                    i = ret;
742
0
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
0
                    i = ret;
742
0
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
20
            for (int ret : ret_vals) {
740
20
                if (ret != 0) {
741
0
                    i = ret;
742
0
                }
743
20
            }
744
10
            return i;
745
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
0
                    i = ret;
742
0
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
0
                    i = ret;
742
0
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
0
                    i = ret;
742
0
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
0
                    i = ret;
742
0
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
0
                    i = ret;
742
0
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
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
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
747
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
735
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
747
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
735
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
747
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
735
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
747
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
735
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
747
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
735
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
747
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
735
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
747
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
735
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
747
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
735
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
747
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
735
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
747
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
735
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
747
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
735
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
747
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
735
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
736
10
    return [funcs...]() {
737
10
        return [](std::initializer_list<int> ret_vals) {
738
10
            int i = 0;
739
10
            for (int ret : ret_vals) {
740
10
                if (ret != 0) {
741
10
                    i = ret;
742
10
                }
743
10
            }
744
10
            return i;
745
10
        }({funcs()...});
746
10
    };
747
10
}
748
749
10
int InstanceRecycler::do_recycle() {
750
10
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
751
10
    tablet_metrics_context_.reset();
752
10
    segment_metrics_context_.reset();
753
10
    DORIS_CLOUD_DEFER {
754
10
        tablet_metrics_context_.finish_report();
755
10
        segment_metrics_context_.finish_report();
756
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
753
10
    DORIS_CLOUD_DEFER {
754
10
        tablet_metrics_context_.finish_report();
755
10
        segment_metrics_context_.finish_report();
756
10
    };
757
10
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
758
0
        int res = recycle_cluster_snapshots();
759
0
        if (res != 0) {
760
0
            return -1;
761
0
        }
762
0
        return recycle_deleted_instance();
763
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
764
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
765
10
                                        fmt::format("instance id {}", instance_id_),
766
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
766
120
                                        [](int r) { return r != 0; });
767
10
        sync_executor
768
10
                .add(task_wrapper(
769
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
769
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
770
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
770
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
771
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
772
                                   // becase they may both recycle the same set of tablets
773
                        // recycle dropped table or idexes(mv, rollup)
774
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
774
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
775
                        // recycle dropped partitions
776
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
776
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
777
10
                .add(task_wrapper(
778
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
778
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
779
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
779
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
780
10
                .add(task_wrapper(
781
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
781
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
782
10
                .add(task_wrapper(
783
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
783
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
784
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
784
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
785
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
785
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
786
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
786
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
787
10
                .add(task_wrapper(
788
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
788
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
789
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
789
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
790
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
790
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
791
10
        bool finished = true;
792
10
        std::vector<int> rets = sync_executor.when_all(&finished);
793
120
        for (int ret : rets) {
794
120
            if (ret != 0) {
795
0
                return ret;
796
0
            }
797
120
        }
798
10
        return finished ? 0 : -1;
799
10
    } else {
800
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
801
0
                     << " instance_id=" << instance_id_;
802
0
        return -1;
803
0
    }
804
10
}
805
806
/**
807
* 1. delete all remote data
808
* 2. delete all kv
809
* 3. remove instance kv
810
*/
811
5
int InstanceRecycler::recycle_deleted_instance() {
812
5
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
813
814
5
    int ret = 0;
815
5
    auto start_time = steady_clock::now();
816
817
5
    DORIS_CLOUD_DEFER {
818
5
        auto cost = duration<float>(steady_clock::now() - start_time).count();
819
5
        LOG(WARNING) << (ret == 0 ? "successfully" : "failed to")
820
5
                     << " recycle deleted instance, cost=" << cost
821
5
                     << "s, instance_id=" << instance_id_;
822
5
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
817
5
    DORIS_CLOUD_DEFER {
818
5
        auto cost = duration<float>(steady_clock::now() - start_time).count();
819
5
        LOG(WARNING) << (ret == 0 ? "successfully" : "failed to")
820
5
                     << " recycle deleted instance, cost=" << cost
821
5
                     << "s, instance_id=" << instance_id_;
822
5
    };
823
824
    // Step 1: Recycle tmp rowsets (contains ref count but txn is not committed)
825
5
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
826
5
        int res = recycle_tmp_rowsets();
827
5
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
828
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
829
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
830
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
831
            // and cannot be recycled.
832
5
            res = recycle_tmp_rowsets();
833
5
        }
834
5
        return res;
835
5
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_1clEv
Line
Count
Source
825
5
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
826
5
        int res = recycle_tmp_rowsets();
827
5
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
828
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
829
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
830
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
831
            // and cannot be recycled.
832
5
            res = recycle_tmp_rowsets();
833
5
        }
834
5
        return res;
835
5
    };
836
5
    if (recycle_tmp_rowsets_with_mark_delete_enabled() != 0) {
837
0
        LOG_WARNING("failed to recycle tmp rowsets").tag("instance_id", instance_id_);
838
0
        return -1;
839
0
    }
840
841
    // Step 2: Recycle versioned rowsets in recycle space (already marked for deletion)
842
5
    if (recycle_versioned_rowsets() != 0) {
843
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
844
0
        return -1;
845
0
    }
846
847
    // Step 3: Recycle operation logs (can recycle logs not referenced by snapshots)
848
5
    if (recycle_operation_logs() != 0) {
849
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
850
0
        return -1;
851
0
    }
852
853
    // Step 4: Check if there are still cluster snapshots
854
5
    bool has_snapshots = false;
855
5
    if (has_cluster_snapshots(&has_snapshots) != 0) {
856
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
857
0
        return -1;
858
5
    } else if (has_snapshots) {
859
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
860
1
        return 0;
861
1
    }
862
863
4
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
864
4
                            instance_info().snapshot_switch_status() !=
865
1
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
866
4
    if (snapshot_enabled) {
867
1
        bool has_unrecycled_rowsets = false;
868
1
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
869
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
870
0
            return -1;
871
1
        } else if (has_unrecycled_rowsets) {
872
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
873
0
                    .tag("instance_id", instance_id_);
874
0
            return ret;
875
0
        }
876
3
    } else { // delete all remote data if snapshot is disabled
877
3
        for (auto& [_, accessor] : accessor_map_) {
878
3
            if (stopped()) {
879
0
                return ret;
880
0
            }
881
882
3
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
883
3
            int del_ret = accessor->delete_all();
884
3
            if (del_ret == 0) {
885
3
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
886
3
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
887
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
888
                // so the recycling has been successful.
889
0
                ret = -1;
890
0
            }
891
3
        }
892
893
3
        if (ret != 0) {
894
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
895
0
            return ret;
896
0
        }
897
3
    }
898
899
    // delete all kv
900
4
    std::unique_ptr<Transaction> txn;
901
4
    TxnErrorCode err = txn_kv_->create_txn(&txn);
902
4
    if (err != TxnErrorCode::TXN_OK) {
903
0
        LOG(WARNING) << "failed to create txn";
904
0
        ret = -1;
905
0
        return -1;
906
0
    }
907
4
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
908
    // delete kv before deleting objects to prevent the checker from misjudging data loss
909
4
    std::string start_txn_key = txn_key_prefix(instance_id_);
910
4
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
911
4
    txn->remove(start_txn_key, end_txn_key);
912
4
    std::string start_version_key = version_key_prefix(instance_id_);
913
4
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
914
4
    txn->remove(start_version_key, end_version_key);
915
4
    std::string start_meta_key = meta_key_prefix(instance_id_);
916
4
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
917
4
    txn->remove(start_meta_key, end_meta_key);
918
4
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
919
4
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
920
4
    txn->remove(start_recycle_key, end_recycle_key);
921
4
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
922
4
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
923
4
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
924
4
    std::string start_copy_key = copy_key_prefix(instance_id_);
925
4
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
926
4
    txn->remove(start_copy_key, end_copy_key);
927
    // should not remove job key range, because we need to reserve job recycle kv
928
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
929
4
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
930
4
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
931
4
    txn->remove(start_job_tablet_key, end_job_tablet_key);
932
4
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
933
4
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
934
4
    std::string start_vault_key = storage_vault_key(key_info0);
935
4
    std::string end_vault_key = storage_vault_key(key_info1);
936
4
    txn->remove(start_vault_key, end_vault_key);
937
4
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
938
4
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
939
4
    txn->remove(versioned_version_key_start, versioned_version_key_end);
940
4
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
941
4
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
942
4
    txn->remove(versioned_index_key_start, versioned_index_key_end);
943
4
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
944
4
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
945
4
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
946
4
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
947
4
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
948
4
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
949
4
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
950
4
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
951
4
    txn->remove(versioned_data_key_start, versioned_data_key_end);
952
4
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
953
4
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
954
4
    txn->remove(versioned_log_key_start, versioned_log_key_end);
955
4
    err = txn->commit();
956
4
    if (err != TxnErrorCode::TXN_OK) {
957
0
        LOG(WARNING) << "failed to delete all kv, instance_id=" << instance_id_ << ", err=" << err;
958
0
        ret = -1;
959
0
    }
960
961
4
    if (ret == 0) {
962
        // remove instance kv
963
        // ATTN: MUST ensure that cloud platform won't regenerate the same instance id
964
4
        err = txn_kv_->create_txn(&txn);
965
4
        if (err != TxnErrorCode::TXN_OK) {
966
0
            LOG(WARNING) << "failed to create txn";
967
0
            ret = -1;
968
0
            return ret;
969
0
        }
970
4
        std::string key;
971
4
        instance_key({instance_id_}, &key);
972
4
        txn->atomic_add(system_meta_service_instance_update_key(), 1);
973
4
        txn->remove(key);
974
4
        err = txn->commit();
975
4
        if (err != TxnErrorCode::TXN_OK) {
976
0
            LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
977
0
                         << " err=" << err;
978
0
            ret = -1;
979
0
        }
980
4
    }
981
4
    return ret;
982
4
}
983
984
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
985
9
                                          bool* exists, PackedFileRecycleStats* stats) {
986
9
    if (exists == nullptr) {
987
0
        return -1;
988
0
    }
989
9
    *exists = false;
990
991
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
992
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
993
9
    std::string scan_begin = begin;
994
995
9
    while (true) {
996
9
        std::unique_ptr<RangeGetIterator> it_range;
997
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
998
9
        if (get_ret < 0) {
999
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1000
0
                    .tag("instance_id", instance_id_)
1001
0
                    .tag("tablet_id", tablet_id)
1002
0
                    .tag("ret", get_ret);
1003
0
            return -1;
1004
0
        }
1005
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1006
6
            return 0;
1007
6
        }
1008
1009
3
        std::string last_key;
1010
3
        while (it_range->has_next()) {
1011
3
            auto [k, v] = it_range->next();
1012
3
            last_key.assign(k.data(), k.size());
1013
3
            doris::RowsetMetaCloudPB rowset_meta;
1014
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1015
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1016
0
                        .tag("instance_id", instance_id_)
1017
0
                        .tag("tablet_id", tablet_id)
1018
0
                        .tag("key", hex(k));
1019
0
                continue;
1020
0
            }
1021
3
            if (stats) {
1022
3
                ++stats->rowset_scan_count;
1023
3
            }
1024
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1025
3
                *exists = true;
1026
3
                return 0;
1027
3
            }
1028
3
        }
1029
1030
0
        if (!it_range->more()) {
1031
0
            return 0;
1032
0
        }
1033
1034
        // Continue scanning from the next key to keep each transaction short.
1035
0
        scan_begin = std::move(last_key);
1036
0
        scan_begin.push_back('\x00');
1037
0
    }
1038
9
}
1039
1040
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1041
                                                          const std::string& rowset_id,
1042
                                                          int64_t txn_id, bool* recycle_exists,
1043
11
                                                          bool* tmp_exists) {
1044
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1045
0
        return -1;
1046
0
    }
1047
11
    *recycle_exists = false;
1048
11
    *tmp_exists = false;
1049
1050
11
    if (txn_id <= 0) {
1051
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1052
0
                .tag("instance_id", instance_id_)
1053
0
                .tag("tablet_id", tablet_id)
1054
0
                .tag("rowset_id", rowset_id)
1055
0
                .tag("txn_id", txn_id);
1056
0
        return -1;
1057
0
    }
1058
1059
11
    std::unique_ptr<Transaction> txn;
1060
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1061
11
    if (err != TxnErrorCode::TXN_OK) {
1062
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1063
0
                .tag("instance_id", instance_id_)
1064
0
                .tag("tablet_id", tablet_id)
1065
0
                .tag("rowset_id", rowset_id)
1066
0
                .tag("txn_id", txn_id)
1067
0
                .tag("err", err);
1068
0
        return -1;
1069
0
    }
1070
1071
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1072
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1073
11
    if (ret == TxnErrorCode::TXN_OK) {
1074
1
        *recycle_exists = true;
1075
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1076
0
        LOG_WARNING("failed to check recycle rowset existence")
1077
0
                .tag("instance_id", instance_id_)
1078
0
                .tag("tablet_id", tablet_id)
1079
0
                .tag("rowset_id", rowset_id)
1080
0
                .tag("key", hex(recycle_key))
1081
0
                .tag("err", ret);
1082
0
        return -1;
1083
0
    }
1084
1085
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1086
11
    ret = key_exists(txn.get(), tmp_key, true);
1087
11
    if (ret == TxnErrorCode::TXN_OK) {
1088
1
        *tmp_exists = true;
1089
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1090
0
        LOG_WARNING("failed to check tmp rowset existence")
1091
0
                .tag("instance_id", instance_id_)
1092
0
                .tag("tablet_id", tablet_id)
1093
0
                .tag("txn_id", txn_id)
1094
0
                .tag("key", hex(tmp_key))
1095
0
                .tag("err", ret);
1096
0
        return -1;
1097
0
    }
1098
1099
11
    return 0;
1100
11
}
1101
1102
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1103
8
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1104
8
    if (!hint.empty()) {
1105
8
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1106
8
            return {hint, it->second};
1107
8
        }
1108
8
    }
1109
1110
0
    return {"", nullptr};
1111
8
}
1112
1113
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1114
                                               const std::string& packed_file_path,
1115
3
                                               PackedFileRecycleStats* stats) {
1116
3
    bool local_changed = false;
1117
3
    int64_t left_num = 0;
1118
3
    int64_t left_bytes = 0;
1119
3
    bool all_small_files_confirmed = true;
1120
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1121
1122
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1123
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1124
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1125
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1126
14
        LOG_INFO("packed slice correction status")
1127
14
                .tag("instance_id", instance_id_)
1128
14
                .tag("packed_file_path", packed_file_path)
1129
14
                .tag("small_file_path", file.path())
1130
14
                .tag("tablet_id", tablet_id)
1131
14
                .tag("rowset_id", rowset_id)
1132
14
                .tag("txn_id", txn_id)
1133
14
                .tag("size", file.size())
1134
14
                .tag("deleted", file.deleted())
1135
14
                .tag("corrected", file.corrected())
1136
14
                .tag("confirmed_this_round", confirmed_this_round);
1137
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
1122
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1123
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1124
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1125
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1126
14
        LOG_INFO("packed slice correction status")
1127
14
                .tag("instance_id", instance_id_)
1128
14
                .tag("packed_file_path", packed_file_path)
1129
14
                .tag("small_file_path", file.path())
1130
14
                .tag("tablet_id", tablet_id)
1131
14
                .tag("rowset_id", rowset_id)
1132
14
                .tag("txn_id", txn_id)
1133
14
                .tag("size", file.size())
1134
14
                .tag("deleted", file.deleted())
1135
14
                .tag("corrected", file.corrected())
1136
14
                .tag("confirmed_this_round", confirmed_this_round);
1137
14
    };
1138
1139
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1140
14
        auto* small_file = packed_info->mutable_slices(i);
1141
14
        if (small_file->deleted()) {
1142
3
            log_small_file_status(*small_file, small_file->corrected());
1143
3
            continue;
1144
3
        }
1145
1146
11
        if (small_file->corrected()) {
1147
0
            left_num++;
1148
0
            left_bytes += small_file->size();
1149
0
            log_small_file_status(*small_file, true);
1150
0
            continue;
1151
0
        }
1152
1153
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1154
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1155
0
                    .tag("instance_id", instance_id_)
1156
0
                    .tag("small_file_path", small_file->path())
1157
0
                    .tag("index", i);
1158
0
            return -1;
1159
0
        }
1160
1161
11
        int64_t tablet_id = small_file->tablet_id();
1162
11
        const std::string& rowset_id = small_file->rowset_id();
1163
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1164
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1165
0
                    .tag("instance_id", instance_id_)
1166
0
                    .tag("small_file_path", small_file->path())
1167
0
                    .tag("index", i)
1168
0
                    .tag("tablet_id", tablet_id)
1169
0
                    .tag("rowset_id", rowset_id)
1170
0
                    .tag("has_txn_id", small_file->has_txn_id())
1171
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1172
0
            return -1;
1173
0
        }
1174
11
        int64_t txn_id = small_file->txn_id();
1175
11
        bool recycle_exists = false;
1176
11
        bool tmp_exists = false;
1177
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1178
11
                                                &tmp_exists) != 0) {
1179
0
            return -1;
1180
0
        }
1181
1182
11
        bool small_file_confirmed = false;
1183
11
        if (tmp_exists) {
1184
1
            left_num++;
1185
1
            left_bytes += small_file->size();
1186
1
            small_file_confirmed = true;
1187
10
        } else if (recycle_exists) {
1188
1
            left_num++;
1189
1
            left_bytes += small_file->size();
1190
            // keep small_file_confirmed=false so the packed file remains uncorrected
1191
9
        } else {
1192
9
            bool rowset_exists = false;
1193
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1194
0
                return -1;
1195
0
            }
1196
1197
9
            if (!rowset_exists) {
1198
6
                if (!small_file->deleted()) {
1199
6
                    small_file->set_deleted(true);
1200
6
                    local_changed = true;
1201
6
                }
1202
6
                if (!small_file->corrected()) {
1203
6
                    small_file->set_corrected(true);
1204
6
                    local_changed = true;
1205
6
                }
1206
6
                small_file_confirmed = true;
1207
6
            } else {
1208
3
                left_num++;
1209
3
                left_bytes += small_file->size();
1210
3
                small_file_confirmed = true;
1211
3
            }
1212
9
        }
1213
1214
11
        if (!small_file_confirmed) {
1215
1
            all_small_files_confirmed = false;
1216
1
        }
1217
1218
11
        if (small_file->corrected() != small_file_confirmed) {
1219
4
            small_file->set_corrected(small_file_confirmed);
1220
4
            local_changed = true;
1221
4
        }
1222
1223
11
        log_small_file_status(*small_file, small_file_confirmed);
1224
11
    }
1225
1226
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1227
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1228
3
        local_changed = true;
1229
3
    }
1230
3
    if (packed_info->ref_cnt() != left_num) {
1231
3
        auto old_ref_cnt = packed_info->ref_cnt();
1232
3
        packed_info->set_ref_cnt(left_num);
1233
3
        LOG_INFO("corrected packed file ref count")
1234
3
                .tag("instance_id", instance_id_)
1235
3
                .tag("resource_id", packed_info->resource_id())
1236
3
                .tag("packed_file_path", packed_file_path)
1237
3
                .tag("old_ref_cnt", old_ref_cnt)
1238
3
                .tag("new_ref_cnt", left_num);
1239
3
        local_changed = true;
1240
3
    }
1241
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1242
2
        packed_info->set_corrected(all_small_files_confirmed);
1243
2
        local_changed = true;
1244
2
    }
1245
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1246
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1247
1
        local_changed = true;
1248
1
    }
1249
1250
3
    if (changed != nullptr) {
1251
3
        *changed = local_changed;
1252
3
    }
1253
3
    return 0;
1254
3
}
1255
1256
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1257
                                                 const std::string& packed_file_path,
1258
4
                                                 PackedFileRecycleStats* stats) {
1259
4
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1260
4
    bool correction_ok = false;
1261
4
    cloud::PackedFileInfoPB packed_info;
1262
1263
4
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1264
4
        if (stopped()) {
1265
0
            LOG_WARNING("recycler stopped before processing packed file")
1266
0
                    .tag("instance_id", instance_id_)
1267
0
                    .tag("packed_file_path", packed_file_path)
1268
0
                    .tag("attempt", attempt);
1269
0
            return -1;
1270
0
        }
1271
1272
4
        std::unique_ptr<Transaction> txn;
1273
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1274
4
        if (err != TxnErrorCode::TXN_OK) {
1275
0
            LOG_WARNING("failed to create txn when processing packed file")
1276
0
                    .tag("instance_id", instance_id_)
1277
0
                    .tag("packed_file_path", packed_file_path)
1278
0
                    .tag("attempt", attempt)
1279
0
                    .tag("err", err);
1280
0
            return -1;
1281
0
        }
1282
1283
4
        std::string packed_val;
1284
4
        err = txn->get(packed_key, &packed_val);
1285
4
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1286
0
            return 0;
1287
0
        }
1288
4
        if (err != TxnErrorCode::TXN_OK) {
1289
0
            LOG_WARNING("failed to get packed file kv")
1290
0
                    .tag("instance_id", instance_id_)
1291
0
                    .tag("packed_file_path", packed_file_path)
1292
0
                    .tag("attempt", attempt)
1293
0
                    .tag("err", err);
1294
0
            return -1;
1295
0
        }
1296
1297
4
        if (!packed_info.ParseFromString(packed_val)) {
1298
0
            LOG_WARNING("failed to parse packed file info")
1299
0
                    .tag("instance_id", instance_id_)
1300
0
                    .tag("packed_file_path", packed_file_path)
1301
0
                    .tag("attempt", attempt);
1302
0
            return -1;
1303
0
        }
1304
1305
4
        int64_t now_sec = ::time(nullptr);
1306
4
        bool corrected = packed_info.corrected();
1307
4
        bool due = config::force_immediate_recycle ||
1308
4
                   now_sec - packed_info.created_at_sec() >=
1309
4
                           config::packed_file_correction_delay_seconds;
1310
1311
4
        if (!corrected && due) {
1312
3
            bool changed = false;
1313
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1314
0
                LOG_WARNING("correct_packed_file_info failed")
1315
0
                        .tag("instance_id", instance_id_)
1316
0
                        .tag("packed_file_path", packed_file_path)
1317
0
                        .tag("attempt", attempt);
1318
0
                return -1;
1319
0
            }
1320
3
            if (changed) {
1321
3
                std::string updated;
1322
3
                if (!packed_info.SerializeToString(&updated)) {
1323
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1324
0
                            .tag("instance_id", instance_id_)
1325
0
                            .tag("packed_file_path", packed_file_path)
1326
0
                            .tag("attempt", attempt);
1327
0
                    return -1;
1328
0
                }
1329
3
                txn->put(packed_key, updated);
1330
3
                err = txn->commit();
1331
3
                if (err == TxnErrorCode::TXN_OK) {
1332
3
                    if (stats) {
1333
3
                        ++stats->num_corrected;
1334
3
                    }
1335
3
                } else {
1336
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1337
0
                        LOG_WARNING(
1338
0
                                "failed to commit correction for packed file due to conflict, "
1339
0
                                "retrying")
1340
0
                                .tag("instance_id", instance_id_)
1341
0
                                .tag("packed_file_path", packed_file_path)
1342
0
                                .tag("attempt", attempt);
1343
0
                        sleep_for_packed_file_retry();
1344
0
                        packed_info.Clear();
1345
0
                        continue;
1346
0
                    }
1347
0
                    LOG_WARNING("failed to commit correction for packed file")
1348
0
                            .tag("instance_id", instance_id_)
1349
0
                            .tag("packed_file_path", packed_file_path)
1350
0
                            .tag("attempt", attempt)
1351
0
                            .tag("err", err);
1352
0
                    return -1;
1353
0
                }
1354
3
            }
1355
3
        }
1356
1357
4
        correction_ok = true;
1358
4
        break;
1359
4
    }
1360
1361
4
    if (!correction_ok) {
1362
0
        return -1;
1363
0
    }
1364
1365
4
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1366
4
          packed_info.ref_cnt() == 0)) {
1367
3
        return 0;
1368
3
    }
1369
1370
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1371
0
        LOG_WARNING("packed file missing resource id when recycling")
1372
0
                .tag("instance_id", instance_id_)
1373
0
                .tag("packed_file_path", packed_file_path);
1374
0
        return -1;
1375
0
    }
1376
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1377
1
    if (!accessor) {
1378
0
        LOG_WARNING("no accessor available to delete packed file")
1379
0
                .tag("instance_id", instance_id_)
1380
0
                .tag("packed_file_path", packed_file_path)
1381
0
                .tag("resource_id", packed_info.resource_id());
1382
0
        return -1;
1383
0
    }
1384
1
    int del_ret = accessor->delete_file(packed_file_path);
1385
1
    if (del_ret != 0 && del_ret != 1) {
1386
0
        LOG_WARNING("failed to delete packed file")
1387
0
                .tag("instance_id", instance_id_)
1388
0
                .tag("packed_file_path", packed_file_path)
1389
0
                .tag("resource_id", resource_id)
1390
0
                .tag("ret", del_ret);
1391
0
        return -1;
1392
0
    }
1393
1
    if (del_ret == 1) {
1394
0
        LOG_INFO("packed file already removed")
1395
0
                .tag("instance_id", instance_id_)
1396
0
                .tag("packed_file_path", packed_file_path)
1397
0
                .tag("resource_id", resource_id);
1398
1
    } else {
1399
1
        LOG_INFO("deleted packed file")
1400
1
                .tag("instance_id", instance_id_)
1401
1
                .tag("packed_file_path", packed_file_path)
1402
1
                .tag("resource_id", resource_id);
1403
1
    }
1404
1405
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1406
1
        std::unique_ptr<Transaction> del_txn;
1407
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1408
1
        if (err != TxnErrorCode::TXN_OK) {
1409
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1410
0
                    .tag("instance_id", instance_id_)
1411
0
                    .tag("packed_file_path", packed_file_path)
1412
0
                    .tag("del_attempt", del_attempt)
1413
0
                    .tag("err", err);
1414
0
            return -1;
1415
0
        }
1416
1417
1
        std::string latest_val;
1418
1
        err = del_txn->get(packed_key, &latest_val);
1419
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1420
0
            return 0;
1421
0
        }
1422
1
        if (err != TxnErrorCode::TXN_OK) {
1423
0
            LOG_WARNING("failed to re-read packed file kv before removal")
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
                    .tag("err", err);
1428
0
            return -1;
1429
0
        }
1430
1431
1
        cloud::PackedFileInfoPB latest_info;
1432
1
        if (!latest_info.ParseFromString(latest_val)) {
1433
0
            LOG_WARNING("failed to parse packed file info before removal")
1434
0
                    .tag("instance_id", instance_id_)
1435
0
                    .tag("packed_file_path", packed_file_path)
1436
0
                    .tag("del_attempt", del_attempt);
1437
0
            return -1;
1438
0
        }
1439
1440
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1441
1
              latest_info.ref_cnt() == 0)) {
1442
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1443
0
                    .tag("instance_id", instance_id_)
1444
0
                    .tag("packed_file_path", packed_file_path)
1445
0
                    .tag("del_attempt", del_attempt);
1446
0
            return 0;
1447
0
        }
1448
1449
1
        del_txn->remove(packed_key);
1450
1
        err = del_txn->commit();
1451
1
        if (err == TxnErrorCode::TXN_OK) {
1452
1
            if (stats) {
1453
1
                ++stats->num_deleted;
1454
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1455
1
                                        static_cast<int64_t>(latest_val.size());
1456
1
                if (del_ret == 0 || del_ret == 1) {
1457
1
                    ++stats->num_object_deleted;
1458
1
                    int64_t object_size = latest_info.total_slice_bytes();
1459
1
                    if (object_size <= 0) {
1460
0
                        object_size = packed_info.total_slice_bytes();
1461
0
                    }
1462
1
                    stats->bytes_object_deleted += object_size;
1463
1
                }
1464
1
            }
1465
1
            LOG_INFO("removed packed file metadata")
1466
1
                    .tag("instance_id", instance_id_)
1467
1
                    .tag("packed_file_path", packed_file_path);
1468
1
            return 0;
1469
1
        }
1470
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1471
0
            if (del_attempt >= max_retry_times) {
1472
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1473
0
                        .tag("instance_id", instance_id_)
1474
0
                        .tag("packed_file_path", packed_file_path)
1475
0
                        .tag("del_attempt", del_attempt);
1476
0
                return -1;
1477
0
            }
1478
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1479
0
                    .tag("instance_id", instance_id_)
1480
0
                    .tag("packed_file_path", packed_file_path)
1481
0
                    .tag("del_attempt", del_attempt);
1482
0
            sleep_for_packed_file_retry();
1483
0
            continue;
1484
0
        }
1485
0
        LOG_WARNING("failed to remove packed file kv")
1486
0
                .tag("instance_id", instance_id_)
1487
0
                .tag("packed_file_path", packed_file_path)
1488
0
                .tag("del_attempt", del_attempt)
1489
0
                .tag("err", err);
1490
0
        return -1;
1491
0
    }
1492
1493
0
    return -1;
1494
1
}
1495
1496
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view /*value*/,
1497
4
                                            PackedFileRecycleStats* stats, int* ret) {
1498
4
    if (stats) {
1499
4
        ++stats->num_scanned;
1500
4
    }
1501
4
    std::string packed_file_path;
1502
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1503
0
        LOG_WARNING("failed to decode packed file key")
1504
0
                .tag("instance_id", instance_id_)
1505
0
                .tag("key", hex(key));
1506
0
        if (stats) {
1507
0
            ++stats->num_failed;
1508
0
        }
1509
0
        if (ret) {
1510
0
            *ret = -1;
1511
0
        }
1512
0
        return 0;
1513
0
    }
1514
1515
4
    std::string packed_key(key);
1516
4
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1517
4
    if (process_ret != 0) {
1518
0
        if (stats) {
1519
0
            ++stats->num_failed;
1520
0
        }
1521
0
        if (ret) {
1522
0
            *ret = -1;
1523
0
        }
1524
0
    }
1525
4
    return 0;
1526
4
}
1527
1528
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1529
9.77k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1530
9.77k
    if (config::force_immediate_recycle) {
1531
15
        return 0L;
1532
15
    }
1533
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1534
9.75k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1535
9.75k
    int64_t retention_seconds = config::retention_seconds;
1536
9.75k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1537
7.80k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1538
7.80k
    }
1539
9.75k
    int64_t final_expiration = expiration + retention_seconds;
1540
9.75k
    if (*earlest_ts > final_expiration) {
1541
7
        *earlest_ts = final_expiration;
1542
7
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1543
7
    }
1544
9.75k
    return final_expiration;
1545
9.77k
}
1546
1547
int64_t calculate_partition_expired_time(
1548
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1549
9
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1550
9
    if (config::force_immediate_recycle) {
1551
3
        return 0L;
1552
3
    }
1553
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1554
6
                                                            : partition_meta_pb.creation_time();
1555
6
    int64_t retention_seconds = config::retention_seconds;
1556
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1557
6
        retention_seconds =
1558
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1559
6
    }
1560
6
    int64_t final_expiration = expiration + retention_seconds;
1561
6
    if (*earlest_ts > final_expiration) {
1562
2
        *earlest_ts = final_expiration;
1563
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1564
2
    }
1565
6
    return final_expiration;
1566
9
}
1567
1568
int64_t calculate_index_expired_time(const std::string& instance_id_,
1569
                                     const RecycleIndexPB& index_meta_pb,
1570
10
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1571
10
    if (config::force_immediate_recycle) {
1572
4
        return 0L;
1573
4
    }
1574
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1575
6
                                                        : index_meta_pb.creation_time();
1576
6
    int64_t retention_seconds = config::retention_seconds;
1577
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1578
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1579
6
    }
1580
6
    int64_t final_expiration = expiration + retention_seconds;
1581
6
    if (*earlest_ts > final_expiration) {
1582
2
        *earlest_ts = final_expiration;
1583
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1584
2
    }
1585
6
    return final_expiration;
1586
10
}
1587
1588
int64_t calculate_tmp_rowset_expired_time(
1589
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1590
106k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1591
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1592
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1593
    //  duration or timeout always < `retention_time` in practice.
1594
106k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1595
106k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1596
106k
                                 : tmp_rowset_meta_pb.creation_time();
1597
106k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1598
106k
    int64_t final_expiration = expiration + config::retention_seconds;
1599
106k
    if (*earlest_ts > final_expiration) {
1600
24
        *earlest_ts = final_expiration;
1601
24
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1602
24
    }
1603
106k
    return final_expiration;
1604
106k
}
1605
1606
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1607
30.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1608
30.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1609
30.0k
    if (*earlest_ts > final_expiration / 1000) {
1610
8
        *earlest_ts = final_expiration / 1000;
1611
8
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1612
8
    }
1613
30.0k
    return final_expiration;
1614
30.0k
}
1615
1616
int64_t calculate_restore_job_expired_time(
1617
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1618
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1619
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1620
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1621
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1622
        // final state, recycle immediately
1623
41
        return 0L;
1624
41
    }
1625
    // not final state, wait much longer than the FE's timeout(1 day)
1626
0
    int64_t last_modified_s =
1627
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1628
0
    int64_t expiration = restore_job.expired_at_s() > 0
1629
0
                                 ? last_modified_s + restore_job.expired_at_s()
1630
0
                                 : last_modified_s;
1631
0
    int64_t final_expiration = expiration + config::retention_seconds;
1632
0
    if (*earlest_ts > final_expiration) {
1633
0
        *earlest_ts = final_expiration;
1634
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1635
0
    }
1636
0
    return final_expiration;
1637
41
}
1638
1639
2
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1640
2
    AbortTxnRequest req;
1641
2
    TxnInfoPB txn_info;
1642
2
    MetaServiceCode code = MetaServiceCode::OK;
1643
2
    std::string msg;
1644
2
    std::stringstream ss;
1645
2
    std::unique_ptr<Transaction> txn;
1646
2
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1647
2
    if (err != TxnErrorCode::TXN_OK) {
1648
0
        LOG_WARNING("failed to create txn").tag("err", err);
1649
0
        return -1;
1650
0
    }
1651
1652
    // get txn index
1653
2
    TxnIndexPB txn_idx_pb;
1654
2
    auto index_key = txn_index_key({instance_id_, txn_id});
1655
2
    std::string index_val;
1656
2
    err = txn->get(index_key, &index_val);
1657
2
    if (err != TxnErrorCode::TXN_OK) {
1658
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1659
            // maybe recycled
1660
0
            LOG_INFO("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1661
0
                    .tag("key", hex(index_key))
1662
0
                    .tag("txn_id", txn_id);
1663
0
            return 0;
1664
0
        }
1665
0
        LOG_WARNING("failed to get txn index")
1666
0
                .tag("err", err)
1667
0
                .tag("key", hex(index_key))
1668
0
                .tag("txn_id", txn_id);
1669
0
        return -1;
1670
0
    }
1671
2
    if (!txn_idx_pb.ParseFromString(index_val)) {
1672
0
        LOG_WARNING("failed to parse txn index")
1673
0
                .tag("err", err)
1674
0
                .tag("key", hex(index_key))
1675
0
                .tag("txn_id", txn_id);
1676
0
        return -1;
1677
0
    }
1678
1679
2
    auto info_key = txn_info_key({instance_id_, txn_idx_pb.tablet_index().db_id(), txn_id});
1680
2
    std::string info_val;
1681
2
    err = txn->get(info_key, &info_val);
1682
2
    if (err != TxnErrorCode::TXN_OK) {
1683
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1684
            // maybe recycled
1685
0
            LOG_INFO("txn info not found, txn_id={} instance_id={}", txn_id, instance_id_)
1686
0
                    .tag("key", hex(info_key))
1687
0
                    .tag("txn_id", txn_id);
1688
0
            return 0;
1689
0
        }
1690
0
        LOG_WARNING("failed to get txn info")
1691
0
                .tag("err", err)
1692
0
                .tag("key", hex(info_key))
1693
0
                .tag("txn_id", txn_id);
1694
0
        return -1;
1695
0
    }
1696
2
    if (!txn_info.ParseFromString(info_val)) {
1697
0
        LOG_WARNING("failed to parse txn info")
1698
0
                .tag("err", err)
1699
0
                .tag("key", hex(info_key))
1700
0
                .tag("txn_id", txn_id);
1701
0
        return -1;
1702
0
    }
1703
1704
2
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
1705
0
        LOG_INFO("txn is not prepared status, txn_id={} status={}", txn_id, txn_info.status())
1706
0
                .tag("key", hex(info_key))
1707
0
                .tag("txn_id", txn_id);
1708
0
        return 0;
1709
0
    }
1710
1711
2
    req.set_txn_id(txn_id);
1712
1713
2
    LOG(INFO) << "begin abort txn for related rowset, txn_id=" << txn_id
1714
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString();
1715
1716
2
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
1717
2
    err = txn->commit();
1718
2
    if (err != TxnErrorCode::TXN_OK) {
1719
0
        code = cast_as<ErrCategory::COMMIT>(err);
1720
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
1721
0
        msg = ss.str();
1722
0
        return -1;
1723
0
    }
1724
1725
2
    LOG(INFO) << "finish abort txn for related rowset, txn_id=" << txn_id
1726
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString()
1727
2
              << " code=" << code << " msg=" << msg;
1728
1729
2
    return 0;
1730
2
}
1731
1732
4
int InstanceRecycler::abort_job_for_related_rowset(const RowsetMetaCloudPB& rowset_meta) {
1733
4
    FinishTabletJobRequest req;
1734
4
    FinishTabletJobResponse res;
1735
4
    req.set_action(FinishTabletJobRequest::ABORT);
1736
4
    MetaServiceCode code = MetaServiceCode::OK;
1737
4
    std::string msg;
1738
4
    std::stringstream ss;
1739
1740
4
    TabletIndexPB tablet_idx;
1741
4
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, rowset_meta.tablet_id(), tablet_idx);
1742
4
    if (ret == 1) {
1743
        // tablet maybe recycled, directly return 0
1744
1
        return 0;
1745
3
    } else if (ret != 0) {
1746
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << rowset_meta.tablet_id()
1747
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
1748
0
        return ret;
1749
0
    }
1750
1751
3
    std::unique_ptr<Transaction> txn;
1752
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1753
3
    if (err != TxnErrorCode::TXN_OK) {
1754
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
1755
0
        return -1;
1756
0
    }
1757
1758
3
    std::string job_key =
1759
3
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
1760
3
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
1761
3
    std::string job_val;
1762
3
    err = txn->get(job_key, &job_val);
1763
3
    if (err != TxnErrorCode::TXN_OK) {
1764
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1765
0
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
1766
0
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
1767
0
            return 0;
1768
0
        }
1769
0
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
1770
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
1771
0
                     << " key=" << hex(job_key);
1772
0
        return -1;
1773
0
    }
1774
1775
3
    TabletJobInfoPB job_pb;
1776
3
    if (!job_pb.ParseFromString(job_val)) {
1777
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
1778
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
1779
0
        return -1;
1780
0
    }
1781
1782
3
    std::string job_id {};
1783
3
    if (!job_pb.compaction().empty()) {
1784
2
        for (const auto& c : job_pb.compaction()) {
1785
2
            if (c.id() == rowset_meta.job_id()) {
1786
2
                job_id = c.id();
1787
2
                break;
1788
2
            }
1789
2
        }
1790
2
    } else if (job_pb.has_schema_change()) {
1791
1
        job_id = job_pb.schema_change().id();
1792
1
    }
1793
1794
3
    if (!job_id.empty() && rowset_meta.job_id() == job_id) {
1795
3
        LOG(INFO) << "begin to abort job for related rowset, job_id=" << rowset_meta.job_id()
1796
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
1797
3
        req.mutable_job()->CopyFrom(job_pb);
1798
3
        req.set_action(FinishTabletJobRequest::ABORT);
1799
3
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
1800
3
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
1801
3
                           ss);
1802
3
        if (code != MetaServiceCode::OK) {
1803
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
1804
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
1805
0
                         << " msg=" << msg;
1806
0
            return -1;
1807
0
        }
1808
3
        LOG(INFO) << "finish abort job for related rowset, job_id=" << rowset_meta.job_id()
1809
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
1810
3
                  << " code=" << code << " msg=" << msg;
1811
3
    } else {
1812
        // clang-format off
1813
0
        LOG(INFO) << "there is no job for related rowset, directly recycle rowset data"
1814
0
                  << ", instance_id=" << instance_id_ 
1815
0
                  << ", tablet_id=" << tablet_idx.tablet_id() 
1816
0
                  << ", job_id=" << job_id
1817
0
                  << ", rowset_id=" << rowset_meta.rowset_id_v2();
1818
        // clang-format on
1819
0
    }
1820
1821
3
    return 0;
1822
3
}
1823
1824
template <typename T>
1825
57.7k
int InstanceRecycler::abort_txn_or_job_for_recycle(T& rowset_meta_pb) {
1826
57.7k
    RowsetMetaCloudPB* rs_meta;
1827
57.7k
    RecycleRowsetPB::Type rowset_type = RecycleRowsetPB::PREPARE;
1828
1829
57.7k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1830
        // For keys that are not in the RecycleRowsetPB::PREPARE state
1831
        // we do not need to check the job or txn state
1832
        // because tmp_rowset_key already exists when this key is generated.
1833
3.75k
        rowset_type = rowset_meta_pb.type();
1834
3.75k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1835
54.0k
    } else {
1836
54.0k
        rs_meta = &rowset_meta_pb;
1837
54.0k
    }
1838
1839
57.7k
    DCHECK(rs_meta != nullptr);
1840
1841
    // compaction/sc will generate recycle_rowset_key for each input rowset with load_id
1842
    // we need skip them because the related txn has been finished
1843
    // load_rowset1 load_rowset2 => pick for compaction => compact_rowset
1844
    // compact_rowset1 compact_rowset2 => pick for compaction/sc job => new_rowset
1845
57.7k
    if (rowset_type == RecycleRowsetPB::PREPARE) {
1846
54.6k
        if (rs_meta->has_load_id()) {
1847
            // load
1848
2
            return abort_txn_for_related_rowset(rs_meta->txn_id());
1849
54.6k
        } else if (rs_meta->has_job_id()) {
1850
            // compaction / schema change
1851
3
            return abort_job_for_related_rowset(*rs_meta);
1852
3
        }
1853
54.6k
    }
1854
1855
57.7k
    return 0;
1856
57.7k
}
_ZN5doris5cloud16InstanceRecycler28abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRT_
Line
Count
Source
1825
3.75k
int InstanceRecycler::abort_txn_or_job_for_recycle(T& rowset_meta_pb) {
1826
3.75k
    RowsetMetaCloudPB* rs_meta;
1827
3.75k
    RecycleRowsetPB::Type rowset_type = RecycleRowsetPB::PREPARE;
1828
1829
3.75k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1830
        // For keys that are not in the RecycleRowsetPB::PREPARE state
1831
        // we do not need to check the job or txn state
1832
        // because tmp_rowset_key already exists when this key is generated.
1833
3.75k
        rowset_type = rowset_meta_pb.type();
1834
3.75k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1835
3.75k
    } else {
1836
3.75k
        rs_meta = &rowset_meta_pb;
1837
3.75k
    }
1838
1839
3.75k
    DCHECK(rs_meta != nullptr);
1840
1841
    // compaction/sc will generate recycle_rowset_key for each input rowset with load_id
1842
    // we need skip them because the related txn has been finished
1843
    // load_rowset1 load_rowset2 => pick for compaction => compact_rowset
1844
    // compact_rowset1 compact_rowset2 => pick for compaction/sc job => new_rowset
1845
3.75k
    if (rowset_type == RecycleRowsetPB::PREPARE) {
1846
652
        if (rs_meta->has_load_id()) {
1847
            // load
1848
1
            return abort_txn_for_related_rowset(rs_meta->txn_id());
1849
651
        } else if (rs_meta->has_job_id()) {
1850
            // compaction / schema change
1851
1
            return abort_job_for_related_rowset(*rs_meta);
1852
1
        }
1853
652
    }
1854
1855
3.75k
    return 0;
1856
3.75k
}
_ZN5doris5cloud16InstanceRecycler28abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRT_
Line
Count
Source
1825
54.0k
int InstanceRecycler::abort_txn_or_job_for_recycle(T& rowset_meta_pb) {
1826
54.0k
    RowsetMetaCloudPB* rs_meta;
1827
54.0k
    RecycleRowsetPB::Type rowset_type = RecycleRowsetPB::PREPARE;
1828
1829
54.0k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1830
        // For keys that are not in the RecycleRowsetPB::PREPARE state
1831
        // we do not need to check the job or txn state
1832
        // because tmp_rowset_key already exists when this key is generated.
1833
54.0k
        rowset_type = rowset_meta_pb.type();
1834
54.0k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1835
54.0k
    } else {
1836
54.0k
        rs_meta = &rowset_meta_pb;
1837
54.0k
    }
1838
1839
54.0k
    DCHECK(rs_meta != nullptr);
1840
1841
    // compaction/sc will generate recycle_rowset_key for each input rowset with load_id
1842
    // we need skip them because the related txn has been finished
1843
    // load_rowset1 load_rowset2 => pick for compaction => compact_rowset
1844
    // compact_rowset1 compact_rowset2 => pick for compaction/sc job => new_rowset
1845
54.0k
    if (rowset_type == RecycleRowsetPB::PREPARE) {
1846
54.0k
        if (rs_meta->has_load_id()) {
1847
            // load
1848
1
            return abort_txn_for_related_rowset(rs_meta->txn_id());
1849
54.0k
        } else if (rs_meta->has_job_id()) {
1850
            // compaction / schema change
1851
2
            return abort_job_for_related_rowset(*rs_meta);
1852
2
        }
1853
54.0k
    }
1854
1855
54.0k
    return 0;
1856
54.0k
}
1857
1858
template <typename T>
1859
int mark_rowset_as_recycled(TxnKv* txn_kv, const std::string& instance_id, std::string_view key,
1860
113k
                            T& rowset_meta_pb) {
1861
113k
    RowsetMetaCloudPB* rs_meta;
1862
1863
113k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1864
106k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1865
106k
    } else {
1866
106k
        rs_meta = &rowset_meta_pb;
1867
106k
    }
1868
1869
113k
    bool need_write_back = false;
1870
113k
    if ((!rs_meta->has_is_recycled() || !rs_meta->is_recycled())) {
1871
55.7k
        need_write_back = true;
1872
55.7k
        rs_meta->set_is_recycled(true);
1873
55.7k
    }
1874
1875
113k
    if (need_write_back) {
1876
55.7k
        std::unique_ptr<Transaction> txn;
1877
55.7k
        TxnErrorCode err = txn_kv->create_txn(&txn);
1878
55.7k
        if (err != TxnErrorCode::TXN_OK) {
1879
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1880
0
            return -1;
1881
0
        }
1882
        // double check becase of new transaction
1883
55.7k
        T rowset_meta;
1884
55.7k
        std::string val;
1885
55.7k
        err = txn->get(key, &val);
1886
55.7k
        if (!rowset_meta.ParseFromString(val)) {
1887
0
            LOG(WARNING) << "failed to parse rs_meta, instance_id=" << instance_id;
1888
0
            return -1;
1889
0
        }
1890
55.7k
        if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1891
52.0k
            rs_meta = rowset_meta.mutable_rowset_meta();
1892
52.0k
        } else {
1893
52.0k
            rs_meta = &rowset_meta;
1894
52.0k
        }
1895
55.7k
        if ((rs_meta->has_is_recycled() && rs_meta->is_recycled())) {
1896
0
            return 0;
1897
0
        }
1898
55.7k
        rs_meta->set_is_recycled(true);
1899
55.7k
        val.clear();
1900
55.7k
        rowset_meta.SerializeToString(&val);
1901
55.7k
        txn->put(key, val);
1902
55.7k
        err = txn->commit();
1903
55.7k
        if (err != TxnErrorCode::TXN_OK) {
1904
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
1905
0
            return -1;
1906
0
        }
1907
55.7k
    }
1908
113k
    return need_write_back ? 1 : 0;
1909
113k
}
_ZN5doris5cloud23mark_rowset_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS8_ERT_
Line
Count
Source
1860
7.50k
                            T& rowset_meta_pb) {
1861
7.50k
    RowsetMetaCloudPB* rs_meta;
1862
1863
7.50k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1864
7.50k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1865
7.50k
    } else {
1866
7.50k
        rs_meta = &rowset_meta_pb;
1867
7.50k
    }
1868
1869
7.50k
    bool need_write_back = false;
1870
7.50k
    if ((!rs_meta->has_is_recycled() || !rs_meta->is_recycled())) {
1871
3.75k
        need_write_back = true;
1872
3.75k
        rs_meta->set_is_recycled(true);
1873
3.75k
    }
1874
1875
7.50k
    if (need_write_back) {
1876
3.75k
        std::unique_ptr<Transaction> txn;
1877
3.75k
        TxnErrorCode err = txn_kv->create_txn(&txn);
1878
3.75k
        if (err != TxnErrorCode::TXN_OK) {
1879
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1880
0
            return -1;
1881
0
        }
1882
        // double check becase of new transaction
1883
3.75k
        T rowset_meta;
1884
3.75k
        std::string val;
1885
3.75k
        err = txn->get(key, &val);
1886
3.75k
        if (!rowset_meta.ParseFromString(val)) {
1887
0
            LOG(WARNING) << "failed to parse rs_meta, instance_id=" << instance_id;
1888
0
            return -1;
1889
0
        }
1890
3.75k
        if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1891
3.75k
            rs_meta = rowset_meta.mutable_rowset_meta();
1892
3.75k
        } else {
1893
3.75k
            rs_meta = &rowset_meta;
1894
3.75k
        }
1895
3.75k
        if ((rs_meta->has_is_recycled() && rs_meta->is_recycled())) {
1896
0
            return 0;
1897
0
        }
1898
3.75k
        rs_meta->set_is_recycled(true);
1899
3.75k
        val.clear();
1900
3.75k
        rowset_meta.SerializeToString(&val);
1901
3.75k
        txn->put(key, val);
1902
3.75k
        err = txn->commit();
1903
3.75k
        if (err != TxnErrorCode::TXN_OK) {
1904
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
1905
0
            return -1;
1906
0
        }
1907
3.75k
    }
1908
7.50k
    return need_write_back ? 1 : 0;
1909
7.50k
}
_ZN5doris5cloud23mark_rowset_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS8_ERT_
Line
Count
Source
1860
106k
                            T& rowset_meta_pb) {
1861
106k
    RowsetMetaCloudPB* rs_meta;
1862
1863
106k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1864
106k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1865
106k
    } else {
1866
106k
        rs_meta = &rowset_meta_pb;
1867
106k
    }
1868
1869
106k
    bool need_write_back = false;
1870
106k
    if ((!rs_meta->has_is_recycled() || !rs_meta->is_recycled())) {
1871
52.0k
        need_write_back = true;
1872
52.0k
        rs_meta->set_is_recycled(true);
1873
52.0k
    }
1874
1875
106k
    if (need_write_back) {
1876
52.0k
        std::unique_ptr<Transaction> txn;
1877
52.0k
        TxnErrorCode err = txn_kv->create_txn(&txn);
1878
52.0k
        if (err != TxnErrorCode::TXN_OK) {
1879
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1880
0
            return -1;
1881
0
        }
1882
        // double check becase of new transaction
1883
52.0k
        T rowset_meta;
1884
52.0k
        std::string val;
1885
52.0k
        err = txn->get(key, &val);
1886
52.0k
        if (!rowset_meta.ParseFromString(val)) {
1887
0
            LOG(WARNING) << "failed to parse rs_meta, instance_id=" << instance_id;
1888
0
            return -1;
1889
0
        }
1890
52.0k
        if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1891
52.0k
            rs_meta = rowset_meta.mutable_rowset_meta();
1892
52.0k
        } else {
1893
52.0k
            rs_meta = &rowset_meta;
1894
52.0k
        }
1895
52.0k
        if ((rs_meta->has_is_recycled() && rs_meta->is_recycled())) {
1896
0
            return 0;
1897
0
        }
1898
52.0k
        rs_meta->set_is_recycled(true);
1899
52.0k
        val.clear();
1900
52.0k
        rowset_meta.SerializeToString(&val);
1901
52.0k
        txn->put(key, val);
1902
52.0k
        err = txn->commit();
1903
52.0k
        if (err != TxnErrorCode::TXN_OK) {
1904
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
1905
0
            return -1;
1906
0
        }
1907
52.0k
    }
1908
106k
    return need_write_back ? 1 : 0;
1909
106k
}
1910
1911
1
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
1912
1
    const std::string task_name = "recycle_ref_rowsets";
1913
1
    *has_unrecycled_rowsets = false;
1914
1915
1
    std::string data_rowset_ref_count_key_start =
1916
1
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
1917
1
    std::string data_rowset_ref_count_key_end =
1918
1
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
1919
1920
1
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
1921
1922
1
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
1923
1
    register_recycle_task(task_name, start_time);
1924
1925
1
    DORIS_CLOUD_DEFER {
1926
1
        unregister_recycle_task(task_name);
1927
1
        int64_t cost =
1928
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
1929
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
1930
1
                .tag("instance_id", instance_id_);
1931
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Line
Count
Source
1925
1
    DORIS_CLOUD_DEFER {
1926
1
        unregister_recycle_task(task_name);
1927
1
        int64_t cost =
1928
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
1929
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
1930
1
                .tag("instance_id", instance_id_);
1931
1
    };
1932
1933
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
1934
1
    std::set<int64_t> tablets_with_refs;
1935
1
    int64_t num_scanned = 0;
1936
1937
1
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
1938
0
        ++num_scanned;
1939
0
        int64_t tablet_id;
1940
0
        std::string rowset_id;
1941
0
        std::string_view key(k);
1942
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
1943
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
1944
0
            return 0; // Continue scanning
1945
0
        }
1946
1947
0
        tablets_with_refs.insert(tablet_id);
1948
0
        return 0;
1949
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
1950
1951
1
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
1952
1
                         std::move(scan_func)) != 0) {
1953
0
        LOG_WARNING("failed to scan data rowset ref count keys");
1954
0
        return -1;
1955
0
    }
1956
1957
1
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
1958
1
             tablets_with_refs.size(), num_scanned)
1959
1
            .tag("instance_id", instance_id_);
1960
1961
    // Phase 2: Recycle each tablet
1962
1
    int64_t num_recycled_tablets = 0;
1963
1
    for (int64_t tablet_id : tablets_with_refs) {
1964
0
        if (stopped()) {
1965
0
            LOG_INFO("recycler stopped, skip remaining tablets")
1966
0
                    .tag("instance_id", instance_id_)
1967
0
                    .tag("tablets_processed", num_recycled_tablets)
1968
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
1969
0
            break;
1970
0
        }
1971
1972
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
1973
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
1974
0
            LOG_WARNING("failed to recycle tablet")
1975
0
                    .tag("instance_id", instance_id_)
1976
0
                    .tag("tablet_id", tablet_id);
1977
0
            return -1;
1978
0
        }
1979
0
        ++num_recycled_tablets;
1980
0
    }
1981
1982
1
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
1983
1
            .tag("instance_id", instance_id_)
1984
1
            .tag("total_tablets", tablets_with_refs.size());
1985
1986
    // Phase 3: Scan again to check if any ref count keys still exist
1987
1
    std::unique_ptr<Transaction> txn;
1988
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1989
1
    if (err != TxnErrorCode::TXN_OK) {
1990
0
        LOG_WARNING("failed to create txn for final check")
1991
0
                .tag("instance_id", instance_id_)
1992
0
                .tag("err", err);
1993
0
        return -1;
1994
0
    }
1995
1996
1
    std::unique_ptr<RangeGetIterator> iter;
1997
1
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
1998
1
    if (err != TxnErrorCode::TXN_OK) {
1999
0
        LOG_WARNING("failed to create range iterator for final check")
2000
0
                .tag("instance_id", instance_id_)
2001
0
                .tag("err", err);
2002
0
        return -1;
2003
0
    }
2004
2005
1
    *has_unrecycled_rowsets = iter->has_next();
2006
1
    if (*has_unrecycled_rowsets) {
2007
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2008
0
                .tag("instance_id", instance_id_);
2009
0
    }
2010
2011
1
    return 0;
2012
1
}
2013
2014
17
int InstanceRecycler::recycle_indexes() {
2015
17
    const std::string task_name = "recycle_indexes";
2016
17
    int64_t num_scanned = 0;
2017
17
    int64_t num_expired = 0;
2018
17
    int64_t num_recycled = 0;
2019
17
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2020
2021
17
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2022
17
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2023
17
    std::string index_key0;
2024
17
    std::string index_key1;
2025
17
    recycle_index_key(index_key_info0, &index_key0);
2026
17
    recycle_index_key(index_key_info1, &index_key1);
2027
2028
17
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2029
2030
17
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2031
17
    register_recycle_task(task_name, start_time);
2032
2033
17
    DORIS_CLOUD_DEFER {
2034
17
        unregister_recycle_task(task_name);
2035
17
        int64_t cost =
2036
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2037
17
        metrics_context.finish_report();
2038
17
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2039
17
                .tag("instance_id", instance_id_)
2040
17
                .tag("num_scanned", num_scanned)
2041
17
                .tag("num_expired", num_expired)
2042
17
                .tag("num_recycled", num_recycled);
2043
17
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2033
2
    DORIS_CLOUD_DEFER {
2034
2
        unregister_recycle_task(task_name);
2035
2
        int64_t cost =
2036
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2037
2
        metrics_context.finish_report();
2038
2
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2039
2
                .tag("instance_id", instance_id_)
2040
2
                .tag("num_scanned", num_scanned)
2041
2
                .tag("num_expired", num_expired)
2042
2
                .tag("num_recycled", num_recycled);
2043
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2033
15
    DORIS_CLOUD_DEFER {
2034
15
        unregister_recycle_task(task_name);
2035
15
        int64_t cost =
2036
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2037
15
        metrics_context.finish_report();
2038
15
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2039
15
                .tag("instance_id", instance_id_)
2040
15
                .tag("num_scanned", num_scanned)
2041
15
                .tag("num_expired", num_expired)
2042
15
                .tag("num_recycled", num_recycled);
2043
15
    };
2044
2045
17
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2046
2047
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2048
17
    std::vector<std::string_view> index_keys;
2049
17
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2050
10
        ++num_scanned;
2051
10
        RecycleIndexPB index_pb;
2052
10
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2053
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2054
0
            return -1;
2055
0
        }
2056
10
        int64_t current_time = ::time(nullptr);
2057
10
        if (current_time <
2058
10
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2059
0
            return 0;
2060
0
        }
2061
10
        ++num_expired;
2062
        // decode index_id
2063
10
        auto k1 = k;
2064
10
        k1.remove_prefix(1);
2065
10
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2066
10
        decode_key(&k1, &out);
2067
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2068
10
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2069
10
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2070
10
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2071
10
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2072
        // Change state to RECYCLING
2073
10
        std::unique_ptr<Transaction> txn;
2074
10
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2075
10
        if (err != TxnErrorCode::TXN_OK) {
2076
0
            LOG_WARNING("failed to create txn").tag("err", err);
2077
0
            return -1;
2078
0
        }
2079
10
        std::string val;
2080
10
        err = txn->get(k, &val);
2081
10
        if (err ==
2082
10
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2083
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2084
0
            return 0;
2085
0
        }
2086
10
        if (err != TxnErrorCode::TXN_OK) {
2087
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2088
0
            return -1;
2089
0
        }
2090
10
        index_pb.Clear();
2091
10
        if (!index_pb.ParseFromString(val)) {
2092
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2093
0
            return -1;
2094
0
        }
2095
10
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2096
9
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2097
9
            txn->put(k, index_pb.SerializeAsString());
2098
9
            err = txn->commit();
2099
9
            if (err != TxnErrorCode::TXN_OK) {
2100
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2101
0
                return -1;
2102
0
            }
2103
9
        }
2104
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2105
1
            LOG_WARNING("failed to recycle tablets under index")
2106
1
                    .tag("table_id", index_pb.table_id())
2107
1
                    .tag("instance_id", instance_id_)
2108
1
                    .tag("index_id", index_id);
2109
1
            return -1;
2110
1
        }
2111
2112
9
        if (index_pb.has_db_id()) {
2113
            // Recycle the versioned keys
2114
3
            std::unique_ptr<Transaction> txn;
2115
3
            err = txn_kv_->create_txn(&txn);
2116
3
            if (err != TxnErrorCode::TXN_OK) {
2117
0
                LOG_WARNING("failed to create txn").tag("err", err);
2118
0
                return -1;
2119
0
            }
2120
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2121
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2122
3
            std::string index_inverted_key = versioned::index_inverted_key(
2123
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2124
3
            versioned_remove_all(txn.get(), meta_key);
2125
3
            txn->remove(index_key);
2126
3
            txn->remove(index_inverted_key);
2127
3
            err = txn->commit();
2128
3
            if (err != TxnErrorCode::TXN_OK) {
2129
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2130
0
                return -1;
2131
0
            }
2132
3
        }
2133
2134
9
        metrics_context.total_recycled_num = ++num_recycled;
2135
9
        metrics_context.report();
2136
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2137
9
        index_keys.push_back(k);
2138
9
        return 0;
2139
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2049
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2050
2
        ++num_scanned;
2051
2
        RecycleIndexPB index_pb;
2052
2
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2053
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2054
0
            return -1;
2055
0
        }
2056
2
        int64_t current_time = ::time(nullptr);
2057
2
        if (current_time <
2058
2
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2059
0
            return 0;
2060
0
        }
2061
2
        ++num_expired;
2062
        // decode index_id
2063
2
        auto k1 = k;
2064
2
        k1.remove_prefix(1);
2065
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2066
2
        decode_key(&k1, &out);
2067
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2068
2
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2069
2
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2070
2
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2071
2
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2072
        // Change state to RECYCLING
2073
2
        std::unique_ptr<Transaction> txn;
2074
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2075
2
        if (err != TxnErrorCode::TXN_OK) {
2076
0
            LOG_WARNING("failed to create txn").tag("err", err);
2077
0
            return -1;
2078
0
        }
2079
2
        std::string val;
2080
2
        err = txn->get(k, &val);
2081
2
        if (err ==
2082
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2083
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2084
0
            return 0;
2085
0
        }
2086
2
        if (err != TxnErrorCode::TXN_OK) {
2087
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2088
0
            return -1;
2089
0
        }
2090
2
        index_pb.Clear();
2091
2
        if (!index_pb.ParseFromString(val)) {
2092
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2093
0
            return -1;
2094
0
        }
2095
2
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2096
1
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2097
1
            txn->put(k, index_pb.SerializeAsString());
2098
1
            err = txn->commit();
2099
1
            if (err != TxnErrorCode::TXN_OK) {
2100
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2101
0
                return -1;
2102
0
            }
2103
1
        }
2104
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2105
1
            LOG_WARNING("failed to recycle tablets under index")
2106
1
                    .tag("table_id", index_pb.table_id())
2107
1
                    .tag("instance_id", instance_id_)
2108
1
                    .tag("index_id", index_id);
2109
1
            return -1;
2110
1
        }
2111
2112
1
        if (index_pb.has_db_id()) {
2113
            // Recycle the versioned keys
2114
1
            std::unique_ptr<Transaction> txn;
2115
1
            err = txn_kv_->create_txn(&txn);
2116
1
            if (err != TxnErrorCode::TXN_OK) {
2117
0
                LOG_WARNING("failed to create txn").tag("err", err);
2118
0
                return -1;
2119
0
            }
2120
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2121
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2122
1
            std::string index_inverted_key = versioned::index_inverted_key(
2123
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2124
1
            versioned_remove_all(txn.get(), meta_key);
2125
1
            txn->remove(index_key);
2126
1
            txn->remove(index_inverted_key);
2127
1
            err = txn->commit();
2128
1
            if (err != TxnErrorCode::TXN_OK) {
2129
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2130
0
                return -1;
2131
0
            }
2132
1
        }
2133
2134
1
        metrics_context.total_recycled_num = ++num_recycled;
2135
1
        metrics_context.report();
2136
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2137
1
        index_keys.push_back(k);
2138
1
        return 0;
2139
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2049
8
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2050
8
        ++num_scanned;
2051
8
        RecycleIndexPB index_pb;
2052
8
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2053
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2054
0
            return -1;
2055
0
        }
2056
8
        int64_t current_time = ::time(nullptr);
2057
8
        if (current_time <
2058
8
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2059
0
            return 0;
2060
0
        }
2061
8
        ++num_expired;
2062
        // decode index_id
2063
8
        auto k1 = k;
2064
8
        k1.remove_prefix(1);
2065
8
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2066
8
        decode_key(&k1, &out);
2067
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2068
8
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2069
8
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2070
8
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2071
8
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2072
        // Change state to RECYCLING
2073
8
        std::unique_ptr<Transaction> txn;
2074
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2075
8
        if (err != TxnErrorCode::TXN_OK) {
2076
0
            LOG_WARNING("failed to create txn").tag("err", err);
2077
0
            return -1;
2078
0
        }
2079
8
        std::string val;
2080
8
        err = txn->get(k, &val);
2081
8
        if (err ==
2082
8
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2083
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2084
0
            return 0;
2085
0
        }
2086
8
        if (err != TxnErrorCode::TXN_OK) {
2087
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2088
0
            return -1;
2089
0
        }
2090
8
        index_pb.Clear();
2091
8
        if (!index_pb.ParseFromString(val)) {
2092
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2093
0
            return -1;
2094
0
        }
2095
8
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2096
8
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2097
8
            txn->put(k, index_pb.SerializeAsString());
2098
8
            err = txn->commit();
2099
8
            if (err != TxnErrorCode::TXN_OK) {
2100
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2101
0
                return -1;
2102
0
            }
2103
8
        }
2104
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2105
0
            LOG_WARNING("failed to recycle tablets under index")
2106
0
                    .tag("table_id", index_pb.table_id())
2107
0
                    .tag("instance_id", instance_id_)
2108
0
                    .tag("index_id", index_id);
2109
0
            return -1;
2110
0
        }
2111
2112
8
        if (index_pb.has_db_id()) {
2113
            // Recycle the versioned keys
2114
2
            std::unique_ptr<Transaction> txn;
2115
2
            err = txn_kv_->create_txn(&txn);
2116
2
            if (err != TxnErrorCode::TXN_OK) {
2117
0
                LOG_WARNING("failed to create txn").tag("err", err);
2118
0
                return -1;
2119
0
            }
2120
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2121
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2122
2
            std::string index_inverted_key = versioned::index_inverted_key(
2123
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2124
2
            versioned_remove_all(txn.get(), meta_key);
2125
2
            txn->remove(index_key);
2126
2
            txn->remove(index_inverted_key);
2127
2
            err = txn->commit();
2128
2
            if (err != TxnErrorCode::TXN_OK) {
2129
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2130
0
                return -1;
2131
0
            }
2132
2
        }
2133
2134
8
        metrics_context.total_recycled_num = ++num_recycled;
2135
8
        metrics_context.report();
2136
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2137
8
        index_keys.push_back(k);
2138
8
        return 0;
2139
8
    };
2140
2141
17
    auto loop_done = [&index_keys, this]() -> int {
2142
6
        if (index_keys.empty()) return 0;
2143
5
        DORIS_CLOUD_DEFER {
2144
5
            index_keys.clear();
2145
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2143
1
        DORIS_CLOUD_DEFER {
2144
1
            index_keys.clear();
2145
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2143
4
        DORIS_CLOUD_DEFER {
2144
4
            index_keys.clear();
2145
4
        };
2146
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2147
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2148
0
            return -1;
2149
0
        }
2150
5
        return 0;
2151
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2141
2
    auto loop_done = [&index_keys, this]() -> int {
2142
2
        if (index_keys.empty()) return 0;
2143
1
        DORIS_CLOUD_DEFER {
2144
1
            index_keys.clear();
2145
1
        };
2146
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2147
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2148
0
            return -1;
2149
0
        }
2150
1
        return 0;
2151
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2141
4
    auto loop_done = [&index_keys, this]() -> int {
2142
4
        if (index_keys.empty()) return 0;
2143
4
        DORIS_CLOUD_DEFER {
2144
4
            index_keys.clear();
2145
4
        };
2146
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2147
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2148
0
            return -1;
2149
0
        }
2150
4
        return 0;
2151
4
    };
2152
2153
17
    if (config::enable_recycler_stats_metrics) {
2154
0
        scan_and_statistics_indexes();
2155
0
    }
2156
    // recycle_func and loop_done for scan and recycle
2157
17
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
2158
17
}
2159
2160
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
2161
8.24k
                             int64_t tablet_id) {
2162
8.24k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
2163
2164
8.24k
    std::unique_ptr<Transaction> txn;
2165
8.24k
    TxnErrorCode err = txn_kv->create_txn(&txn);
2166
8.24k
    if (err != TxnErrorCode::TXN_OK) {
2167
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
2168
0
                     << " tablet_id=" << tablet_id << " err=" << err;
2169
0
        return false;
2170
0
    }
2171
2172
8.24k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
2173
8.24k
    std::string tablet_idx_val;
2174
8.24k
    TabletIndexPB tablet_idx_pb;
2175
8.24k
    if (!get_tablet_idx_from_recycler_cache(instance_id, tablet_id, &tablet_idx_pb)) {
2176
8.24k
        err = txn->get(tablet_idx_key, &tablet_idx_val);
2177
8.24k
        if (TxnErrorCode::TXN_OK != err) {
2178
0
            LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
2179
0
                         << " tablet_id=" << tablet_id << " err=" << err
2180
0
                         << " key=" << hex(tablet_idx_key);
2181
0
            return false;
2182
0
        }
2183
2184
8.24k
        if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
2185
0
            LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
2186
0
                         << " tablet_id=" << tablet_id;
2187
0
            return false;
2188
0
        }
2189
8.24k
        put_tablet_idx_to_recycler_cache(instance_id, tablet_id, tablet_idx_pb);
2190
8.24k
    }
2191
2192
8.24k
    if (!tablet_idx_pb.has_db_id()) {
2193
        // In the previous version, the db_id was not set in the index_pb.
2194
        // If updating to the version which enable txn lazy commit, the db_id will be set.
2195
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
2196
0
                  << " instance_id=" << instance_id
2197
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
2198
0
        return true;
2199
0
    }
2200
2201
8.24k
    std::string ver_val;
2202
8.24k
    std::string ver_key =
2203
8.24k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
2204
8.24k
                                   tablet_idx_pb.partition_id()});
2205
8.24k
    err = txn->get(ver_key, &ver_val);
2206
2207
8.24k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
2208
204
        LOG(INFO) << ""
2209
204
                     "partition version not found, instance_id="
2210
204
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
2211
204
                  << " table_id=" << tablet_idx_pb.table_id()
2212
204
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
2213
204
                  << " key=" << hex(ver_key);
2214
204
        return true;
2215
204
    }
2216
2217
8.03k
    if (TxnErrorCode::TXN_OK != err) {
2218
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
2219
0
                     << " db_id=" << tablet_idx_pb.db_id()
2220
0
                     << " table_id=" << tablet_idx_pb.table_id()
2221
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2222
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
2223
0
        return false;
2224
0
    }
2225
2226
8.03k
    VersionPB version_pb;
2227
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
2228
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
2229
0
                     << " db_id=" << tablet_idx_pb.db_id()
2230
0
                     << " table_id=" << tablet_idx_pb.table_id()
2231
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2232
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
2233
0
        return false;
2234
0
    }
2235
2236
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
2237
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
2238
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
2239
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
2240
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
2241
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
2242
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
2243
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
2244
4.00k
                     << " key=" << hex(ver_key);
2245
4.00k
        return false;
2246
4.00k
    }
2247
4.03k
    return true;
2248
8.03k
}
2249
2250
15
int InstanceRecycler::recycle_partitions() {
2251
15
    const std::string task_name = "recycle_partitions";
2252
15
    int64_t num_scanned = 0;
2253
15
    int64_t num_expired = 0;
2254
15
    int64_t num_recycled = 0;
2255
15
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2256
2257
15
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
2258
15
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
2259
15
    std::string part_key0;
2260
15
    std::string part_key1;
2261
15
    recycle_partition_key(part_key_info0, &part_key0);
2262
15
    recycle_partition_key(part_key_info1, &part_key1);
2263
2264
15
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
2265
2266
15
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2267
15
    register_recycle_task(task_name, start_time);
2268
2269
15
    DORIS_CLOUD_DEFER {
2270
15
        unregister_recycle_task(task_name);
2271
15
        int64_t cost =
2272
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2273
15
        metrics_context.finish_report();
2274
15
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2275
15
                .tag("instance_id", instance_id_)
2276
15
                .tag("num_scanned", num_scanned)
2277
15
                .tag("num_expired", num_expired)
2278
15
                .tag("num_recycled", num_recycled);
2279
15
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2269
2
    DORIS_CLOUD_DEFER {
2270
2
        unregister_recycle_task(task_name);
2271
2
        int64_t cost =
2272
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2273
2
        metrics_context.finish_report();
2274
2
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2275
2
                .tag("instance_id", instance_id_)
2276
2
                .tag("num_scanned", num_scanned)
2277
2
                .tag("num_expired", num_expired)
2278
2
                .tag("num_recycled", num_recycled);
2279
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2269
13
    DORIS_CLOUD_DEFER {
2270
13
        unregister_recycle_task(task_name);
2271
13
        int64_t cost =
2272
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2273
13
        metrics_context.finish_report();
2274
13
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2275
13
                .tag("instance_id", instance_id_)
2276
13
                .tag("num_scanned", num_scanned)
2277
13
                .tag("num_expired", num_expired)
2278
13
                .tag("num_recycled", num_recycled);
2279
13
    };
2280
2281
15
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2282
2283
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
2284
15
    std::vector<std::string_view> partition_keys;
2285
15
    std::vector<std::string> partition_version_keys;
2286
15
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2287
9
        ++num_scanned;
2288
9
        RecyclePartitionPB part_pb;
2289
9
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2290
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2291
0
            return -1;
2292
0
        }
2293
9
        int64_t current_time = ::time(nullptr);
2294
9
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2295
9
                                                            &earlest_ts)) { // not expired
2296
0
            return 0;
2297
0
        }
2298
9
        ++num_expired;
2299
        // decode partition_id
2300
9
        auto k1 = k;
2301
9
        k1.remove_prefix(1);
2302
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2303
9
        decode_key(&k1, &out);
2304
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2305
9
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2306
9
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2307
9
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2308
9
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2309
        // Change state to RECYCLING
2310
9
        std::unique_ptr<Transaction> txn;
2311
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2312
9
        if (err != TxnErrorCode::TXN_OK) {
2313
0
            LOG_WARNING("failed to create txn").tag("err", err);
2314
0
            return -1;
2315
0
        }
2316
9
        std::string val;
2317
9
        err = txn->get(k, &val);
2318
9
        if (err ==
2319
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2320
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2321
0
            return 0;
2322
0
        }
2323
9
        if (err != TxnErrorCode::TXN_OK) {
2324
0
            LOG_WARNING("failed to get kv");
2325
0
            return -1;
2326
0
        }
2327
9
        part_pb.Clear();
2328
9
        if (!part_pb.ParseFromString(val)) {
2329
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2330
0
            return -1;
2331
0
        }
2332
        // Partitions with PREPARED state MUST have no data
2333
9
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2334
8
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2335
8
            txn->put(k, part_pb.SerializeAsString());
2336
8
            err = txn->commit();
2337
8
            if (err != TxnErrorCode::TXN_OK) {
2338
0
                LOG_WARNING("failed to commit txn: {}", err);
2339
0
                return -1;
2340
0
            }
2341
8
        }
2342
2343
9
        int ret = 0;
2344
33
        for (int64_t index_id : part_pb.index_id()) {
2345
33
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2346
1
                LOG_WARNING("failed to recycle tablets under partition")
2347
1
                        .tag("table_id", part_pb.table_id())
2348
1
                        .tag("instance_id", instance_id_)
2349
1
                        .tag("index_id", index_id)
2350
1
                        .tag("partition_id", partition_id);
2351
1
                ret = -1;
2352
1
            }
2353
33
        }
2354
9
        if (ret == 0 && part_pb.has_db_id()) {
2355
            // Recycle the versioned keys
2356
8
            std::unique_ptr<Transaction> txn;
2357
8
            err = txn_kv_->create_txn(&txn);
2358
8
            if (err != TxnErrorCode::TXN_OK) {
2359
0
                LOG_WARNING("failed to create txn").tag("err", err);
2360
0
                return -1;
2361
0
            }
2362
8
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2363
8
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2364
8
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2365
8
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2366
8
            std::string partition_version_key =
2367
8
                    versioned::partition_version_key({instance_id_, partition_id});
2368
8
            versioned_remove_all(txn.get(), meta_key);
2369
8
            txn->remove(index_key);
2370
8
            txn->remove(inverted_index_key);
2371
8
            versioned_remove_all(txn.get(), partition_version_key);
2372
8
            err = txn->commit();
2373
8
            if (err != TxnErrorCode::TXN_OK) {
2374
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2375
0
                return -1;
2376
0
            }
2377
8
        }
2378
2379
9
        if (ret == 0) {
2380
8
            ++num_recycled;
2381
8
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2382
8
            partition_keys.push_back(k);
2383
8
            if (part_pb.db_id() > 0) {
2384
8
                partition_version_keys.push_back(partition_version_key(
2385
8
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2386
8
            }
2387
8
            metrics_context.total_recycled_num = num_recycled;
2388
8
            metrics_context.report();
2389
8
        }
2390
9
        return ret;
2391
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2286
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2287
2
        ++num_scanned;
2288
2
        RecyclePartitionPB part_pb;
2289
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2290
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2291
0
            return -1;
2292
0
        }
2293
2
        int64_t current_time = ::time(nullptr);
2294
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2295
2
                                                            &earlest_ts)) { // not expired
2296
0
            return 0;
2297
0
        }
2298
2
        ++num_expired;
2299
        // decode partition_id
2300
2
        auto k1 = k;
2301
2
        k1.remove_prefix(1);
2302
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2303
2
        decode_key(&k1, &out);
2304
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2305
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2306
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2307
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2308
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2309
        // Change state to RECYCLING
2310
2
        std::unique_ptr<Transaction> txn;
2311
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2312
2
        if (err != TxnErrorCode::TXN_OK) {
2313
0
            LOG_WARNING("failed to create txn").tag("err", err);
2314
0
            return -1;
2315
0
        }
2316
2
        std::string val;
2317
2
        err = txn->get(k, &val);
2318
2
        if (err ==
2319
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2320
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2321
0
            return 0;
2322
0
        }
2323
2
        if (err != TxnErrorCode::TXN_OK) {
2324
0
            LOG_WARNING("failed to get kv");
2325
0
            return -1;
2326
0
        }
2327
2
        part_pb.Clear();
2328
2
        if (!part_pb.ParseFromString(val)) {
2329
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2330
0
            return -1;
2331
0
        }
2332
        // Partitions with PREPARED state MUST have no data
2333
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2334
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2335
1
            txn->put(k, part_pb.SerializeAsString());
2336
1
            err = txn->commit();
2337
1
            if (err != TxnErrorCode::TXN_OK) {
2338
0
                LOG_WARNING("failed to commit txn: {}", err);
2339
0
                return -1;
2340
0
            }
2341
1
        }
2342
2343
2
        int ret = 0;
2344
2
        for (int64_t index_id : part_pb.index_id()) {
2345
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2346
1
                LOG_WARNING("failed to recycle tablets under partition")
2347
1
                        .tag("table_id", part_pb.table_id())
2348
1
                        .tag("instance_id", instance_id_)
2349
1
                        .tag("index_id", index_id)
2350
1
                        .tag("partition_id", partition_id);
2351
1
                ret = -1;
2352
1
            }
2353
2
        }
2354
2
        if (ret == 0 && part_pb.has_db_id()) {
2355
            // Recycle the versioned keys
2356
1
            std::unique_ptr<Transaction> txn;
2357
1
            err = txn_kv_->create_txn(&txn);
2358
1
            if (err != TxnErrorCode::TXN_OK) {
2359
0
                LOG_WARNING("failed to create txn").tag("err", err);
2360
0
                return -1;
2361
0
            }
2362
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2363
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2364
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2365
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2366
1
            std::string partition_version_key =
2367
1
                    versioned::partition_version_key({instance_id_, partition_id});
2368
1
            versioned_remove_all(txn.get(), meta_key);
2369
1
            txn->remove(index_key);
2370
1
            txn->remove(inverted_index_key);
2371
1
            versioned_remove_all(txn.get(), partition_version_key);
2372
1
            err = txn->commit();
2373
1
            if (err != TxnErrorCode::TXN_OK) {
2374
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2375
0
                return -1;
2376
0
            }
2377
1
        }
2378
2379
2
        if (ret == 0) {
2380
1
            ++num_recycled;
2381
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2382
1
            partition_keys.push_back(k);
2383
1
            if (part_pb.db_id() > 0) {
2384
1
                partition_version_keys.push_back(partition_version_key(
2385
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2386
1
            }
2387
1
            metrics_context.total_recycled_num = num_recycled;
2388
1
            metrics_context.report();
2389
1
        }
2390
2
        return ret;
2391
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2286
7
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2287
7
        ++num_scanned;
2288
7
        RecyclePartitionPB part_pb;
2289
7
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2290
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2291
0
            return -1;
2292
0
        }
2293
7
        int64_t current_time = ::time(nullptr);
2294
7
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2295
7
                                                            &earlest_ts)) { // not expired
2296
0
            return 0;
2297
0
        }
2298
7
        ++num_expired;
2299
        // decode partition_id
2300
7
        auto k1 = k;
2301
7
        k1.remove_prefix(1);
2302
7
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2303
7
        decode_key(&k1, &out);
2304
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2305
7
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2306
7
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2307
7
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2308
7
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2309
        // Change state to RECYCLING
2310
7
        std::unique_ptr<Transaction> txn;
2311
7
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2312
7
        if (err != TxnErrorCode::TXN_OK) {
2313
0
            LOG_WARNING("failed to create txn").tag("err", err);
2314
0
            return -1;
2315
0
        }
2316
7
        std::string val;
2317
7
        err = txn->get(k, &val);
2318
7
        if (err ==
2319
7
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2320
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2321
0
            return 0;
2322
0
        }
2323
7
        if (err != TxnErrorCode::TXN_OK) {
2324
0
            LOG_WARNING("failed to get kv");
2325
0
            return -1;
2326
0
        }
2327
7
        part_pb.Clear();
2328
7
        if (!part_pb.ParseFromString(val)) {
2329
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2330
0
            return -1;
2331
0
        }
2332
        // Partitions with PREPARED state MUST have no data
2333
7
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2334
7
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2335
7
            txn->put(k, part_pb.SerializeAsString());
2336
7
            err = txn->commit();
2337
7
            if (err != TxnErrorCode::TXN_OK) {
2338
0
                LOG_WARNING("failed to commit txn: {}", err);
2339
0
                return -1;
2340
0
            }
2341
7
        }
2342
2343
7
        int ret = 0;
2344
31
        for (int64_t index_id : part_pb.index_id()) {
2345
31
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2346
0
                LOG_WARNING("failed to recycle tablets under partition")
2347
0
                        .tag("table_id", part_pb.table_id())
2348
0
                        .tag("instance_id", instance_id_)
2349
0
                        .tag("index_id", index_id)
2350
0
                        .tag("partition_id", partition_id);
2351
0
                ret = -1;
2352
0
            }
2353
31
        }
2354
7
        if (ret == 0 && part_pb.has_db_id()) {
2355
            // Recycle the versioned keys
2356
7
            std::unique_ptr<Transaction> txn;
2357
7
            err = txn_kv_->create_txn(&txn);
2358
7
            if (err != TxnErrorCode::TXN_OK) {
2359
0
                LOG_WARNING("failed to create txn").tag("err", err);
2360
0
                return -1;
2361
0
            }
2362
7
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2363
7
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2364
7
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2365
7
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2366
7
            std::string partition_version_key =
2367
7
                    versioned::partition_version_key({instance_id_, partition_id});
2368
7
            versioned_remove_all(txn.get(), meta_key);
2369
7
            txn->remove(index_key);
2370
7
            txn->remove(inverted_index_key);
2371
7
            versioned_remove_all(txn.get(), partition_version_key);
2372
7
            err = txn->commit();
2373
7
            if (err != TxnErrorCode::TXN_OK) {
2374
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2375
0
                return -1;
2376
0
            }
2377
7
        }
2378
2379
7
        if (ret == 0) {
2380
7
            ++num_recycled;
2381
7
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2382
7
            partition_keys.push_back(k);
2383
7
            if (part_pb.db_id() > 0) {
2384
7
                partition_version_keys.push_back(partition_version_key(
2385
7
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2386
7
            }
2387
7
            metrics_context.total_recycled_num = num_recycled;
2388
7
            metrics_context.report();
2389
7
        }
2390
7
        return ret;
2391
7
    };
2392
2393
15
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2394
5
        if (partition_keys.empty()) return 0;
2395
4
        DORIS_CLOUD_DEFER {
2396
4
            partition_keys.clear();
2397
4
            partition_version_keys.clear();
2398
4
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2395
1
        DORIS_CLOUD_DEFER {
2396
1
            partition_keys.clear();
2397
1
            partition_version_keys.clear();
2398
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2395
3
        DORIS_CLOUD_DEFER {
2396
3
            partition_keys.clear();
2397
3
            partition_version_keys.clear();
2398
3
        };
2399
4
        std::unique_ptr<Transaction> txn;
2400
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2401
4
        if (err != TxnErrorCode::TXN_OK) {
2402
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2403
0
            return -1;
2404
0
        }
2405
8
        for (auto& k : partition_keys) {
2406
8
            txn->remove(k);
2407
8
        }
2408
8
        for (auto& k : partition_version_keys) {
2409
8
            txn->remove(k);
2410
8
        }
2411
4
        err = txn->commit();
2412
4
        if (err != TxnErrorCode::TXN_OK) {
2413
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2414
0
                         << " err=" << err;
2415
0
            return -1;
2416
0
        }
2417
4
        return 0;
2418
4
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2393
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2394
2
        if (partition_keys.empty()) return 0;
2395
1
        DORIS_CLOUD_DEFER {
2396
1
            partition_keys.clear();
2397
1
            partition_version_keys.clear();
2398
1
        };
2399
1
        std::unique_ptr<Transaction> txn;
2400
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2401
1
        if (err != TxnErrorCode::TXN_OK) {
2402
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2403
0
            return -1;
2404
0
        }
2405
1
        for (auto& k : partition_keys) {
2406
1
            txn->remove(k);
2407
1
        }
2408
1
        for (auto& k : partition_version_keys) {
2409
1
            txn->remove(k);
2410
1
        }
2411
1
        err = txn->commit();
2412
1
        if (err != TxnErrorCode::TXN_OK) {
2413
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2414
0
                         << " err=" << err;
2415
0
            return -1;
2416
0
        }
2417
1
        return 0;
2418
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2393
3
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2394
3
        if (partition_keys.empty()) return 0;
2395
3
        DORIS_CLOUD_DEFER {
2396
3
            partition_keys.clear();
2397
3
            partition_version_keys.clear();
2398
3
        };
2399
3
        std::unique_ptr<Transaction> txn;
2400
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2401
3
        if (err != TxnErrorCode::TXN_OK) {
2402
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2403
0
            return -1;
2404
0
        }
2405
7
        for (auto& k : partition_keys) {
2406
7
            txn->remove(k);
2407
7
        }
2408
7
        for (auto& k : partition_version_keys) {
2409
7
            txn->remove(k);
2410
7
        }
2411
3
        err = txn->commit();
2412
3
        if (err != TxnErrorCode::TXN_OK) {
2413
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2414
0
                         << " err=" << err;
2415
0
            return -1;
2416
0
        }
2417
3
        return 0;
2418
3
    };
2419
2420
15
    if (config::enable_recycler_stats_metrics) {
2421
0
        scan_and_statistics_partitions();
2422
0
    }
2423
    // recycle_func and loop_done for scan and recycle
2424
15
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
2425
15
}
2426
2427
14
int InstanceRecycler::recycle_versions() {
2428
14
    if (should_recycle_versioned_keys()) {
2429
2
        return recycle_orphan_partitions();
2430
2
    }
2431
2432
12
    int64_t num_scanned = 0;
2433
12
    int64_t num_recycled = 0;
2434
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
2435
2436
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
2437
2438
12
    auto start_time = steady_clock::now();
2439
2440
12
    DORIS_CLOUD_DEFER {
2441
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2442
12
        metrics_context.finish_report();
2443
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
2444
12
                .tag("instance_id", instance_id_)
2445
12
                .tag("num_scanned", num_scanned)
2446
12
                .tag("num_recycled", num_recycled);
2447
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
2440
12
    DORIS_CLOUD_DEFER {
2441
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2442
12
        metrics_context.finish_report();
2443
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
2444
12
                .tag("instance_id", instance_id_)
2445
12
                .tag("num_scanned", num_scanned)
2446
12
                .tag("num_recycled", num_recycled);
2447
12
    };
2448
2449
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
2450
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
2451
12
    int64_t last_scanned_table_id = 0;
2452
12
    bool is_recycled = false; // Is last scanned kv recycled
2453
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
2454
12
                         &metrics_context, this](std::string_view k, std::string_view) {
2455
2
        ++num_scanned;
2456
2
        auto k1 = k;
2457
2
        k1.remove_prefix(1);
2458
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
2459
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2460
2
        decode_key(&k1, &out);
2461
2
        DCHECK_EQ(out.size(), 6) << k;
2462
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
2463
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
2464
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
2465
0
            return 0;
2466
0
        }
2467
2
        last_scanned_table_id = table_id;
2468
2
        is_recycled = false;
2469
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
2470
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
2471
2
        std::unique_ptr<Transaction> txn;
2472
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2473
2
        if (err != TxnErrorCode::TXN_OK) {
2474
0
            return -1;
2475
0
        }
2476
2
        std::unique_ptr<RangeGetIterator> iter;
2477
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
2478
2
        if (err != TxnErrorCode::TXN_OK) {
2479
0
            return -1;
2480
0
        }
2481
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
2482
1
            return 0;
2483
1
        }
2484
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2485
        // 1. Remove all partition version kvs of this table
2486
1
        auto partition_version_key_begin =
2487
1
                partition_version_key({instance_id_, db_id, table_id, 0});
2488
1
        auto partition_version_key_end =
2489
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
2490
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
2491
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
2492
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
2493
1
                     << " table_id=" << table_id;
2494
        // 2. Remove the table version kv of this table
2495
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
2496
1
        txn->remove(tbl_version_key);
2497
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
2498
        // 3. Remove mow delete bitmap update lock and tablet job lock
2499
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2500
1
        txn->remove(lock_key);
2501
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2502
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2503
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2504
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
2505
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2506
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2507
1
                     << " table_id=" << table_id;
2508
1
        err = txn->commit();
2509
1
        if (err != TxnErrorCode::TXN_OK) {
2510
0
            return -1;
2511
0
        }
2512
1
        metrics_context.total_recycled_num = ++num_recycled;
2513
1
        metrics_context.report();
2514
1
        is_recycled = true;
2515
1
        return 0;
2516
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2454
2
                         &metrics_context, this](std::string_view k, std::string_view) {
2455
2
        ++num_scanned;
2456
2
        auto k1 = k;
2457
2
        k1.remove_prefix(1);
2458
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
2459
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2460
2
        decode_key(&k1, &out);
2461
2
        DCHECK_EQ(out.size(), 6) << k;
2462
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
2463
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
2464
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
2465
0
            return 0;
2466
0
        }
2467
2
        last_scanned_table_id = table_id;
2468
2
        is_recycled = false;
2469
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
2470
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
2471
2
        std::unique_ptr<Transaction> txn;
2472
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2473
2
        if (err != TxnErrorCode::TXN_OK) {
2474
0
            return -1;
2475
0
        }
2476
2
        std::unique_ptr<RangeGetIterator> iter;
2477
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
2478
2
        if (err != TxnErrorCode::TXN_OK) {
2479
0
            return -1;
2480
0
        }
2481
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
2482
1
            return 0;
2483
1
        }
2484
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2485
        // 1. Remove all partition version kvs of this table
2486
1
        auto partition_version_key_begin =
2487
1
                partition_version_key({instance_id_, db_id, table_id, 0});
2488
1
        auto partition_version_key_end =
2489
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
2490
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
2491
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
2492
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
2493
1
                     << " table_id=" << table_id;
2494
        // 2. Remove the table version kv of this table
2495
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
2496
1
        txn->remove(tbl_version_key);
2497
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
2498
        // 3. Remove mow delete bitmap update lock and tablet job lock
2499
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2500
1
        txn->remove(lock_key);
2501
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2502
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2503
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2504
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
2505
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2506
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2507
1
                     << " table_id=" << table_id;
2508
1
        err = txn->commit();
2509
1
        if (err != TxnErrorCode::TXN_OK) {
2510
0
            return -1;
2511
0
        }
2512
1
        metrics_context.total_recycled_num = ++num_recycled;
2513
1
        metrics_context.report();
2514
1
        is_recycled = true;
2515
1
        return 0;
2516
1
    };
2517
2518
12
    if (config::enable_recycler_stats_metrics) {
2519
0
        scan_and_statistics_versions();
2520
0
    }
2521
    // recycle_func and loop_done for scan and recycle
2522
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
2523
14
}
2524
2525
3
int InstanceRecycler::recycle_orphan_partitions() {
2526
3
    int64_t num_scanned = 0;
2527
3
    int64_t num_recycled = 0;
2528
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
2529
2530
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
2531
3
            .tag("instance_id", instance_id_);
2532
2533
3
    auto start_time = steady_clock::now();
2534
2535
3
    DORIS_CLOUD_DEFER {
2536
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2537
3
        metrics_context.finish_report();
2538
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
2539
3
                .tag("instance_id", instance_id_)
2540
3
                .tag("num_scanned", num_scanned)
2541
3
                .tag("num_recycled", num_recycled);
2542
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
2535
3
    DORIS_CLOUD_DEFER {
2536
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2537
3
        metrics_context.finish_report();
2538
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
2539
3
                .tag("instance_id", instance_id_)
2540
3
                .tag("num_scanned", num_scanned)
2541
3
                .tag("num_recycled", num_recycled);
2542
3
    };
2543
2544
3
    bool is_empty_table = false;        // whether the table has no indexes
2545
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
2546
3
    int64_t current_table_id = 0;       // current scanning table id
2547
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
2548
3
                         &current_table_id, &is_table_kvs_recycled,
2549
3
                         this](std::string_view k, std::string_view) {
2550
2
        ++num_scanned;
2551
2552
2
        std::string_view k1(k);
2553
2
        int64_t db_id, table_id, partition_id;
2554
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
2555
2
                                                            &partition_id)) {
2556
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
2557
0
            return -1;
2558
2
        } else if (table_id != current_table_id) {
2559
2
            current_table_id = table_id;
2560
2
            is_table_kvs_recycled = false;
2561
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
2562
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
2563
2
            if (err != TxnErrorCode::TXN_OK) {
2564
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
2565
0
                             << " table_id=" << table_id << " err=" << err;
2566
0
                return -1;
2567
0
            }
2568
2
        }
2569
2570
2
        if (!is_empty_table) {
2571
            // table is not empty, skip recycle
2572
1
            return 0;
2573
1
        }
2574
2575
1
        std::unique_ptr<Transaction> txn;
2576
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2577
1
        if (err != TxnErrorCode::TXN_OK) {
2578
0
            return -1;
2579
0
        }
2580
2581
        // 1. Remove all partition related kvs
2582
1
        std::string partition_meta_key =
2583
1
                versioned::meta_partition_key({instance_id_, partition_id});
2584
1
        std::string partition_index_key =
2585
1
                versioned::partition_index_key({instance_id_, partition_id});
2586
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
2587
1
                {instance_id_, db_id, table_id, partition_id});
2588
1
        std::string partition_version_key =
2589
1
                versioned::partition_version_key({instance_id_, partition_id});
2590
1
        txn->remove(partition_index_key);
2591
1
        txn->remove(partition_inverted_key);
2592
1
        versioned_remove_all(txn.get(), partition_meta_key);
2593
1
        versioned_remove_all(txn.get(), partition_version_key);
2594
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
2595
1
                     << " table_id=" << table_id << " db_id=" << db_id
2596
1
                     << " partition_meta_key=" << hex(partition_meta_key)
2597
1
                     << " partition_version_key=" << hex(partition_version_key);
2598
2599
1
        if (!is_table_kvs_recycled) {
2600
1
            is_table_kvs_recycled = true;
2601
2602
            // 2. Remove the table version kv of this table
2603
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
2604
1
            versioned_remove_all(txn.get(), table_version_key);
2605
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
2606
            // 3. Remove mow delete bitmap update lock and tablet job lock
2607
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2608
1
            txn->remove(lock_key);
2609
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2610
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2611
1
            std::string tablet_job_key_end =
2612
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2613
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
2614
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2615
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2616
1
                         << " table_id=" << table_id;
2617
1
        }
2618
2619
1
        err = txn->commit();
2620
1
        if (err != TxnErrorCode::TXN_OK) {
2621
0
            return -1;
2622
0
        }
2623
1
        metrics_context.total_recycled_num = ++num_recycled;
2624
1
        metrics_context.report();
2625
1
        return 0;
2626
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
2549
2
                         this](std::string_view k, std::string_view) {
2550
2
        ++num_scanned;
2551
2552
2
        std::string_view k1(k);
2553
2
        int64_t db_id, table_id, partition_id;
2554
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
2555
2
                                                            &partition_id)) {
2556
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
2557
0
            return -1;
2558
2
        } else if (table_id != current_table_id) {
2559
2
            current_table_id = table_id;
2560
2
            is_table_kvs_recycled = false;
2561
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
2562
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
2563
2
            if (err != TxnErrorCode::TXN_OK) {
2564
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
2565
0
                             << " table_id=" << table_id << " err=" << err;
2566
0
                return -1;
2567
0
            }
2568
2
        }
2569
2570
2
        if (!is_empty_table) {
2571
            // table is not empty, skip recycle
2572
1
            return 0;
2573
1
        }
2574
2575
1
        std::unique_ptr<Transaction> txn;
2576
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2577
1
        if (err != TxnErrorCode::TXN_OK) {
2578
0
            return -1;
2579
0
        }
2580
2581
        // 1. Remove all partition related kvs
2582
1
        std::string partition_meta_key =
2583
1
                versioned::meta_partition_key({instance_id_, partition_id});
2584
1
        std::string partition_index_key =
2585
1
                versioned::partition_index_key({instance_id_, partition_id});
2586
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
2587
1
                {instance_id_, db_id, table_id, partition_id});
2588
1
        std::string partition_version_key =
2589
1
                versioned::partition_version_key({instance_id_, partition_id});
2590
1
        txn->remove(partition_index_key);
2591
1
        txn->remove(partition_inverted_key);
2592
1
        versioned_remove_all(txn.get(), partition_meta_key);
2593
1
        versioned_remove_all(txn.get(), partition_version_key);
2594
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
2595
1
                     << " table_id=" << table_id << " db_id=" << db_id
2596
1
                     << " partition_meta_key=" << hex(partition_meta_key)
2597
1
                     << " partition_version_key=" << hex(partition_version_key);
2598
2599
1
        if (!is_table_kvs_recycled) {
2600
1
            is_table_kvs_recycled = true;
2601
2602
            // 2. Remove the table version kv of this table
2603
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
2604
1
            versioned_remove_all(txn.get(), table_version_key);
2605
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
2606
            // 3. Remove mow delete bitmap update lock and tablet job lock
2607
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2608
1
            txn->remove(lock_key);
2609
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2610
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2611
1
            std::string tablet_job_key_end =
2612
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2613
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
2614
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2615
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2616
1
                         << " table_id=" << table_id;
2617
1
        }
2618
2619
1
        err = txn->commit();
2620
1
        if (err != TxnErrorCode::TXN_OK) {
2621
0
            return -1;
2622
0
        }
2623
1
        metrics_context.total_recycled_num = ++num_recycled;
2624
1
        metrics_context.report();
2625
1
        return 0;
2626
1
    };
2627
2628
    // recycle_func and loop_done for scan and recycle
2629
3
    return scan_and_recycle(
2630
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
2631
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
2632
3
            std::move(recycle_func));
2633
3
}
2634
2635
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
2636
                                      RecyclerMetricsContext& metrics_context,
2637
49
                                      int64_t partition_id) {
2638
49
    bool is_multi_version =
2639
49
            instance_info_.has_multi_version_status() &&
2640
49
            instance_info_.multi_version_status() != MultiVersionStatus::MULTI_VERSION_DISABLED;
2641
49
    int64_t num_scanned = 0;
2642
49
    std::atomic_long num_recycled = 0;
2643
2644
49
    std::string tablet_key_begin, tablet_key_end;
2645
49
    std::string stats_key_begin, stats_key_end;
2646
49
    std::string job_key_begin, job_key_end;
2647
2648
49
    std::string tablet_belongs;
2649
49
    if (partition_id > 0) {
2650
        // recycle tablets in a partition belonging to the index
2651
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
2652
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
2653
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
2654
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
2655
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
2656
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
2657
33
        tablet_belongs = "partition";
2658
33
    } else {
2659
        // recycle tablets in the index
2660
16
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
2661
16
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
2662
16
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
2663
16
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
2664
16
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
2665
16
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
2666
16
        tablet_belongs = "index";
2667
16
    }
2668
2669
49
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
2670
49
            .tag("table_id", table_id)
2671
49
            .tag("index_id", index_id)
2672
49
            .tag("partition_id", partition_id);
2673
2674
49
    auto start_time = steady_clock::now();
2675
2676
49
    DORIS_CLOUD_DEFER {
2677
49
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2678
49
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
2679
49
                .tag("instance_id", instance_id_)
2680
49
                .tag("table_id", table_id)
2681
49
                .tag("index_id", index_id)
2682
49
                .tag("partition_id", partition_id)
2683
49
                .tag("num_scanned", num_scanned)
2684
49
                .tag("num_recycled", num_recycled);
2685
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
2676
4
    DORIS_CLOUD_DEFER {
2677
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2678
4
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
2679
4
                .tag("instance_id", instance_id_)
2680
4
                .tag("table_id", table_id)
2681
4
                .tag("index_id", index_id)
2682
4
                .tag("partition_id", partition_id)
2683
4
                .tag("num_scanned", num_scanned)
2684
4
                .tag("num_recycled", num_recycled);
2685
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
2676
45
    DORIS_CLOUD_DEFER {
2677
45
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2678
45
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
2679
45
                .tag("instance_id", instance_id_)
2680
45
                .tag("table_id", table_id)
2681
45
                .tag("index_id", index_id)
2682
45
                .tag("partition_id", partition_id)
2683
45
                .tag("num_scanned", num_scanned)
2684
45
                .tag("num_recycled", num_recycled);
2685
45
    };
2686
2687
    // The first string_view represents the tablet key which has been recycled
2688
    // The second bool represents whether the following fdb's tablet key deletion could be done using range move or not
2689
49
    using TabletKeyPair = std::pair<std::string_view, bool>;
2690
49
    SyncExecutor<TabletKeyPair> sync_executor(
2691
49
            _thread_pool_group.recycle_tablet_pool,
2692
49
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
2693
49
                        index_id, partition_id),
2694
4.23k
            [](const TabletKeyPair& k) { return k.first.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKSt4pairISt17basic_string_viewIcSt11char_traitsIcEEbE
Line
Count
Source
2694
4.00k
            [](const TabletKeyPair& k) { return k.first.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKSt4pairISt17basic_string_viewIcSt11char_traitsIcEEbE
Line
Count
Source
2694
237
            [](const TabletKeyPair& k) { return k.first.empty(); });
2695
2696
    // Elements in `tablet_keys` has the same lifetime as `it` in `scan_and_recycle`
2697
49
    std::vector<std::string> tablet_idx_keys;
2698
49
    std::vector<std::string> restore_job_keys;
2699
49
    std::vector<std::string> init_rs_keys;
2700
49
    std::vector<std::string> tablet_compact_stats_keys;
2701
49
    std::vector<std::string> tablet_load_stats_keys;
2702
49
    std::vector<std::string> versioned_meta_tablet_keys;
2703
8.24k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2704
8.24k
        bool use_range_remove = true;
2705
8.24k
        ++num_scanned;
2706
8.24k
        doris::TabletMetaCloudPB tablet_meta_pb;
2707
8.24k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
2708
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
2709
0
            use_range_remove = false;
2710
0
            return -1;
2711
0
        }
2712
8.24k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
2713
2714
8.24k
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
2715
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
2716
4.00k
            return -1;
2717
4.00k
        }
2718
2719
4.24k
        tablet_idx_keys.push_back(meta_tablet_idx_key({instance_id_, tablet_id}));
2720
4.24k
        restore_job_keys.push_back(job_restore_tablet_key({instance_id_, tablet_id}));
2721
4.24k
        if (is_multi_version) {
2722
            // The tablet index/inverted index are recycled in recycle_versioned_tablet.
2723
6
            tablet_compact_stats_keys.push_back(
2724
6
                    versioned::tablet_compact_stats_key({instance_id_, tablet_id}));
2725
6
            tablet_load_stats_keys.push_back(
2726
6
                    versioned::tablet_load_stats_key({instance_id_, tablet_id}));
2727
6
            versioned_meta_tablet_keys.push_back(
2728
6
                    versioned::meta_tablet_key({instance_id_, tablet_id}));
2729
6
        }
2730
4.24k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
2731
4.23k
        sync_executor.add([this, &num_recycled, tid = tablet_id, range_move = use_range_remove,
2732
4.23k
                           &metrics_context, k]() mutable -> TabletKeyPair {
2733
4.23k
            if (recycle_tablet(tid, metrics_context) != 0) {
2734
1
                LOG_WARNING("failed to recycle tablet")
2735
1
                        .tag("instance_id", instance_id_)
2736
1
                        .tag("tablet_id", tid);
2737
1
                range_move = false;
2738
1
                return {std::string_view(), range_move};
2739
1
            }
2740
4.23k
            ++num_recycled;
2741
4.23k
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2742
4.23k
            return {k, range_move};
2743
4.23k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENUlvE_clEv
Line
Count
Source
2732
4.00k
                           &metrics_context, k]() mutable -> TabletKeyPair {
2733
4.00k
            if (recycle_tablet(tid, metrics_context) != 0) {
2734
0
                LOG_WARNING("failed to recycle tablet")
2735
0
                        .tag("instance_id", instance_id_)
2736
0
                        .tag("tablet_id", tid);
2737
0
                range_move = false;
2738
0
                return {std::string_view(), range_move};
2739
0
            }
2740
4.00k
            ++num_recycled;
2741
4.00k
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2742
4.00k
            return {k, range_move};
2743
4.00k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENUlvE_clEv
Line
Count
Source
2732
237
                           &metrics_context, k]() mutable -> TabletKeyPair {
2733
237
            if (recycle_tablet(tid, metrics_context) != 0) {
2734
1
                LOG_WARNING("failed to recycle tablet")
2735
1
                        .tag("instance_id", instance_id_)
2736
1
                        .tag("tablet_id", tid);
2737
1
                range_move = false;
2738
1
                return {std::string_view(), range_move};
2739
1
            }
2740
236
            ++num_recycled;
2741
236
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2742
236
            return {k, range_move};
2743
237
        });
2744
4.23k
        return 0;
2745
4.24k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
2703
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2704
8.00k
        bool use_range_remove = true;
2705
8.00k
        ++num_scanned;
2706
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
2707
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
2708
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
2709
0
            use_range_remove = false;
2710
0
            return -1;
2711
0
        }
2712
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
2713
2714
8.00k
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
2715
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
2716
4.00k
            return -1;
2717
4.00k
        }
2718
2719
4.00k
        tablet_idx_keys.push_back(meta_tablet_idx_key({instance_id_, tablet_id}));
2720
4.00k
        restore_job_keys.push_back(job_restore_tablet_key({instance_id_, tablet_id}));
2721
4.00k
        if (is_multi_version) {
2722
            // The tablet index/inverted index are recycled in recycle_versioned_tablet.
2723
0
            tablet_compact_stats_keys.push_back(
2724
0
                    versioned::tablet_compact_stats_key({instance_id_, tablet_id}));
2725
0
            tablet_load_stats_keys.push_back(
2726
0
                    versioned::tablet_load_stats_key({instance_id_, tablet_id}));
2727
0
            versioned_meta_tablet_keys.push_back(
2728
0
                    versioned::meta_tablet_key({instance_id_, tablet_id}));
2729
0
        }
2730
4.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
2731
4.00k
        sync_executor.add([this, &num_recycled, tid = tablet_id, range_move = use_range_remove,
2732
4.00k
                           &metrics_context, k]() mutable -> TabletKeyPair {
2733
4.00k
            if (recycle_tablet(tid, metrics_context) != 0) {
2734
4.00k
                LOG_WARNING("failed to recycle tablet")
2735
4.00k
                        .tag("instance_id", instance_id_)
2736
4.00k
                        .tag("tablet_id", tid);
2737
4.00k
                range_move = false;
2738
4.00k
                return {std::string_view(), range_move};
2739
4.00k
            }
2740
4.00k
            ++num_recycled;
2741
4.00k
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2742
4.00k
            return {k, range_move};
2743
4.00k
        });
2744
4.00k
        return 0;
2745
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
2703
240
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2704
240
        bool use_range_remove = true;
2705
240
        ++num_scanned;
2706
240
        doris::TabletMetaCloudPB tablet_meta_pb;
2707
240
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
2708
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
2709
0
            use_range_remove = false;
2710
0
            return -1;
2711
0
        }
2712
240
        int64_t tablet_id = tablet_meta_pb.tablet_id();
2713
2714
240
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
2715
0
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
2716
0
            return -1;
2717
0
        }
2718
2719
240
        tablet_idx_keys.push_back(meta_tablet_idx_key({instance_id_, tablet_id}));
2720
240
        restore_job_keys.push_back(job_restore_tablet_key({instance_id_, tablet_id}));
2721
240
        if (is_multi_version) {
2722
            // The tablet index/inverted index are recycled in recycle_versioned_tablet.
2723
6
            tablet_compact_stats_keys.push_back(
2724
6
                    versioned::tablet_compact_stats_key({instance_id_, tablet_id}));
2725
6
            tablet_load_stats_keys.push_back(
2726
6
                    versioned::tablet_load_stats_key({instance_id_, tablet_id}));
2727
6
            versioned_meta_tablet_keys.push_back(
2728
6
                    versioned::meta_tablet_key({instance_id_, tablet_id}));
2729
6
        }
2730
240
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
2731
237
        sync_executor.add([this, &num_recycled, tid = tablet_id, range_move = use_range_remove,
2732
237
                           &metrics_context, k]() mutable -> TabletKeyPair {
2733
237
            if (recycle_tablet(tid, metrics_context) != 0) {
2734
237
                LOG_WARNING("failed to recycle tablet")
2735
237
                        .tag("instance_id", instance_id_)
2736
237
                        .tag("tablet_id", tid);
2737
237
                range_move = false;
2738
237
                return {std::string_view(), range_move};
2739
237
            }
2740
237
            ++num_recycled;
2741
237
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2742
237
            return {k, range_move};
2743
237
        });
2744
237
        return 0;
2745
240
    };
2746
2747
    // TODO(AlexYue): Add one ut to cover use_range_remove = false
2748
49
    auto loop_done = [&, this]() -> int {
2749
49
        bool finished = true;
2750
49
        auto tablet_keys = sync_executor.when_all(&finished);
2751
49
        if (!finished) {
2752
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
2753
1
            return -1;
2754
1
        }
2755
48
        if (tablet_keys.empty() && tablet_idx_keys.empty()) return 0;
2756
46
        if (!tablet_keys.empty() &&
2757
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
2757
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
2757
42
            std::ranges::all_of(tablet_keys, [](const auto& k) { return k.first.empty(); })) {
2758
0
            return -1;
2759
0
        }
2760
        // sort the vector using key's order
2761
46
        std::sort(tablet_keys.begin(), tablet_keys.end(),
2762
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
2762
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
2762
944
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
2763
46
        bool use_range_remove = true;
2764
4.23k
        for (auto& [_, remove] : tablet_keys) {
2765
4.23k
            if (!remove) {
2766
0
                use_range_remove = remove;
2767
0
                break;
2768
0
            }
2769
4.23k
        }
2770
46
        DORIS_CLOUD_DEFER {
2771
46
            tablet_idx_keys.clear();
2772
46
            restore_job_keys.clear();
2773
46
            init_rs_keys.clear();
2774
46
            tablet_compact_stats_keys.clear();
2775
46
            tablet_load_stats_keys.clear();
2776
46
            versioned_meta_tablet_keys.clear();
2777
46
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2770
2
        DORIS_CLOUD_DEFER {
2771
2
            tablet_idx_keys.clear();
2772
2
            restore_job_keys.clear();
2773
2
            init_rs_keys.clear();
2774
2
            tablet_compact_stats_keys.clear();
2775
2
            tablet_load_stats_keys.clear();
2776
2
            versioned_meta_tablet_keys.clear();
2777
2
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2770
44
        DORIS_CLOUD_DEFER {
2771
44
            tablet_idx_keys.clear();
2772
44
            restore_job_keys.clear();
2773
44
            init_rs_keys.clear();
2774
44
            tablet_compact_stats_keys.clear();
2775
44
            tablet_load_stats_keys.clear();
2776
44
            versioned_meta_tablet_keys.clear();
2777
44
        };
2778
46
        std::unique_ptr<Transaction> txn;
2779
46
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2780
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
2781
0
            return -1;
2782
0
        }
2783
46
        std::string tablet_key_end;
2784
46
        if (!tablet_keys.empty()) {
2785
44
            if (use_range_remove) {
2786
44
                tablet_key_end = std::string(tablet_keys.back().first) + '\x00';
2787
44
                txn->remove(tablet_keys.front().first, tablet_key_end);
2788
44
            } else {
2789
0
                for (auto& [k, _] : tablet_keys) {
2790
0
                    txn->remove(k);
2791
0
                }
2792
0
            }
2793
44
        }
2794
46
        if (is_multi_version) {
2795
6
            for (auto& k : tablet_compact_stats_keys) {
2796
                // Remove all versions of tablet compact stats for recycled tablet
2797
6
                LOG_INFO("remove versioned tablet compact stats key")
2798
6
                        .tag("compact_stats_key", hex(k));
2799
6
                versioned_remove_all(txn.get(), k);
2800
6
            }
2801
6
            for (auto& k : tablet_load_stats_keys) {
2802
                // Remove all versions of tablet load stats for recycled tablet
2803
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
2804
6
                versioned_remove_all(txn.get(), k);
2805
6
            }
2806
6
            for (auto& k : versioned_meta_tablet_keys) {
2807
                // Remove all versions of meta tablet for recycled tablet
2808
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
2809
6
                versioned_remove_all(txn.get(), k);
2810
6
            }
2811
5
        }
2812
4.24k
        for (auto& k : tablet_idx_keys) {
2813
4.24k
            txn->remove(k);
2814
            // Invalidate cache for removed tablet_idx_keys
2815
4.24k
            TabletIndexCache* cache = recycler_cache_manager();
2816
4.24k
            if (cache != nullptr) {
2817
                // Extract tablet_id from key: meta_tablet_idx_key({instance_id, tablet_id})
2818
                // The key format is known, we can parse tablet_id from it
2819
0
                std::string_view k1 = k;
2820
0
                k1.remove_prefix(1);
2821
                // 0x01 "meta" ${instance_id} "tablet_index" ${tablet_id}
2822
0
                std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2823
0
                decode_key(&k1, &out);
2824
0
                DCHECK_EQ(out.size(), 4) << k1;
2825
0
                auto tablet_id = std::get<int64_t>(std::get<0>(out[3]));
2826
0
                cache->invalidate(std::make_tuple(instance_id_, tablet_id));
2827
0
            }
2828
4.24k
        }
2829
2830
4.24k
        for (auto& k : restore_job_keys) {
2831
4.24k
            txn->remove(k);
2832
4.24k
        }
2833
46
        for (auto& k : init_rs_keys) {
2834
0
            txn->remove(k);
2835
0
        }
2836
46
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
2837
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
2838
0
                         << ", err=" << err;
2839
0
            return -1;
2840
0
        }
2841
46
        return 0;
2842
46
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
2748
4
    auto loop_done = [&, this]() -> int {
2749
4
        bool finished = true;
2750
4
        auto tablet_keys = sync_executor.when_all(&finished);
2751
4
        if (!finished) {
2752
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
2753
0
            return -1;
2754
0
        }
2755
4
        if (tablet_keys.empty() && tablet_idx_keys.empty()) return 0;
2756
2
        if (!tablet_keys.empty() &&
2757
2
            std::ranges::all_of(tablet_keys, [](const auto& k) { return k.first.empty(); })) {
2758
0
            return -1;
2759
0
        }
2760
        // sort the vector using key's order
2761
2
        std::sort(tablet_keys.begin(), tablet_keys.end(),
2762
2
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
2763
2
        bool use_range_remove = true;
2764
4.00k
        for (auto& [_, remove] : tablet_keys) {
2765
4.00k
            if (!remove) {
2766
0
                use_range_remove = remove;
2767
0
                break;
2768
0
            }
2769
4.00k
        }
2770
2
        DORIS_CLOUD_DEFER {
2771
2
            tablet_idx_keys.clear();
2772
2
            restore_job_keys.clear();
2773
2
            init_rs_keys.clear();
2774
2
            tablet_compact_stats_keys.clear();
2775
2
            tablet_load_stats_keys.clear();
2776
2
            versioned_meta_tablet_keys.clear();
2777
2
        };
2778
2
        std::unique_ptr<Transaction> txn;
2779
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2780
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
2781
0
            return -1;
2782
0
        }
2783
2
        std::string tablet_key_end;
2784
2
        if (!tablet_keys.empty()) {
2785
2
            if (use_range_remove) {
2786
2
                tablet_key_end = std::string(tablet_keys.back().first) + '\x00';
2787
2
                txn->remove(tablet_keys.front().first, tablet_key_end);
2788
2
            } else {
2789
0
                for (auto& [k, _] : tablet_keys) {
2790
0
                    txn->remove(k);
2791
0
                }
2792
0
            }
2793
2
        }
2794
2
        if (is_multi_version) {
2795
0
            for (auto& k : tablet_compact_stats_keys) {
2796
                // Remove all versions of tablet compact stats for recycled tablet
2797
0
                LOG_INFO("remove versioned tablet compact stats key")
2798
0
                        .tag("compact_stats_key", hex(k));
2799
0
                versioned_remove_all(txn.get(), k);
2800
0
            }
2801
0
            for (auto& k : tablet_load_stats_keys) {
2802
                // Remove all versions of tablet load stats for recycled tablet
2803
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
2804
0
                versioned_remove_all(txn.get(), k);
2805
0
            }
2806
0
            for (auto& k : versioned_meta_tablet_keys) {
2807
                // Remove all versions of meta tablet for recycled tablet
2808
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
2809
0
                versioned_remove_all(txn.get(), k);
2810
0
            }
2811
0
        }
2812
4.00k
        for (auto& k : tablet_idx_keys) {
2813
4.00k
            txn->remove(k);
2814
            // Invalidate cache for removed tablet_idx_keys
2815
4.00k
            TabletIndexCache* cache = recycler_cache_manager();
2816
4.00k
            if (cache != nullptr) {
2817
                // Extract tablet_id from key: meta_tablet_idx_key({instance_id, tablet_id})
2818
                // The key format is known, we can parse tablet_id from it
2819
0
                std::string_view k1 = k;
2820
0
                k1.remove_prefix(1);
2821
                // 0x01 "meta" ${instance_id} "tablet_index" ${tablet_id}
2822
0
                std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2823
0
                decode_key(&k1, &out);
2824
0
                DCHECK_EQ(out.size(), 4) << k1;
2825
0
                auto tablet_id = std::get<int64_t>(std::get<0>(out[3]));
2826
0
                cache->invalidate(std::make_tuple(instance_id_, tablet_id));
2827
0
            }
2828
4.00k
        }
2829
2830
4.00k
        for (auto& k : restore_job_keys) {
2831
4.00k
            txn->remove(k);
2832
4.00k
        }
2833
2
        for (auto& k : init_rs_keys) {
2834
0
            txn->remove(k);
2835
0
        }
2836
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
2837
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
2838
0
                         << ", err=" << err;
2839
0
            return -1;
2840
0
        }
2841
2
        return 0;
2842
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
2748
45
    auto loop_done = [&, this]() -> int {
2749
45
        bool finished = true;
2750
45
        auto tablet_keys = sync_executor.when_all(&finished);
2751
45
        if (!finished) {
2752
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
2753
1
            return -1;
2754
1
        }
2755
44
        if (tablet_keys.empty() && tablet_idx_keys.empty()) return 0;
2756
44
        if (!tablet_keys.empty() &&
2757
44
            std::ranges::all_of(tablet_keys, [](const auto& k) { return k.first.empty(); })) {
2758
0
            return -1;
2759
0
        }
2760
        // sort the vector using key's order
2761
44
        std::sort(tablet_keys.begin(), tablet_keys.end(),
2762
44
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
2763
44
        bool use_range_remove = true;
2764
236
        for (auto& [_, remove] : tablet_keys) {
2765
236
            if (!remove) {
2766
0
                use_range_remove = remove;
2767
0
                break;
2768
0
            }
2769
236
        }
2770
44
        DORIS_CLOUD_DEFER {
2771
44
            tablet_idx_keys.clear();
2772
44
            restore_job_keys.clear();
2773
44
            init_rs_keys.clear();
2774
44
            tablet_compact_stats_keys.clear();
2775
44
            tablet_load_stats_keys.clear();
2776
44
            versioned_meta_tablet_keys.clear();
2777
44
        };
2778
44
        std::unique_ptr<Transaction> txn;
2779
44
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2780
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
2781
0
            return -1;
2782
0
        }
2783
44
        std::string tablet_key_end;
2784
44
        if (!tablet_keys.empty()) {
2785
42
            if (use_range_remove) {
2786
42
                tablet_key_end = std::string(tablet_keys.back().first) + '\x00';
2787
42
                txn->remove(tablet_keys.front().first, tablet_key_end);
2788
42
            } else {
2789
0
                for (auto& [k, _] : tablet_keys) {
2790
0
                    txn->remove(k);
2791
0
                }
2792
0
            }
2793
42
        }
2794
44
        if (is_multi_version) {
2795
6
            for (auto& k : tablet_compact_stats_keys) {
2796
                // Remove all versions of tablet compact stats for recycled tablet
2797
6
                LOG_INFO("remove versioned tablet compact stats key")
2798
6
                        .tag("compact_stats_key", hex(k));
2799
6
                versioned_remove_all(txn.get(), k);
2800
6
            }
2801
6
            for (auto& k : tablet_load_stats_keys) {
2802
                // Remove all versions of tablet load stats for recycled tablet
2803
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
2804
6
                versioned_remove_all(txn.get(), k);
2805
6
            }
2806
6
            for (auto& k : versioned_meta_tablet_keys) {
2807
                // Remove all versions of meta tablet for recycled tablet
2808
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
2809
6
                versioned_remove_all(txn.get(), k);
2810
6
            }
2811
5
        }
2812
239
        for (auto& k : tablet_idx_keys) {
2813
239
            txn->remove(k);
2814
            // Invalidate cache for removed tablet_idx_keys
2815
239
            TabletIndexCache* cache = recycler_cache_manager();
2816
239
            if (cache != nullptr) {
2817
                // Extract tablet_id from key: meta_tablet_idx_key({instance_id, tablet_id})
2818
                // The key format is known, we can parse tablet_id from it
2819
0
                std::string_view k1 = k;
2820
0
                k1.remove_prefix(1);
2821
                // 0x01 "meta" ${instance_id} "tablet_index" ${tablet_id}
2822
0
                std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2823
0
                decode_key(&k1, &out);
2824
0
                DCHECK_EQ(out.size(), 4) << k1;
2825
0
                auto tablet_id = std::get<int64_t>(std::get<0>(out[3]));
2826
0
                cache->invalidate(std::make_tuple(instance_id_, tablet_id));
2827
0
            }
2828
239
        }
2829
2830
239
        for (auto& k : restore_job_keys) {
2831
239
            txn->remove(k);
2832
239
        }
2833
44
        for (auto& k : init_rs_keys) {
2834
0
            txn->remove(k);
2835
0
        }
2836
44
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
2837
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
2838
0
                         << ", err=" << err;
2839
0
            return -1;
2840
0
        }
2841
44
        return 0;
2842
44
    };
2843
2844
49
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
2845
49
                               std::move(loop_done));
2846
49
    if (ret != 0) {
2847
3
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
2848
3
        return ret;
2849
3
    }
2850
2851
    // directly remove tablet stats and tablet jobs of these dropped index or partition
2852
46
    std::unique_ptr<Transaction> txn;
2853
46
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2854
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
2855
0
        return -1;
2856
0
    }
2857
46
    txn->remove(stats_key_begin, stats_key_end);
2858
46
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
2859
46
                 << " end=" << hex(stats_key_end);
2860
46
    txn->remove(job_key_begin, job_key_end);
2861
46
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
2862
46
    std::string schema_key_begin, schema_key_end;
2863
46
    std::string schema_dict_key;
2864
46
    std::string versioned_schema_key_begin, versioned_schema_key_end;
2865
46
    if (partition_id <= 0) {
2866
        // Delete schema kv of this index
2867
14
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
2868
14
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
2869
14
        txn->remove(schema_key_begin, schema_key_end);
2870
14
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
2871
14
                     << " end=" << hex(schema_key_end);
2872
14
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
2873
14
        txn->remove(schema_dict_key);
2874
14
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
2875
14
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
2876
14
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
2877
14
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
2878
14
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
2879
14
                     << " end=" << hex(versioned_schema_key_end);
2880
14
    }
2881
2882
46
    TxnErrorCode err = txn->commit();
2883
46
    if (err != TxnErrorCode::TXN_OK) {
2884
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
2885
0
                     << " err=" << err;
2886
0
        return -1;
2887
0
    }
2888
2889
46
    return ret;
2890
46
}
2891
2892
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
2893
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
2894
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
2895
5.61k
    if (num_segments <= 0) return 0;
2896
2897
5.61k
    std::vector<std::string> file_paths;
2898
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
2899
0
        return -1;
2900
0
    }
2901
2902
    // Process inverted indexes
2903
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
2904
    // default format as v1.
2905
5.61k
    InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
2906
5.61k
    bool delete_rowset_data_by_prefix = false;
2907
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
2908
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
2909
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
2910
0
        delete_rowset_data_by_prefix = true;
2911
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
2912
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
2913
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
2914
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
2915
10.0k
            }
2916
10.0k
        }
2917
4.80k
        if (rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
2918
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
2919
2.00k
        }
2920
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
2921
        // schema version and index id are not found, delete rowset data by prefix directly.
2922
0
        delete_rowset_data_by_prefix = true;
2923
809
    } else {
2924
        // otherwise, try to get schema kv
2925
809
        InvertedIndexInfo index_info;
2926
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
2927
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
2928
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
2929
809
                                 &inverted_index_get_ret);
2930
809
        if (inverted_index_get_ret == 0) {
2931
809
            index_format = index_info.first;
2932
809
            index_ids = index_info.second;
2933
809
        } else if (inverted_index_get_ret == 1) {
2934
            // 1. Schema kv not found means tablet has been recycled
2935
            // Maybe some tablet recycle failed by some bugs
2936
            // We need to delete again to double check
2937
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
2938
            // because we are uncertain about the inverted index information.
2939
            // If there are inverted indexes, some data might not be deleted,
2940
            // but this is acceptable as we have made our best effort to delete the data.
2941
0
            LOG_INFO(
2942
0
                    "delete rowset data schema kv not found, need to delete again to double "
2943
0
                    "check")
2944
0
                    .tag("instance_id", instance_id_)
2945
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
2946
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
2947
            // Currently index_ids is guaranteed to be empty,
2948
            // but we clear it again here as a safeguard against future code changes
2949
            // that might cause index_ids to no longer be empty
2950
0
            index_format = InvertedIndexStorageFormatPB::V2;
2951
0
            index_ids.clear();
2952
0
        } else {
2953
            // failed to get schema kv, delete rowset data by prefix directly.
2954
0
            delete_rowset_data_by_prefix = true;
2955
0
        }
2956
809
    }
2957
2958
5.61k
    if (delete_rowset_data_by_prefix) {
2959
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
2960
0
                                  rs_meta_pb.rowset_id_v2());
2961
0
    }
2962
2963
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
2964
5.61k
    if (it == accessor_map_.end()) {
2965
1.60k
        LOG_WARNING("instance has no such resource id")
2966
1.60k
                .tag("instance_id", instance_id_)
2967
1.60k
                .tag("resource_id", rs_meta_pb.resource_id());
2968
1.60k
        return -1;
2969
1.60k
    }
2970
4.01k
    auto& accessor = it->second;
2971
2972
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
2973
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
2974
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
2975
20.0k
        file_paths.push_back(segment_path(tablet_id, rowset_id, i));
2976
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
2977
40.0k
            for (const auto& index_id : index_ids) {
2978
40.0k
                file_paths.push_back(inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
2979
40.0k
                                                            index_id.second));
2980
40.0k
            }
2981
20.0k
        } else if (!index_ids.empty()) {
2982
0
            file_paths.push_back(inverted_index_path_v2(tablet_id, rowset_id, i));
2983
0
        }
2984
20.0k
    }
2985
2986
    // Process delete bitmap - check if it's stored in packed file
2987
4.01k
    bool delete_bitmap_is_packed = false;
2988
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
2989
4.01k
                                                       &delete_bitmap_is_packed) != 0) {
2990
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
2991
0
                .tag("instance_id", instance_id_)
2992
0
                .tag("tablet_id", tablet_id)
2993
0
                .tag("rowset_id", rowset_id);
2994
0
        return -1;
2995
0
    }
2996
    // Only delete standalone delete bitmap file if not stored in packed file
2997
4.01k
    if (!delete_bitmap_is_packed) {
2998
4.01k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
2999
4.01k
    }
3000
    // TODO(AlexYue): seems could do do batch
3001
4.01k
    return accessor->delete_files(file_paths);
3002
4.01k
}
3003
3004
62.3k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3005
62.3k
    LOG_INFO("begin process_packed_file_location_index")
3006
62.3k
            .tag("instance_id", instance_id_)
3007
62.3k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3008
62.3k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3009
62.3k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3010
62.3k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3011
62.3k
    if (index_map.empty()) {
3012
62.3k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3013
62.3k
                .tag("instance_id", instance_id_)
3014
62.3k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3015
62.3k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3016
62.3k
        return 0;
3017
62.3k
    }
3018
3019
16
    struct PackedSmallFileInfo {
3020
16
        std::string small_file_path;
3021
16
    };
3022
16
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3023
16
    packed_file_updates.reserve(index_map.size());
3024
27
    for (const auto& [small_path, index_pb] : index_map) {
3025
27
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3026
0
            continue;
3027
0
        }
3028
27
        packed_file_updates[index_pb.packed_file_path()].push_back(
3029
27
                PackedSmallFileInfo {small_path});
3030
27
    }
3031
16
    if (packed_file_updates.empty()) {
3032
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3033
0
                .tag("instance_id", instance_id_)
3034
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3035
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3036
0
                .tag("index_map_size", index_map.size());
3037
0
        return 0;
3038
0
    }
3039
3040
16
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3041
16
    int ret = 0;
3042
24
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3043
24
        if (small_files.empty()) {
3044
0
            continue;
3045
0
        }
3046
3047
24
        bool success = false;
3048
24
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3049
24
            std::unique_ptr<Transaction> txn;
3050
24
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3051
24
            if (err != TxnErrorCode::TXN_OK) {
3052
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3053
0
                        .tag("instance_id", instance_id_)
3054
0
                        .tag("packed_file_path", packed_file_path)
3055
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3056
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3057
0
                        .tag("err", err);
3058
0
                ret = -1;
3059
0
                break;
3060
0
            }
3061
3062
24
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3063
24
            std::string packed_val;
3064
24
            err = txn->get(packed_key, &packed_val);
3065
24
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3066
0
                LOG_WARNING("packed file info not found when recycling rowset")
3067
0
                        .tag("instance_id", instance_id_)
3068
0
                        .tag("packed_file_path", packed_file_path)
3069
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3070
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3071
0
                        .tag("key", hex(packed_key))
3072
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3073
                // Skip this packed file entry and continue with others
3074
0
                success = true;
3075
0
                break;
3076
0
            }
3077
24
            if (err != TxnErrorCode::TXN_OK) {
3078
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
3079
0
                        .tag("instance_id", instance_id_)
3080
0
                        .tag("packed_file_path", packed_file_path)
3081
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3082
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3083
0
                        .tag("err", err);
3084
0
                ret = -1;
3085
0
                break;
3086
0
            }
3087
3088
24
            cloud::PackedFileInfoPB packed_info;
3089
24
            if (!packed_info.ParseFromString(packed_val)) {
3090
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
3091
0
                        .tag("instance_id", instance_id_)
3092
0
                        .tag("packed_file_path", packed_file_path)
3093
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3094
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3095
0
                ret = -1;
3096
0
                break;
3097
0
            }
3098
3099
24
            LOG_INFO("packed file update check")
3100
24
                    .tag("instance_id", instance_id_)
3101
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3102
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3103
24
                    .tag("merged_file_path", packed_file_path)
3104
24
                    .tag("requested_small_files", small_files.size())
3105
24
                    .tag("merge_entries", packed_info.slices_size());
3106
3107
24
            auto* small_file_entries = packed_info.mutable_slices();
3108
24
            int64_t changed_files = 0;
3109
24
            int64_t missing_entries = 0;
3110
24
            int64_t already_deleted = 0;
3111
27
            for (const auto& small_file_info : small_files) {
3112
27
                bool found = false;
3113
87
                for (auto& small_file_entry : *small_file_entries) {
3114
87
                    if (small_file_entry.path() == small_file_info.small_file_path) {
3115
27
                        if (!small_file_entry.deleted()) {
3116
27
                            small_file_entry.set_deleted(true);
3117
27
                            if (!small_file_entry.corrected()) {
3118
27
                                small_file_entry.set_corrected(true);
3119
27
                            }
3120
27
                            ++changed_files;
3121
27
                        } else {
3122
0
                            ++already_deleted;
3123
0
                        }
3124
27
                        found = true;
3125
27
                        break;
3126
27
                    }
3127
87
                }
3128
27
                if (!found) {
3129
0
                    ++missing_entries;
3130
0
                    LOG_WARNING("packed file info missing small file entry")
3131
0
                            .tag("instance_id", instance_id_)
3132
0
                            .tag("packed_file_path", packed_file_path)
3133
0
                            .tag("small_file_path", small_file_info.small_file_path)
3134
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3135
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
3136
0
                }
3137
27
            }
3138
3139
24
            if (changed_files == 0) {
3140
0
                LOG_INFO("skip merge file update: no merge entries changed")
3141
0
                        .tag("instance_id", instance_id_)
3142
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3143
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3144
0
                        .tag("merged_file_path", packed_file_path)
3145
0
                        .tag("missing_entries", missing_entries)
3146
0
                        .tag("already_deleted", already_deleted)
3147
0
                        .tag("requested_small_files", small_files.size())
3148
0
                        .tag("merge_entries", packed_info.slices_size());
3149
0
                success = true;
3150
0
                break;
3151
0
            }
3152
3153
            // Calculate remaining files
3154
24
            int64_t left_file_count = 0;
3155
24
            int64_t left_file_bytes = 0;
3156
141
            for (const auto& small_file_entry : packed_info.slices()) {
3157
141
                if (!small_file_entry.deleted()) {
3158
57
                    ++left_file_count;
3159
57
                    left_file_bytes += small_file_entry.size();
3160
57
                }
3161
141
            }
3162
24
            packed_info.set_remaining_slice_bytes(left_file_bytes);
3163
24
            packed_info.set_ref_cnt(left_file_count);
3164
24
            LOG_INFO("updated packed file reference info")
3165
24
                    .tag("instance_id", instance_id_)
3166
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3167
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3168
24
                    .tag("packed_file_path", packed_file_path)
3169
24
                    .tag("ref_cnt", left_file_count)
3170
24
                    .tag("left_file_bytes", left_file_bytes);
3171
3172
24
            if (left_file_count == 0) {
3173
7
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3174
7
            }
3175
3176
24
            std::string updated_val;
3177
24
            if (!packed_info.SerializeToString(&updated_val)) {
3178
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
3179
0
                        .tag("instance_id", instance_id_)
3180
0
                        .tag("packed_file_path", packed_file_path)
3181
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3182
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3183
0
                ret = -1;
3184
0
                break;
3185
0
            }
3186
3187
24
            txn->put(packed_key, updated_val);
3188
24
            err = txn->commit();
3189
24
            if (err == TxnErrorCode::TXN_OK) {
3190
24
                success = true;
3191
24
                if (left_file_count == 0) {
3192
7
                    LOG_INFO("packed file ready to delete, deleting immediately")
3193
7
                            .tag("instance_id", instance_id_)
3194
7
                            .tag("packed_file_path", packed_file_path);
3195
7
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3196
0
                        ret = -1;
3197
0
                    }
3198
7
                }
3199
24
                break;
3200
24
            }
3201
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
3202
0
                if (attempt >= max_retry_times) {
3203
0
                    LOG_WARNING("packed file info update conflict after max retry")
3204
0
                            .tag("instance_id", instance_id_)
3205
0
                            .tag("packed_file_path", packed_file_path)
3206
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3207
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
3208
0
                            .tag("changed_files", changed_files)
3209
0
                            .tag("attempt", attempt);
3210
0
                    ret = -1;
3211
0
                    break;
3212
0
                }
3213
0
                LOG_WARNING("packed file info update conflict, retrying")
3214
0
                        .tag("instance_id", instance_id_)
3215
0
                        .tag("packed_file_path", packed_file_path)
3216
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3217
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3218
0
                        .tag("changed_files", changed_files)
3219
0
                        .tag("attempt", attempt);
3220
0
                sleep_for_packed_file_retry();
3221
0
                continue;
3222
0
            }
3223
3224
0
            LOG_WARNING("failed to commit packed file info update")
3225
0
                    .tag("instance_id", instance_id_)
3226
0
                    .tag("packed_file_path", packed_file_path)
3227
0
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3228
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3229
0
                    .tag("err", err)
3230
0
                    .tag("changed_files", changed_files);
3231
0
            ret = -1;
3232
0
            break;
3233
0
        }
3234
3235
24
        if (!success) {
3236
0
            ret = -1;
3237
0
        }
3238
24
    }
3239
3240
16
    return ret;
3241
16
}
3242
3243
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(int64_t tablet_id,
3244
                                                                     const std::string& rowset_id,
3245
58.2k
                                                                     bool* out_is_packed) {
3246
58.2k
    if (out_is_packed) {
3247
58.2k
        *out_is_packed = false;
3248
58.2k
    }
3249
3250
    // Get delete bitmap storage info from FDB
3251
58.2k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
3252
58.2k
    std::unique_ptr<Transaction> txn;
3253
58.2k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
3254
58.2k
    if (err != TxnErrorCode::TXN_OK) {
3255
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
3256
0
                .tag("instance_id", instance_id_)
3257
0
                .tag("tablet_id", tablet_id)
3258
0
                .tag("rowset_id", rowset_id)
3259
0
                .tag("err", err);
3260
0
        return -1;
3261
0
    }
3262
3263
58.2k
    std::string dbm_val;
3264
58.2k
    err = txn->get(dbm_key, &dbm_val);
3265
58.2k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3266
        // No delete bitmap for this rowset, nothing to do
3267
4.63k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
3268
4.63k
                .tag("instance_id", instance_id_)
3269
4.63k
                .tag("tablet_id", tablet_id)
3270
4.63k
                .tag("rowset_id", rowset_id);
3271
4.63k
        return 0;
3272
4.63k
    }
3273
53.5k
    if (err != TxnErrorCode::TXN_OK) {
3274
0
        LOG_WARNING("failed to get delete bitmap storage")
3275
0
                .tag("instance_id", instance_id_)
3276
0
                .tag("tablet_id", tablet_id)
3277
0
                .tag("rowset_id", rowset_id)
3278
0
                .tag("err", err);
3279
0
        return -1;
3280
0
    }
3281
3282
53.5k
    DeleteBitmapStoragePB storage;
3283
53.5k
    if (!storage.ParseFromString(dbm_val)) {
3284
0
        LOG_WARNING("failed to parse delete bitmap storage")
3285
0
                .tag("instance_id", instance_id_)
3286
0
                .tag("tablet_id", tablet_id)
3287
0
                .tag("rowset_id", rowset_id);
3288
0
        return -1;
3289
0
    }
3290
3291
    // Check if delete bitmap is stored in packed file
3292
53.5k
    if (!storage.has_packed_slice_location() ||
3293
53.5k
        storage.packed_slice_location().packed_file_path().empty()) {
3294
        // Not stored in packed file, nothing to do
3295
53.5k
        return 0;
3296
53.5k
    }
3297
3298
0
    if (out_is_packed) {
3299
0
        *out_is_packed = true;
3300
0
    }
3301
3302
0
    const auto& packed_loc = storage.packed_slice_location();
3303
0
    const std::string& packed_file_path = packed_loc.packed_file_path();
3304
3305
0
    LOG_INFO("decrementing delete bitmap packed file ref count")
3306
0
            .tag("instance_id", instance_id_)
3307
0
            .tag("tablet_id", tablet_id)
3308
0
            .tag("rowset_id", rowset_id)
3309
0
            .tag("packed_file_path", packed_file_path);
3310
3311
0
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3312
0
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3313
0
        std::unique_ptr<Transaction> update_txn;
3314
0
        err = txn_kv_->create_txn(&update_txn);
3315
0
        if (err != TxnErrorCode::TXN_OK) {
3316
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
3317
0
                    .tag("instance_id", instance_id_)
3318
0
                    .tag("tablet_id", tablet_id)
3319
0
                    .tag("rowset_id", rowset_id)
3320
0
                    .tag("err", err);
3321
0
            return -1;
3322
0
        }
3323
3324
0
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3325
0
        std::string packed_val;
3326
0
        err = update_txn->get(packed_key, &packed_val);
3327
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3328
0
            LOG_WARNING("packed file info not found for delete bitmap")
3329
0
                    .tag("instance_id", instance_id_)
3330
0
                    .tag("tablet_id", tablet_id)
3331
0
                    .tag("rowset_id", rowset_id)
3332
0
                    .tag("packed_file_path", packed_file_path);
3333
0
            return 0;
3334
0
        }
3335
0
        if (err != TxnErrorCode::TXN_OK) {
3336
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
3337
0
                    .tag("instance_id", instance_id_)
3338
0
                    .tag("tablet_id", tablet_id)
3339
0
                    .tag("rowset_id", rowset_id)
3340
0
                    .tag("packed_file_path", packed_file_path)
3341
0
                    .tag("err", err);
3342
0
            return -1;
3343
0
        }
3344
3345
0
        cloud::PackedFileInfoPB packed_info;
3346
0
        if (!packed_info.ParseFromString(packed_val)) {
3347
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
3348
0
                    .tag("instance_id", instance_id_)
3349
0
                    .tag("tablet_id", tablet_id)
3350
0
                    .tag("rowset_id", rowset_id)
3351
0
                    .tag("packed_file_path", packed_file_path);
3352
0
            return -1;
3353
0
        }
3354
3355
        // Find and mark the small file entry as deleted
3356
        // Use tablet_id and rowset_id to match entry instead of path,
3357
        // because path format may vary with path_version (with or without shard prefix)
3358
0
        auto* entries = packed_info.mutable_slices();
3359
0
        bool found = false;
3360
0
        bool already_deleted = false;
3361
0
        for (auto& entry : *entries) {
3362
0
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
3363
0
                if (!entry.deleted()) {
3364
0
                    entry.set_deleted(true);
3365
0
                    if (!entry.corrected()) {
3366
0
                        entry.set_corrected(true);
3367
0
                    }
3368
0
                } else {
3369
0
                    already_deleted = true;
3370
0
                }
3371
0
                found = true;
3372
0
                break;
3373
0
            }
3374
0
        }
3375
3376
0
        if (!found) {
3377
0
            LOG_WARNING("delete bitmap entry not found in packed file")
3378
0
                    .tag("instance_id", instance_id_)
3379
0
                    .tag("tablet_id", tablet_id)
3380
0
                    .tag("rowset_id", rowset_id)
3381
0
                    .tag("packed_file_path", packed_file_path);
3382
0
            return 0;
3383
0
        }
3384
3385
0
        if (already_deleted) {
3386
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
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
            return 0;
3392
0
        }
3393
3394
        // Calculate remaining files
3395
0
        int64_t left_file_count = 0;
3396
0
        int64_t left_file_bytes = 0;
3397
0
        for (const auto& entry : packed_info.slices()) {
3398
0
            if (!entry.deleted()) {
3399
0
                ++left_file_count;
3400
0
                left_file_bytes += entry.size();
3401
0
            }
3402
0
        }
3403
0
        packed_info.set_remaining_slice_bytes(left_file_bytes);
3404
0
        packed_info.set_ref_cnt(left_file_count);
3405
3406
0
        if (left_file_count == 0) {
3407
0
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3408
0
        }
3409
3410
0
        std::string updated_val;
3411
0
        if (!packed_info.SerializeToString(&updated_val)) {
3412
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
3413
0
                    .tag("instance_id", instance_id_)
3414
0
                    .tag("tablet_id", tablet_id)
3415
0
                    .tag("rowset_id", rowset_id)
3416
0
                    .tag("packed_file_path", packed_file_path);
3417
0
            return -1;
3418
0
        }
3419
3420
0
        update_txn->put(packed_key, updated_val);
3421
0
        err = update_txn->commit();
3422
0
        if (err == TxnErrorCode::TXN_OK) {
3423
0
            LOG_INFO("delete bitmap packed file ref count decremented")
3424
0
                    .tag("instance_id", instance_id_)
3425
0
                    .tag("tablet_id", tablet_id)
3426
0
                    .tag("rowset_id", rowset_id)
3427
0
                    .tag("packed_file_path", packed_file_path)
3428
0
                    .tag("left_file_count", left_file_count);
3429
0
            if (left_file_count == 0) {
3430
0
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3431
0
                    return -1;
3432
0
                }
3433
0
            }
3434
0
            return 0;
3435
0
        }
3436
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
3437
0
            if (attempt >= max_retry_times) {
3438
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
3439
0
                        .tag("instance_id", instance_id_)
3440
0
                        .tag("tablet_id", tablet_id)
3441
0
                        .tag("rowset_id", rowset_id)
3442
0
                        .tag("packed_file_path", packed_file_path)
3443
0
                        .tag("attempt", attempt);
3444
0
                return -1;
3445
0
            }
3446
0
            sleep_for_packed_file_retry();
3447
0
            continue;
3448
0
        }
3449
3450
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
3451
0
                .tag("instance_id", instance_id_)
3452
0
                .tag("tablet_id", tablet_id)
3453
0
                .tag("rowset_id", rowset_id)
3454
0
                .tag("packed_file_path", packed_file_path)
3455
0
                .tag("err", err);
3456
0
        return -1;
3457
0
    }
3458
3459
0
    return -1;
3460
0
}
3461
3462
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
3463
                                                const std::string& packed_key,
3464
7
                                                const cloud::PackedFileInfoPB& packed_info) {
3465
7
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
3466
0
        LOG_WARNING("packed file missing resource id when recycling")
3467
0
                .tag("instance_id", instance_id_)
3468
0
                .tag("packed_file_path", packed_file_path);
3469
0
        return -1;
3470
0
    }
3471
3472
7
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
3473
7
    if (!accessor) {
3474
0
        LOG_WARNING("no accessor available to delete packed file")
3475
0
                .tag("instance_id", instance_id_)
3476
0
                .tag("packed_file_path", packed_file_path)
3477
0
                .tag("resource_id", packed_info.resource_id());
3478
0
        return -1;
3479
0
    }
3480
3481
7
    int del_ret = accessor->delete_file(packed_file_path);
3482
7
    if (del_ret != 0 && del_ret != 1) {
3483
0
        LOG_WARNING("failed to delete packed file")
3484
0
                .tag("instance_id", instance_id_)
3485
0
                .tag("packed_file_path", packed_file_path)
3486
0
                .tag("resource_id", resource_id)
3487
0
                .tag("ret", del_ret);
3488
0
        return -1;
3489
0
    }
3490
7
    if (del_ret == 1) {
3491
0
        LOG_INFO("packed file already removed")
3492
0
                .tag("instance_id", instance_id_)
3493
0
                .tag("packed_file_path", packed_file_path)
3494
0
                .tag("resource_id", resource_id);
3495
7
    } else {
3496
7
        LOG_INFO("deleted packed file")
3497
7
                .tag("instance_id", instance_id_)
3498
7
                .tag("packed_file_path", packed_file_path)
3499
7
                .tag("resource_id", resource_id);
3500
7
    }
3501
3502
7
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
3503
7
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3504
7
        std::unique_ptr<Transaction> del_txn;
3505
7
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
3506
7
        if (err != TxnErrorCode::TXN_OK) {
3507
0
            LOG_WARNING("failed to create txn when removing packed file kv")
3508
0
                    .tag("instance_id", instance_id_)
3509
0
                    .tag("packed_file_path", packed_file_path)
3510
0
                    .tag("attempt", attempt)
3511
0
                    .tag("err", err);
3512
0
            return -1;
3513
0
        }
3514
3515
7
        std::string latest_val;
3516
7
        err = del_txn->get(packed_key, &latest_val);
3517
7
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3518
0
            return 0;
3519
0
        }
3520
7
        if (err != TxnErrorCode::TXN_OK) {
3521
0
            LOG_WARNING("failed to re-read packed file kv before removal")
3522
0
                    .tag("instance_id", instance_id_)
3523
0
                    .tag("packed_file_path", packed_file_path)
3524
0
                    .tag("attempt", attempt)
3525
0
                    .tag("err", err);
3526
0
            return -1;
3527
0
        }
3528
3529
7
        cloud::PackedFileInfoPB latest_info;
3530
7
        if (!latest_info.ParseFromString(latest_val)) {
3531
0
            LOG_WARNING("failed to parse packed file info before removal")
3532
0
                    .tag("instance_id", instance_id_)
3533
0
                    .tag("packed_file_path", packed_file_path)
3534
0
                    .tag("attempt", attempt);
3535
0
            return -1;
3536
0
        }
3537
3538
7
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
3539
7
              latest_info.ref_cnt() == 0)) {
3540
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
3541
0
                    .tag("instance_id", instance_id_)
3542
0
                    .tag("packed_file_path", packed_file_path)
3543
0
                    .tag("attempt", attempt);
3544
0
            return 0;
3545
0
        }
3546
3547
7
        del_txn->remove(packed_key);
3548
7
        err = del_txn->commit();
3549
7
        if (err == TxnErrorCode::TXN_OK) {
3550
7
            LOG_INFO("removed packed file metadata")
3551
7
                    .tag("instance_id", instance_id_)
3552
7
                    .tag("packed_file_path", packed_file_path);
3553
7
            return 0;
3554
7
        }
3555
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
3556
0
            if (attempt >= max_retry_times) {
3557
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
3558
0
                        .tag("instance_id", instance_id_)
3559
0
                        .tag("packed_file_path", packed_file_path)
3560
0
                        .tag("attempt", attempt);
3561
0
                return -1;
3562
0
            }
3563
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
3564
0
                    .tag("instance_id", instance_id_)
3565
0
                    .tag("packed_file_path", packed_file_path)
3566
0
                    .tag("attempt", attempt);
3567
0
            sleep_for_packed_file_retry();
3568
0
            continue;
3569
0
        }
3570
0
        LOG_WARNING("failed to remove packed file kv")
3571
0
                .tag("instance_id", instance_id_)
3572
0
                .tag("packed_file_path", packed_file_path)
3573
0
                .tag("attempt", attempt)
3574
0
                .tag("err", err);
3575
0
        return -1;
3576
0
    }
3577
0
    return -1;
3578
7
}
3579
3580
int InstanceRecycler::delete_rowset_data(
3581
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
3582
98
        RecyclerMetricsContext& metrics_context) {
3583
98
    int ret = 0;
3584
    // resource_id -> file_paths
3585
98
    std::map<std::string, std::vector<std::string>> resource_file_paths;
3586
    // (resource_id, tablet_id, rowset_id)
3587
98
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
3588
98
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
3589
3590
57.1k
    for (const auto& [_, rs] : rowsets) {
3591
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
3592
        // due to aborted schema change.
3593
57.1k
        if (is_formal_rowset) {
3594
3.16k
            std::lock_guard lock(recycled_tablets_mtx_);
3595
3.16k
            if (recycled_tablets_.count(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
3596
                // Tablet has been recycled and this rowset has no packed slices, so file data
3597
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
3598
                // slice info must still run to decrement packed file ref counts.
3599
0
                continue;
3600
0
            }
3601
3.16k
        }
3602
3603
57.1k
        int64_t num_segments = rs.num_segments();
3604
        // Check num_segments before accessor lookup, because empty rowsets
3605
        // (e.g. base compaction output of empty rowsets) may have no resource_id
3606
        // set. Skipping them early avoids a spurious "no such resource id" error
3607
        // that marks the entire batch as failed and prevents txn_remove from
3608
        // cleaning up recycle KV keys.
3609
57.1k
        if (num_segments <= 0) {
3610
0
            metrics_context.total_recycled_num++;
3611
0
            metrics_context.total_recycled_data_size += rs.total_disk_size();
3612
0
            continue;
3613
0
        }
3614
3615
57.1k
        auto it = accessor_map_.find(rs.resource_id());
3616
        // possible if the accessor is not initilized correctly
3617
57.1k
        if (it == accessor_map_.end()) [[unlikely]] {
3618
3.00k
            LOG_WARNING("instance has no such resource id")
3619
3.00k
                    .tag("instance_id", instance_id_)
3620
3.00k
                    .tag("resource_id", rs.resource_id());
3621
3.00k
            ret = -1;
3622
3.00k
            continue;
3623
3.00k
        }
3624
3625
54.1k
        auto& file_paths = resource_file_paths[rs.resource_id()];
3626
54.1k
        const auto& rowset_id = rs.rowset_id_v2();
3627
54.1k
        int64_t tablet_id = rs.tablet_id();
3628
54.1k
        LOG_INFO("recycle rowset merge index size")
3629
54.1k
                .tag("instance_id", instance_id_)
3630
54.1k
                .tag("tablet_id", tablet_id)
3631
54.1k
                .tag("rowset_id", rowset_id)
3632
54.1k
                .tag("merge_index_size", rs.packed_slice_locations_size());
3633
54.1k
        if (decrement_packed_file_ref_counts(rs) != 0) {
3634
0
            ret = -1;
3635
0
            continue;
3636
0
        }
3637
3638
        // Process delete bitmap - check if it's stored in packed file
3639
54.1k
        bool delete_bitmap_is_packed = false;
3640
54.1k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3641
54.1k
                                                           &delete_bitmap_is_packed) != 0) {
3642
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3643
0
                    .tag("instance_id", instance_id_)
3644
0
                    .tag("tablet_id", tablet_id)
3645
0
                    .tag("rowset_id", rowset_id);
3646
0
            ret = -1;
3647
0
            continue;
3648
0
        }
3649
        // Only delete standalone delete bitmap file if not stored in packed file
3650
54.2k
        if (!delete_bitmap_is_packed) {
3651
54.2k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3652
54.2k
        }
3653
3654
        // Process inverted indexes
3655
54.1k
        std::vector<std::pair<int64_t, std::string>> index_ids;
3656
        // default format as v1.
3657
54.1k
        InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
3658
54.1k
        int inverted_index_get_ret = 0;
3659
54.1k
        if (rs.has_tablet_schema()) {
3660
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
3661
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3662
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3663
53.5k
                }
3664
53.5k
            }
3665
26.6k
            if (rs.tablet_schema().has_inverted_index_storage_format()) {
3666
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
3667
26.5k
            }
3668
27.5k
        } else {
3669
27.5k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
3670
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
3671
0
                                "instance_id="
3672
0
                             << instance_id_ << " tablet_id=" << tablet_id
3673
0
                             << " rowset_id=" << rowset_id;
3674
0
                ret = -1;
3675
0
                continue;
3676
0
            }
3677
27.5k
            InvertedIndexInfo index_info;
3678
27.5k
            inverted_index_get_ret =
3679
27.5k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
3680
27.5k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3681
27.5k
                                     &inverted_index_get_ret);
3682
27.5k
            if (inverted_index_get_ret == 0) {
3683
27.0k
                index_format = index_info.first;
3684
27.0k
                index_ids = index_info.second;
3685
27.0k
            } else if (inverted_index_get_ret == 1) {
3686
                // 1. Schema kv not found means tablet has been recycled
3687
                // Maybe some tablet recycle failed by some bugs
3688
                // We need to delete again to double check
3689
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3690
                // because we are uncertain about the inverted index information.
3691
                // If there are inverted indexes, some data might not be deleted,
3692
                // but this is acceptable as we have made our best effort to delete the data.
3693
507
                LOG_INFO(
3694
507
                        "delete rowset data schema kv not found, need to delete again to "
3695
507
                        "double "
3696
507
                        "check")
3697
507
                        .tag("instance_id", instance_id_)
3698
507
                        .tag("tablet_id", tablet_id)
3699
507
                        .tag("rowset", rs.ShortDebugString());
3700
                // Currently index_ids is guaranteed to be empty,
3701
                // but we clear it again here as a safeguard against future code changes
3702
                // that might cause index_ids to no longer be empty
3703
507
                index_format = InvertedIndexStorageFormatPB::V2;
3704
507
                index_ids.clear();
3705
18.4E
            } else {
3706
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
3707
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
3708
18.4E
                ret = -1;
3709
18.4E
                continue;
3710
18.4E
            }
3711
27.5k
        }
3712
54.2k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3713
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3714
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3715
5
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
3716
5
            continue;
3717
5
        }
3718
324k
        for (int64_t i = 0; i < num_segments; ++i) {
3719
269k
            file_paths.push_back(segment_path(tablet_id, rowset_id, i));
3720
269k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
3721
535k
                for (const auto& index_id : index_ids) {
3722
535k
                    file_paths.push_back(inverted_index_path_v1(tablet_id, rowset_id, i,
3723
535k
                                                                index_id.first, index_id.second));
3724
535k
                }
3725
267k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
3726
                // try to recycle inverted index v2 when get_ret == 1
3727
                // we treat schema not found as if it has a v2 format inverted index
3728
                // to reduce chance of data leakage
3729
2.50k
                if (inverted_index_get_ret == 1) {
3730
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
3731
2.50k
                            .tag("instance_id", instance_id_)
3732
2.50k
                            .tag("inverted index v2 path",
3733
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, i));
3734
2.50k
                }
3735
2.50k
                file_paths.push_back(inverted_index_path_v2(tablet_id, rowset_id, i));
3736
2.50k
            }
3737
269k
        }
3738
54.1k
    }
3739
3740
98
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
3741
98
                                                 "delete_rowset_data",
3742
98
                                                 [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clERKi
Line
Count
Source
3742
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
3742
51
                                                 [](const int& ret) { return ret != 0; });
3743
98
    for (auto& [resource_id, file_paths] : resource_file_paths) {
3744
51
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
3745
51
            DCHECK(accessor_map_.count(*rid))
3746
0
                    << "uninitilized accessor, instance_id=" << instance_id_
3747
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
3748
51
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
3749
51
                                     &accessor_map_);
3750
51
            if (!accessor_map_.contains(*rid)) {
3751
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
3752
0
                        .tag("resource_id", resource_id)
3753
0
                        .tag("instance_id", instance_id_);
3754
0
                return -1;
3755
0
            }
3756
51
            auto& accessor = accessor_map_[*rid];
3757
51
            int ret = accessor->delete_files(*paths);
3758
51
            if (!ret) {
3759
                // deduplication of different files with the same rowset id
3760
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
3761
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
3762
51
                std::set<std::string> deleted_rowset_id;
3763
3764
51
                std::for_each(paths->begin(), paths->end(),
3765
51
                              [&metrics_context, &rowsets, &deleted_rowset_id,
3766
861k
                               this](const std::string& path) {
3767
861k
                                  std::vector<std::string> str;
3768
861k
                                  butil::SplitString(path, '/', &str);
3769
861k
                                  std::string rowset_id;
3770
861k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3771
857k
                                      rowset_id = str.back().substr(0, pos);
3772
857k
                                  } else {
3773
4.20k
                                      if (path.find("packed_file/") != std::string::npos) {
3774
0
                                          return; // packed files do not have rowset_id encoded
3775
0
                                      }
3776
4.20k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3777
4.20k
                                      return;
3778
4.20k
                                  }
3779
857k
                                  auto rs_meta = rowsets.find(rowset_id);
3780
857k
                                  if (rs_meta != rowsets.end() &&
3781
861k
                                      !deleted_rowset_id.contains(rowset_id)) {
3782
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
3783
54.1k
                                      metrics_context.total_recycled_data_size +=
3784
54.1k
                                              rs_meta->second.total_disk_size();
3785
54.1k
                                      segment_metrics_context_.total_recycled_num +=
3786
54.1k
                                              rs_meta->second.num_segments();
3787
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
3788
54.1k
                                              rs_meta->second.total_disk_size();
3789
54.1k
                                      metrics_context.total_recycled_num++;
3790
54.1k
                                  }
3791
857k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
3766
14
                               this](const std::string& path) {
3767
14
                                  std::vector<std::string> str;
3768
14
                                  butil::SplitString(path, '/', &str);
3769
14
                                  std::string rowset_id;
3770
14
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3771
14
                                      rowset_id = str.back().substr(0, pos);
3772
14
                                  } else {
3773
0
                                      if (path.find("packed_file/") != std::string::npos) {
3774
0
                                          return; // packed files do not have rowset_id encoded
3775
0
                                      }
3776
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3777
0
                                      return;
3778
0
                                  }
3779
14
                                  auto rs_meta = rowsets.find(rowset_id);
3780
14
                                  if (rs_meta != rowsets.end() &&
3781
14
                                      !deleted_rowset_id.contains(rowset_id)) {
3782
7
                                      deleted_rowset_id.emplace(rowset_id);
3783
7
                                      metrics_context.total_recycled_data_size +=
3784
7
                                              rs_meta->second.total_disk_size();
3785
7
                                      segment_metrics_context_.total_recycled_num +=
3786
7
                                              rs_meta->second.num_segments();
3787
7
                                      segment_metrics_context_.total_recycled_data_size +=
3788
7
                                              rs_meta->second.total_disk_size();
3789
7
                                      metrics_context.total_recycled_num++;
3790
7
                                  }
3791
14
                              });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
3766
861k
                               this](const std::string& path) {
3767
861k
                                  std::vector<std::string> str;
3768
861k
                                  butil::SplitString(path, '/', &str);
3769
861k
                                  std::string rowset_id;
3770
861k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3771
857k
                                      rowset_id = str.back().substr(0, pos);
3772
857k
                                  } else {
3773
4.20k
                                      if (path.find("packed_file/") != std::string::npos) {
3774
0
                                          return; // packed files do not have rowset_id encoded
3775
0
                                      }
3776
4.20k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3777
4.20k
                                      return;
3778
4.20k
                                  }
3779
857k
                                  auto rs_meta = rowsets.find(rowset_id);
3780
857k
                                  if (rs_meta != rowsets.end() &&
3781
861k
                                      !deleted_rowset_id.contains(rowset_id)) {
3782
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
3783
54.1k
                                      metrics_context.total_recycled_data_size +=
3784
54.1k
                                              rs_meta->second.total_disk_size();
3785
54.1k
                                      segment_metrics_context_.total_recycled_num +=
3786
54.1k
                                              rs_meta->second.num_segments();
3787
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
3788
54.1k
                                              rs_meta->second.total_disk_size();
3789
54.1k
                                      metrics_context.total_recycled_num++;
3790
54.1k
                                  }
3791
857k
                              });
3792
51
            }
3793
51
            return ret;
3794
51
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
3744
5
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
3745
5
            DCHECK(accessor_map_.count(*rid))
3746
0
                    << "uninitilized accessor, instance_id=" << instance_id_
3747
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
3748
5
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
3749
5
                                     &accessor_map_);
3750
5
            if (!accessor_map_.contains(*rid)) {
3751
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
3752
0
                        .tag("resource_id", resource_id)
3753
0
                        .tag("instance_id", instance_id_);
3754
0
                return -1;
3755
0
            }
3756
5
            auto& accessor = accessor_map_[*rid];
3757
5
            int ret = accessor->delete_files(*paths);
3758
5
            if (!ret) {
3759
                // deduplication of different files with the same rowset id
3760
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
3761
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
3762
5
                std::set<std::string> deleted_rowset_id;
3763
3764
5
                std::for_each(paths->begin(), paths->end(),
3765
5
                              [&metrics_context, &rowsets, &deleted_rowset_id,
3766
5
                               this](const std::string& path) {
3767
5
                                  std::vector<std::string> str;
3768
5
                                  butil::SplitString(path, '/', &str);
3769
5
                                  std::string rowset_id;
3770
5
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3771
5
                                      rowset_id = str.back().substr(0, pos);
3772
5
                                  } else {
3773
5
                                      if (path.find("packed_file/") != std::string::npos) {
3774
5
                                          return; // packed files do not have rowset_id encoded
3775
5
                                      }
3776
5
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3777
5
                                      return;
3778
5
                                  }
3779
5
                                  auto rs_meta = rowsets.find(rowset_id);
3780
5
                                  if (rs_meta != rowsets.end() &&
3781
5
                                      !deleted_rowset_id.contains(rowset_id)) {
3782
5
                                      deleted_rowset_id.emplace(rowset_id);
3783
5
                                      metrics_context.total_recycled_data_size +=
3784
5
                                              rs_meta->second.total_disk_size();
3785
5
                                      segment_metrics_context_.total_recycled_num +=
3786
5
                                              rs_meta->second.num_segments();
3787
5
                                      segment_metrics_context_.total_recycled_data_size +=
3788
5
                                              rs_meta->second.total_disk_size();
3789
5
                                      metrics_context.total_recycled_num++;
3790
5
                                  }
3791
5
                              });
3792
5
            }
3793
5
            return ret;
3794
5
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
3744
46
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
3745
46
            DCHECK(accessor_map_.count(*rid))
3746
0
                    << "uninitilized accessor, instance_id=" << instance_id_
3747
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
3748
46
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
3749
46
                                     &accessor_map_);
3750
46
            if (!accessor_map_.contains(*rid)) {
3751
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
3752
0
                        .tag("resource_id", resource_id)
3753
0
                        .tag("instance_id", instance_id_);
3754
0
                return -1;
3755
0
            }
3756
46
            auto& accessor = accessor_map_[*rid];
3757
46
            int ret = accessor->delete_files(*paths);
3758
46
            if (!ret) {
3759
                // deduplication of different files with the same rowset id
3760
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
3761
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
3762
46
                std::set<std::string> deleted_rowset_id;
3763
3764
46
                std::for_each(paths->begin(), paths->end(),
3765
46
                              [&metrics_context, &rowsets, &deleted_rowset_id,
3766
46
                               this](const std::string& path) {
3767
46
                                  std::vector<std::string> str;
3768
46
                                  butil::SplitString(path, '/', &str);
3769
46
                                  std::string rowset_id;
3770
46
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3771
46
                                      rowset_id = str.back().substr(0, pos);
3772
46
                                  } else {
3773
46
                                      if (path.find("packed_file/") != std::string::npos) {
3774
46
                                          return; // packed files do not have rowset_id encoded
3775
46
                                      }
3776
46
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3777
46
                                      return;
3778
46
                                  }
3779
46
                                  auto rs_meta = rowsets.find(rowset_id);
3780
46
                                  if (rs_meta != rowsets.end() &&
3781
46
                                      !deleted_rowset_id.contains(rowset_id)) {
3782
46
                                      deleted_rowset_id.emplace(rowset_id);
3783
46
                                      metrics_context.total_recycled_data_size +=
3784
46
                                              rs_meta->second.total_disk_size();
3785
46
                                      segment_metrics_context_.total_recycled_num +=
3786
46
                                              rs_meta->second.num_segments();
3787
46
                                      segment_metrics_context_.total_recycled_data_size +=
3788
46
                                              rs_meta->second.total_disk_size();
3789
46
                                      metrics_context.total_recycled_num++;
3790
46
                                  }
3791
46
                              });
3792
46
            }
3793
46
            return ret;
3794
46
        });
3795
51
    }
3796
98
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
3797
5
        LOG_INFO(
3798
5
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
3799
5
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
3800
5
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
3801
5
        concurrent_delete_executor.add([&]() -> int {
3802
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
3803
5
            if (!ret) {
3804
5
                auto rs = rowsets.at(rowset_id);
3805
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
3806
5
                metrics_context.total_recycled_num++;
3807
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
3808
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
3809
5
            }
3810
5
            return ret;
3811
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
3801
5
        concurrent_delete_executor.add([&]() -> int {
3802
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
3803
5
            if (!ret) {
3804
5
                auto rs = rowsets.at(rowset_id);
3805
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
3806
5
                metrics_context.total_recycled_num++;
3807
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
3808
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
3809
5
            }
3810
5
            return ret;
3811
5
        });
3812
5
    }
3813
3814
98
    bool finished = true;
3815
98
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
3816
98
    for (int r : rets) {
3817
56
        if (r != 0) {
3818
0
            ret = -1;
3819
0
            break;
3820
0
        }
3821
56
    }
3822
98
    ret = finished ? ret : -1;
3823
98
    return ret;
3824
98
}
3825
3826
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
3827
3.30k
                                         const std::string& rowset_id) {
3828
3.30k
    auto it = accessor_map_.find(resource_id);
3829
3.30k
    if (it == accessor_map_.end()) {
3830
400
        LOG_WARNING("instance has no such resource id")
3831
400
                .tag("instance_id", instance_id_)
3832
400
                .tag("resource_id", resource_id)
3833
400
                .tag("tablet_id", tablet_id)
3834
400
                .tag("rowset_id", rowset_id);
3835
400
        return -1;
3836
400
    }
3837
2.90k
    auto& accessor = it->second;
3838
2.90k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
3839
3.30k
}
3840
3841
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
3842
4
    if (key.empty()) {
3843
0
        return false;
3844
0
    }
3845
4
    std::string_view key_view = key;
3846
4
    key_view.remove_prefix(1); // remove keyspace prefix
3847
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
3848
4
    if (decode_key(&key_view, &decoded) != 0) {
3849
0
        return false;
3850
0
    }
3851
4
    if (decoded.size() < 4) {
3852
0
        return false;
3853
0
    }
3854
4
    try {
3855
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
3856
4
    } catch (const std::bad_variant_access&) {
3857
0
        return false;
3858
0
    }
3859
4
    return true;
3860
4
}
3861
3862
14
int InstanceRecycler::recycle_packed_files() {
3863
14
    const std::string task_name = "recycle_packed_files";
3864
14
    auto start_tp = steady_clock::now();
3865
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
3866
14
    int ret = 0;
3867
14
    PackedFileRecycleStats stats;
3868
3869
14
    register_recycle_task(task_name, start_time);
3870
14
    DORIS_CLOUD_DEFER {
3871
14
        unregister_recycle_task(task_name);
3872
14
        int64_t cost =
3873
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3874
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
3875
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
3876
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
3877
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
3878
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
3879
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
3880
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
3881
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
3882
14
                                                             stats.bytes_object_deleted);
3883
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
3884
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
3885
14
                .tag("instance_id", instance_id_)
3886
14
                .tag("num_scanned", stats.num_scanned)
3887
14
                .tag("num_corrected", stats.num_corrected)
3888
14
                .tag("num_deleted", stats.num_deleted)
3889
14
                .tag("num_failed", stats.num_failed)
3890
14
                .tag("num_objects_deleted", stats.num_object_deleted)
3891
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
3892
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
3893
14
                .tag("bytes_deleted", stats.bytes_deleted)
3894
14
                .tag("ret", ret);
3895
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
3870
14
    DORIS_CLOUD_DEFER {
3871
14
        unregister_recycle_task(task_name);
3872
14
        int64_t cost =
3873
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3874
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
3875
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
3876
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
3877
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
3878
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
3879
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
3880
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
3881
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
3882
14
                                                             stats.bytes_object_deleted);
3883
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
3884
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
3885
14
                .tag("instance_id", instance_id_)
3886
14
                .tag("num_scanned", stats.num_scanned)
3887
14
                .tag("num_corrected", stats.num_corrected)
3888
14
                .tag("num_deleted", stats.num_deleted)
3889
14
                .tag("num_failed", stats.num_failed)
3890
14
                .tag("num_objects_deleted", stats.num_object_deleted)
3891
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
3892
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
3893
14
                .tag("bytes_deleted", stats.bytes_deleted)
3894
14
                .tag("ret", ret);
3895
14
    };
3896
3897
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
3898
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
3899
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
3900
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
3897
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
3898
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
3899
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
3900
4
    };
3901
3902
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
3903
3904
14
    std::string begin = packed_file_key({instance_id_, ""});
3905
14
    std::string end = packed_file_key({instance_id_, "\xff"});
3906
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
3907
0
        ret = -1;
3908
0
    }
3909
3910
14
    return ret;
3911
14
}
3912
3913
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
3914
                                                  RecyclerMetricsContext& metrics_context,
3915
0
                                                  int64_t partition_id, bool is_empty_tablet) {
3916
0
    std::string tablet_key_begin, tablet_key_end;
3917
3918
0
    if (partition_id > 0) {
3919
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
3920
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
3921
0
    } else {
3922
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
3923
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
3924
0
    }
3925
    // for calculate the total num or bytes of recyled objects
3926
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
3927
0
                                                          std::string_view v) -> int {
3928
0
        doris::TabletMetaCloudPB tablet_meta_pb;
3929
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3930
0
            return 0;
3931
0
        }
3932
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3933
3934
0
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3935
0
            return 0;
3936
0
        }
3937
3938
0
        if (!is_empty_tablet) {
3939
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
3940
0
                return 0;
3941
0
            }
3942
0
            tablet_metrics_context_.total_need_recycle_num++;
3943
0
        }
3944
0
        return 0;
3945
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_
3946
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
3947
0
    metrics_context.report(true);
3948
0
    tablet_metrics_context_.report(true);
3949
0
    segment_metrics_context_.report(true);
3950
0
    return ret;
3951
0
}
3952
3953
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
3954
0
                                                 RecyclerMetricsContext& metrics_context) {
3955
0
    int ret = 0;
3956
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
3957
0
    std::unique_ptr<Transaction> txn;
3958
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3959
0
        LOG_WARNING("failed to recycle tablet ")
3960
0
                .tag("tablet id", tablet_id)
3961
0
                .tag("instance_id", instance_id_)
3962
0
                .tag("reason", "failed to create txn");
3963
0
        ret = -1;
3964
0
    }
3965
0
    GetRowsetResponse resp;
3966
0
    std::string msg;
3967
0
    MetaServiceCode code = MetaServiceCode::OK;
3968
    // get rowsets in tablet
3969
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
3970
0
                        tablet_id, code, msg, &resp);
3971
0
    if (code != MetaServiceCode::OK) {
3972
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
3973
0
                .tag("tablet id", tablet_id)
3974
0
                .tag("msg", msg)
3975
0
                .tag("code", code)
3976
0
                .tag("instance id", instance_id_);
3977
0
        ret = -1;
3978
0
    }
3979
0
    for (const auto& rs_meta : resp.rowset_meta()) {
3980
        /*
3981
        * For compatibility, we skip the loop for [0-1] here.
3982
        * The purpose of this loop is to delete object files,
3983
        * and since [0-1] only has meta and doesn't have object files,
3984
        * skipping it doesn't affect system correctness.
3985
        *
3986
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
3987
        * would return error -1 directly, causing the recycle operation to fail.
3988
        *
3989
        * [0-1] doesn't have resource id is a bug.
3990
        * In the future, we will fix this problem, after that,
3991
        * we can remove this if statement.
3992
        *
3993
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
3994
        */
3995
3996
0
        if (rs_meta.end_version() == 1) {
3997
            // Assert that [0-1] has no resource_id to make sure
3998
            // this if statement will not be forgetted to remove
3999
            // when the resource id bug is fixed
4000
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4001
0
            continue;
4002
0
        }
4003
0
        if (!rs_meta.has_resource_id()) {
4004
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4005
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4006
0
                    .tag("instance_id", instance_id_)
4007
0
                    .tag("tablet_id", tablet_id);
4008
0
            continue;
4009
0
        }
4010
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4011
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4012
        // possible if the accessor is not initilized correctly
4013
0
        if (it == accessor_map_.end()) [[unlikely]] {
4014
0
            LOG_WARNING(
4015
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4016
0
                    "recycle process")
4017
0
                    .tag("tablet id", tablet_id)
4018
0
                    .tag("instance_id", instance_id_)
4019
0
                    .tag("resource_id", rs_meta.resource_id())
4020
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4021
0
            continue;
4022
0
        }
4023
4024
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
4025
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4026
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4027
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
4028
0
    }
4029
0
    return ret;
4030
0
}
4031
4032
4.25k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
4033
4.25k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
4034
4.25k
            .tag("instance_id", instance_id_)
4035
4.25k
            .tag("tablet_id", tablet_id);
4036
4037
4.25k
    if (should_recycle_versioned_keys()) {
4038
11
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
4039
11
        if (ret != 0) {
4040
0
            return ret;
4041
0
        }
4042
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
4043
        // during the recycle_versioned_tablet process.
4044
        //
4045
        // .. And remove restore job rowsets of this tablet too
4046
11
    }
4047
4048
4.25k
    int ret = 0;
4049
4.25k
    auto start_time = steady_clock::now();
4050
4051
4.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4052
4053
    // collect resource ids
4054
248
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4055
248
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4056
248
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4057
248
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4058
248
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
4059
248
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
4060
4061
248
    std::set<std::string> resource_ids;
4062
248
    int64_t recycle_rowsets_number = 0;
4063
248
    int64_t recycle_segments_number = 0;
4064
248
    int64_t recycle_rowsets_data_size = 0;
4065
248
    int64_t recycle_rowsets_index_size = 0;
4066
248
    int64_t recycle_restore_job_rowsets_number = 0;
4067
248
    int64_t recycle_restore_job_segments_number = 0;
4068
248
    int64_t recycle_restore_job_rowsets_data_size = 0;
4069
248
    int64_t recycle_restore_job_rowsets_index_size = 0;
4070
248
    int64_t max_rowset_version = 0;
4071
248
    int64_t min_rowset_creation_time = INT64_MAX;
4072
248
    int64_t max_rowset_creation_time = 0;
4073
248
    int64_t min_rowset_expiration_time = INT64_MAX;
4074
248
    int64_t max_rowset_expiration_time = 0;
4075
4076
248
    DORIS_CLOUD_DEFER {
4077
248
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4078
248
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4079
248
                .tag("instance_id", instance_id_)
4080
248
                .tag("tablet_id", tablet_id)
4081
248
                .tag("recycle rowsets number", recycle_rowsets_number)
4082
248
                .tag("recycle segments number", recycle_segments_number)
4083
248
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4084
248
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4085
248
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4086
248
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4087
248
                .tag("all restore job rowsets recycle data size",
4088
248
                     recycle_restore_job_rowsets_data_size)
4089
248
                .tag("all restore job rowsets recycle index size",
4090
248
                     recycle_restore_job_rowsets_index_size)
4091
248
                .tag("max rowset version", max_rowset_version)
4092
248
                .tag("min rowset creation time", min_rowset_creation_time)
4093
248
                .tag("max rowset creation time", max_rowset_creation_time)
4094
248
                .tag("min rowset expiration time", min_rowset_expiration_time)
4095
248
                .tag("max rowset expiration time", max_rowset_expiration_time)
4096
248
                .tag("task type", metrics_context.operation_type)
4097
248
                .tag("ret", ret);
4098
248
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4076
248
    DORIS_CLOUD_DEFER {
4077
248
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4078
248
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4079
248
                .tag("instance_id", instance_id_)
4080
248
                .tag("tablet_id", tablet_id)
4081
248
                .tag("recycle rowsets number", recycle_rowsets_number)
4082
248
                .tag("recycle segments number", recycle_segments_number)
4083
248
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4084
248
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4085
248
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4086
248
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4087
248
                .tag("all restore job rowsets recycle data size",
4088
248
                     recycle_restore_job_rowsets_data_size)
4089
248
                .tag("all restore job rowsets recycle index size",
4090
248
                     recycle_restore_job_rowsets_index_size)
4091
248
                .tag("max rowset version", max_rowset_version)
4092
248
                .tag("min rowset creation time", min_rowset_creation_time)
4093
248
                .tag("max rowset creation time", max_rowset_creation_time)
4094
248
                .tag("min rowset expiration time", min_rowset_expiration_time)
4095
248
                .tag("max rowset expiration time", max_rowset_expiration_time)
4096
248
                .tag("task type", metrics_context.operation_type)
4097
248
                .tag("ret", ret);
4098
248
    };
4099
4100
248
    std::unique_ptr<Transaction> txn;
4101
248
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4102
0
        LOG_WARNING("failed to recycle tablet ")
4103
0
                .tag("tablet id", tablet_id)
4104
0
                .tag("instance_id", instance_id_)
4105
0
                .tag("reason", "failed to create txn");
4106
0
        ret = -1;
4107
0
    }
4108
248
    GetRowsetResponse resp;
4109
248
    std::string msg;
4110
248
    MetaServiceCode code = MetaServiceCode::OK;
4111
    // get rowsets in tablet
4112
248
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4113
248
                        tablet_id, code, msg, &resp);
4114
248
    if (code != MetaServiceCode::OK) {
4115
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4116
0
                .tag("tablet id", tablet_id)
4117
0
                .tag("msg", msg)
4118
0
                .tag("code", code)
4119
0
                .tag("instance id", instance_id_);
4120
0
        ret = -1;
4121
0
    }
4122
248
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
4123
4124
2.51k
    for (const auto& rs_meta : resp.rowset_meta()) {
4125
        // The rowset has no resource id and segments when it was generated by compaction
4126
        // with multiple hole rowsets or it's version is [0-1], so we can skip it.
4127
2.51k
        if (!rs_meta.has_resource_id() && rs_meta.num_segments() == 0) {
4128
0
            LOG_INFO("rowset meta does not have a resource id and no segments, skip this rowset")
4129
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4130
0
                    .tag("instance_id", instance_id_)
4131
0
                    .tag("tablet_id", tablet_id);
4132
0
            recycle_rowsets_number += 1;
4133
0
            continue;
4134
0
        }
4135
2.51k
        if (!rs_meta.has_resource_id()) {
4136
1
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4137
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
4138
1
                    .tag("instance_id", instance_id_)
4139
1
                    .tag("tablet_id", tablet_id);
4140
1
            return -1;
4141
1
        }
4142
2.51k
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4143
2.51k
        auto it = accessor_map_.find(rs_meta.resource_id());
4144
        // possible if the accessor is not initilized correctly
4145
2.51k
        if (it == accessor_map_.end()) [[unlikely]] {
4146
1
            LOG_WARNING(
4147
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4148
1
                    "recycle process")
4149
1
                    .tag("tablet id", tablet_id)
4150
1
                    .tag("instance_id", instance_id_)
4151
1
                    .tag("resource_id", rs_meta.resource_id())
4152
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4153
1
            return -1;
4154
1
        }
4155
2.51k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4156
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
4157
0
                    .tag("instance_id", instance_id_)
4158
0
                    .tag("tablet_id", tablet_id)
4159
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4160
0
            return -1;
4161
0
        }
4162
2.51k
        recycle_rowsets_number += 1;
4163
2.51k
        recycle_segments_number += rs_meta.num_segments();
4164
2.51k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4165
2.51k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4166
2.51k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4167
2.51k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4168
2.51k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4169
2.51k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4170
2.51k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4171
2.51k
        resource_ids.emplace(rs_meta.resource_id());
4172
2.51k
    }
4173
4174
    // get restore job rowset in tablet
4175
246
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
4176
246
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
4177
246
    if (code != MetaServiceCode::OK) {
4178
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
4179
0
                .tag("tablet id", tablet_id)
4180
0
                .tag("msg", msg)
4181
0
                .tag("code", code)
4182
0
                .tag("instance id", instance_id_);
4183
0
        return -1;
4184
0
    }
4185
4186
246
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
4187
0
        if (!rs_meta.has_resource_id()) {
4188
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4189
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4190
0
                    .tag("instance_id", instance_id_)
4191
0
                    .tag("tablet_id", tablet_id);
4192
0
            return -1;
4193
0
        }
4194
4195
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4196
        // possible if the accessor is not initilized correctly
4197
0
        if (it == accessor_map_.end()) [[unlikely]] {
4198
0
            LOG_WARNING(
4199
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4200
0
                    "recycle process")
4201
0
                    .tag("tablet id", tablet_id)
4202
0
                    .tag("instance_id", instance_id_)
4203
0
                    .tag("resource_id", rs_meta.resource_id())
4204
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4205
0
            return -1;
4206
0
        }
4207
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4208
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
4209
0
                    .tag("instance_id", instance_id_)
4210
0
                    .tag("tablet_id", tablet_id)
4211
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4212
0
            return -1;
4213
0
        }
4214
0
        recycle_restore_job_rowsets_number += 1;
4215
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
4216
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
4217
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
4218
0
        resource_ids.emplace(rs_meta.resource_id());
4219
0
    }
4220
4221
246
    LOG_INFO("recycle tablet start to delete object")
4222
246
            .tag("instance id", instance_id_)
4223
246
            .tag("tablet id", tablet_id)
4224
246
            .tag("recycle tablet resource ids are",
4225
246
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
4226
246
                                 [](std::string rs_id, const auto& it) {
4227
206
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4228
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
4226
206
                                 [](std::string rs_id, const auto& it) {
4227
206
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4228
206
                                 }));
4229
4230
246
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
4231
246
            _thread_pool_group.s3_producer_pool,
4232
246
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4233
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
4233
206
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
4234
4235
    // delete all rowset data in this tablet
4236
    // ATTN: there may be data leak if not all accessor initilized successfully
4237
    //       partial data deleted if the tablet is stored cross-storage vault
4238
    //       vault id is not attached to TabletMeta...
4239
246
    for (const auto& resource_id : resource_ids) {
4240
206
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
4241
206
        concurrent_delete_executor.add(
4242
206
                [&, rs_id = resource_id,
4243
206
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4244
206
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4245
206
                    if (res != 0) {
4246
2
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4247
2
                                     << " path=" << accessor_ptr->uri()
4248
2
                                     << " task type=" << metrics_context.operation_type;
4249
2
                        return std::make_pair(-1, rs_id);
4250
2
                    }
4251
204
                    return std::make_pair(0, rs_id);
4252
206
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
4243
206
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4244
206
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4245
206
                    if (res != 0) {
4246
2
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4247
2
                                     << " path=" << accessor_ptr->uri()
4248
2
                                     << " task type=" << metrics_context.operation_type;
4249
2
                        return std::make_pair(-1, rs_id);
4250
2
                    }
4251
204
                    return std::make_pair(0, rs_id);
4252
206
                });
4253
206
    }
4254
4255
246
    bool finished = true;
4256
246
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
4257
246
    for (auto& r : rets) {
4258
206
        if (r.first != 0) {
4259
2
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
4260
2
            ret = -1;
4261
2
        }
4262
206
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
4263
206
    }
4264
246
    ret = finished ? ret : -1;
4265
4266
246
    if (ret != 0) { // failed recycle tablet data
4267
2
        LOG_WARNING("ret!=0")
4268
2
                .tag("finished", finished)
4269
2
                .tag("ret", ret)
4270
2
                .tag("instance_id", instance_id_)
4271
2
                .tag("tablet_id", tablet_id);
4272
2
        return ret;
4273
2
    }
4274
4275
244
    tablet_metrics_context_.total_recycled_data_size +=
4276
244
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4277
244
    tablet_metrics_context_.total_recycled_num += 1;
4278
244
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
4279
244
    segment_metrics_context_.total_recycled_data_size +=
4280
244
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4281
244
    metrics_context.total_recycled_data_size +=
4282
244
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4283
244
    tablet_metrics_context_.report();
4284
244
    segment_metrics_context_.report();
4285
244
    metrics_context.report();
4286
4287
244
    txn.reset();
4288
244
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4289
0
        LOG_WARNING("failed to recycle tablet ")
4290
0
                .tag("tablet id", tablet_id)
4291
0
                .tag("instance_id", instance_id_)
4292
0
                .tag("reason", "failed to create txn");
4293
0
        ret = -1;
4294
0
    }
4295
    // delete all rowset kv in this tablet
4296
244
    txn->remove(rs_key0, rs_key1);
4297
244
    txn->remove(recyc_rs_key0, recyc_rs_key1);
4298
244
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
4299
4300
    // remove delete bitmap for MoW table
4301
244
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
4302
244
    txn->remove(pending_key);
4303
244
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
4304
244
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
4305
244
    txn->remove(delete_bitmap_start, delete_bitmap_end);
4306
4307
244
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
4308
244
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
4309
244
    txn->remove(dbm_start_key, dbm_end_key);
4310
244
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
4311
244
              << " end=" << hex(dbm_end_key);
4312
4313
244
    TxnErrorCode err = txn->commit();
4314
244
    if (err != TxnErrorCode::TXN_OK) {
4315
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
4316
0
        ret = -1;
4317
0
    }
4318
4319
244
    if (ret == 0) {
4320
        // All object files under tablet have been deleted
4321
244
        std::lock_guard lock(recycled_tablets_mtx_);
4322
244
        recycled_tablets_.insert(tablet_id);
4323
244
    }
4324
4325
244
    return ret;
4326
246
}
4327
4328
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
4329
11
                                               RecyclerMetricsContext& metrics_context) {
4330
11
    int ret = 0;
4331
11
    auto start_time = steady_clock::now();
4332
4333
11
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4334
4335
    // collect resource ids
4336
11
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4337
11
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4338
11
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4339
11
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4340
4341
11
    int64_t recycle_rowsets_number = 0;
4342
11
    int64_t recycle_segments_number = 0;
4343
11
    int64_t recycle_rowsets_data_size = 0;
4344
11
    int64_t recycle_rowsets_index_size = 0;
4345
11
    int64_t max_rowset_version = 0;
4346
11
    int64_t min_rowset_creation_time = INT64_MAX;
4347
11
    int64_t max_rowset_creation_time = 0;
4348
11
    int64_t min_rowset_expiration_time = INT64_MAX;
4349
11
    int64_t max_rowset_expiration_time = 0;
4350
4351
11
    DORIS_CLOUD_DEFER {
4352
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4353
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4354
11
                .tag("instance_id", instance_id_)
4355
11
                .tag("tablet_id", tablet_id)
4356
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4357
11
                .tag("recycle segments number", recycle_segments_number)
4358
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4359
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4360
11
                .tag("max rowset version", max_rowset_version)
4361
11
                .tag("min rowset creation time", min_rowset_creation_time)
4362
11
                .tag("max rowset creation time", max_rowset_creation_time)
4363
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4364
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4365
11
                .tag("ret", ret);
4366
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4351
11
    DORIS_CLOUD_DEFER {
4352
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4353
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4354
11
                .tag("instance_id", instance_id_)
4355
11
                .tag("tablet_id", tablet_id)
4356
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4357
11
                .tag("recycle segments number", recycle_segments_number)
4358
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4359
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4360
11
                .tag("max rowset version", max_rowset_version)
4361
11
                .tag("min rowset creation time", min_rowset_creation_time)
4362
11
                .tag("max rowset creation time", max_rowset_creation_time)
4363
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4364
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4365
11
                .tag("ret", ret);
4366
11
    };
4367
4368
11
    std::unique_ptr<Transaction> txn;
4369
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4370
0
        LOG_WARNING("failed to recycle tablet ")
4371
0
                .tag("tablet id", tablet_id)
4372
0
                .tag("instance_id", instance_id_)
4373
0
                .tag("reason", "failed to create txn");
4374
0
        ret = -1;
4375
0
    }
4376
4377
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
4378
    // by the related operation logs.
4379
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
4380
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
4381
11
    MetaReader meta_reader(instance_id_);
4382
11
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
4383
11
    if (err == TxnErrorCode::TXN_OK) {
4384
11
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
4385
11
    }
4386
11
    if (err != TxnErrorCode::TXN_OK) {
4387
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4388
0
                .tag("tablet id", tablet_id)
4389
0
                .tag("err", err)
4390
0
                .tag("instance id", instance_id_);
4391
0
        ret = -1;
4392
0
    }
4393
4394
11
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
4395
11
             load_rowset_metas.size(), compact_rowset_metas.size())
4396
11
            .tag("instance_id", instance_id_)
4397
11
            .tag("tablet_id", tablet_id);
4398
4399
11
    SyncExecutor<int> concurrent_delete_executor(
4400
11
            _thread_pool_group.s3_producer_pool,
4401
11
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4402
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
4403
4404
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
4405
60
        recycle_rowsets_number += 1;
4406
60
        recycle_segments_number += rs_meta.num_segments();
4407
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4408
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4409
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4410
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4411
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4412
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4413
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4414
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
4404
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
4405
60
        recycle_rowsets_number += 1;
4406
60
        recycle_segments_number += rs_meta.num_segments();
4407
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4408
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4409
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4410
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4411
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4412
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4413
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4414
60
    };
4415
4416
11
    std::vector<RowsetDeleteTask> all_tasks;
4417
60
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
4418
60
        update_rowset_stats(rs_meta);
4419
        // Version 0-1 rowset has no resource_id and no actual data files,
4420
        // but still needs ref_count key cleanup, so we add it to all_tasks.
4421
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
4422
60
        RowsetDeleteTask task;
4423
60
        task.rowset_meta = rs_meta;
4424
60
        task.versioned_rowset_key =
4425
60
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
4426
60
        task.non_versioned_rowset_key =
4427
60
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
4428
60
        task.versionstamp = versionstamp;
4429
60
        all_tasks.push_back(std::move(task));
4430
60
    }
4431
4432
11
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
4433
0
        update_rowset_stats(rs_meta);
4434
        // Version 0-1 rowset has no resource_id and no actual data files,
4435
        // but still needs ref_count key cleanup, so we add it to all_tasks.
4436
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
4437
0
        RowsetDeleteTask task;
4438
0
        task.rowset_meta = rs_meta;
4439
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
4440
0
                {instance_id_, tablet_id, rs_meta.end_version()});
4441
0
        task.non_versioned_rowset_key =
4442
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
4443
0
        task.versionstamp = versionstamp;
4444
0
        all_tasks.push_back(std::move(task));
4445
0
    }
4446
4447
11
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
4448
0
        RecycleRowsetPB recycle_rowset;
4449
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
4450
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4451
0
            return -1;
4452
0
        }
4453
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
4454
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
4455
                // in old version, keep this key-value pair and it needs to be checked manually
4456
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4457
0
                return -1;
4458
0
            }
4459
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
4460
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
4461
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
4462
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
4463
0
                return -1;
4464
0
            }
4465
            // decode rowset_id
4466
0
            auto k1 = k;
4467
0
            k1.remove_prefix(1);
4468
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
4469
0
            decode_key(&k1, &out);
4470
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
4471
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
4472
0
            LOG_INFO("delete old-version rowset data")
4473
0
                    .tag("instance_id", instance_id_)
4474
0
                    .tag("tablet_id", tablet_id)
4475
0
                    .tag("rowset_id", rowset_id);
4476
4477
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
4478
            // so we must use prefix deletion directly instead of batch delete.
4479
0
            concurrent_delete_executor.add(
4480
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
4481
                        // delete by prefix, the recycle rowset key will be deleted by range later.
4482
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
4483
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
4484
0
        } else {
4485
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
4486
            // Version 0-1 rowset has no resource_id and no actual data files,
4487
            // but still needs ref_count key cleanup, so we add it to all_tasks.
4488
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
4489
0
            RowsetDeleteTask task;
4490
0
            task.rowset_meta = rowset_meta;
4491
0
            task.recycle_rowset_key = k;
4492
0
            all_tasks.push_back(std::move(task));
4493
0
        }
4494
0
        return 0;
4495
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_
4496
4497
11
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
4498
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
4499
0
                .tag("tablet id", tablet_id)
4500
0
                .tag("instance_id", instance_id_)
4501
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
4502
0
        ret = -1;
4503
0
    }
4504
4505
    // Phase 1: Classify tasks by ref_count
4506
11
    std::vector<RowsetDeleteTask> batch_delete_tasks;
4507
60
    for (auto& task : all_tasks) {
4508
60
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
4509
60
        if (classify_ret < 0) {
4510
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
4511
0
                    .tag("instance_id", instance_id_)
4512
0
                    .tag("tablet_id", tablet_id)
4513
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
4514
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
4515
0
                return recycle_rowset_meta_and_data(t);
4516
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_4clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_4clEv
4517
0
        }
4518
60
    }
4519
4520
11
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
4521
4522
11
    LOG_INFO("batch delete plan created")
4523
11
            .tag("instance_id", instance_id_)
4524
11
            .tag("tablet_id", tablet_id)
4525
11
            .tag("plan_count", batch_delete_tasks.size());
4526
4527
    // Phase 2: Execute batch delete using existing delete_rowset_data
4528
11
    if (!batch_delete_tasks.empty()) {
4529
10
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
4530
49
        for (const auto& task : batch_delete_tasks) {
4531
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
4532
49
            if (task.rowset_meta.resource_id().empty()) {
4533
10
                LOG_INFO("skip rowset with empty resource_id in batch delete")
4534
10
                        .tag("instance_id", instance_id_)
4535
10
                        .tag("tablet_id", tablet_id)
4536
10
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
4537
10
                continue;
4538
10
            }
4539
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
4540
39
        }
4541
4542
        // Only call delete_rowset_data if there are rowsets with actual data to delete
4543
10
        bool delete_success = true;
4544
10
        if (!rowsets_to_delete.empty()) {
4545
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
4546
9
                                                         "batch_delete_versioned_tablet");
4547
9
            int delete_ret = delete_rowset_data(
4548
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
4549
9
            if (delete_ret != 0) {
4550
0
                LOG_WARNING("batch delete execution failed")
4551
0
                        .tag("instance_id", instance_id_)
4552
0
                        .tag("tablet_id", tablet_id);
4553
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
4554
0
                ret = -1;
4555
0
                delete_success = false;
4556
0
            }
4557
9
        }
4558
4559
        // Phase 3: Only cleanup metadata if data deletion succeeded.
4560
        // If deletion failed, keep recycle_rowset_key so next round will retry.
4561
10
        if (delete_success) {
4562
10
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
4563
10
            if (cleanup_ret != 0) {
4564
0
                LOG_WARNING("batch delete cleanup failed")
4565
0
                        .tag("instance_id", instance_id_)
4566
0
                        .tag("tablet_id", tablet_id);
4567
0
                ret = -1;
4568
0
            }
4569
10
        }
4570
10
    }
4571
4572
    // Always wait for fallback tasks to complete before returning
4573
11
    bool finished = true;
4574
11
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4575
11
    for (int r : rets) {
4576
0
        if (r != 0) {
4577
0
            ret = -1;
4578
0
        }
4579
0
    }
4580
4581
11
    ret = finished ? ret : -1;
4582
4583
11
    if (ret != 0) { // failed recycle tablet data
4584
0
        LOG_WARNING("recycle versioned tablet failed")
4585
0
                .tag("finished", finished)
4586
0
                .tag("ret", ret)
4587
0
                .tag("instance_id", instance_id_)
4588
0
                .tag("tablet_id", tablet_id);
4589
0
        return ret;
4590
0
    }
4591
4592
11
    tablet_metrics_context_.total_recycled_data_size +=
4593
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4594
11
    tablet_metrics_context_.total_recycled_num += 1;
4595
11
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
4596
11
    segment_metrics_context_.total_recycled_data_size +=
4597
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4598
11
    metrics_context.total_recycled_data_size +=
4599
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4600
11
    tablet_metrics_context_.report();
4601
11
    segment_metrics_context_.report();
4602
11
    metrics_context.report();
4603
4604
11
    txn.reset();
4605
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4606
0
        LOG_WARNING("failed to recycle tablet ")
4607
0
                .tag("tablet id", tablet_id)
4608
0
                .tag("instance_id", instance_id_)
4609
0
                .tag("reason", "failed to create txn");
4610
0
        ret = -1;
4611
0
    }
4612
    // delete all rowset kv in this tablet
4613
11
    txn->remove(rs_key0, rs_key1);
4614
11
    txn->remove(recyc_rs_key0, recyc_rs_key1);
4615
4616
    // remove delete bitmap for MoW table
4617
11
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
4618
11
    txn->remove(pending_key);
4619
11
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
4620
11
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
4621
11
    txn->remove(delete_bitmap_start, delete_bitmap_end);
4622
4623
11
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
4624
11
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
4625
11
    txn->remove(dbm_start_key, dbm_end_key);
4626
11
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
4627
11
              << " end=" << hex(dbm_end_key);
4628
4629
11
    std::string versioned_idx_key = versioned::tablet_index_key({instance_id_, tablet_id});
4630
11
    std::string tablet_index_val;
4631
11
    err = txn->get(versioned_idx_key, &tablet_index_val);
4632
11
    if (err != TxnErrorCode::TXN_KEY_NOT_FOUND && err != TxnErrorCode::TXN_OK) {
4633
0
        LOG_WARNING("failed to get tablet index kv")
4634
0
                .tag("instance_id", instance_id_)
4635
0
                .tag("tablet_id", tablet_id)
4636
0
                .tag("err", err);
4637
0
        ret = -1;
4638
11
    } else if (err == TxnErrorCode::TXN_OK) {
4639
        // If the tablet index kv exists, we need to delete it
4640
10
        TabletIndexPB tablet_index_pb;
4641
10
        if (!tablet_index_pb.ParseFromString(tablet_index_val)) {
4642
0
            LOG_WARNING("failed to parse tablet index pb")
4643
0
                    .tag("instance_id", instance_id_)
4644
0
                    .tag("tablet_id", tablet_id);
4645
0
            ret = -1;
4646
10
        } else {
4647
10
            std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
4648
10
                    {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
4649
10
                     tablet_index_pb.index_id(), tablet_index_pb.partition_id(), tablet_id});
4650
10
            txn->remove(versioned_inverted_idx_key);
4651
10
            txn->remove(versioned_idx_key);
4652
10
        }
4653
10
    }
4654
4655
11
    err = txn->commit();
4656
11
    if (err != TxnErrorCode::TXN_OK) {
4657
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
4658
0
        ret = -1;
4659
0
    }
4660
4661
11
    if (ret == 0) {
4662
        // All object files under tablet have been deleted
4663
11
        std::lock_guard lock(recycled_tablets_mtx_);
4664
11
        recycled_tablets_.insert(tablet_id);
4665
11
    }
4666
4667
11
    return ret;
4668
11
}
4669
4670
27
int InstanceRecycler::recycle_rowsets() {
4671
27
    if (should_recycle_versioned_keys()) {
4672
5
        return recycle_versioned_rowsets();
4673
5
    }
4674
4675
22
    const std::string task_name = "recycle_rowsets";
4676
22
    int64_t num_scanned = 0;
4677
22
    int64_t num_expired = 0;
4678
22
    int64_t num_prepare = 0;
4679
22
    int64_t num_compacted = 0;
4680
22
    int64_t num_empty_rowset = 0;
4681
22
    size_t total_rowset_key_size = 0;
4682
22
    size_t total_rowset_value_size = 0;
4683
22
    size_t expired_rowset_size = 0;
4684
22
    std::atomic_long num_recycled = 0;
4685
22
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
4686
4687
22
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
4688
22
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
4689
22
    std::string recyc_rs_key0;
4690
22
    std::string recyc_rs_key1;
4691
22
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
4692
22
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
4693
4694
22
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
4695
4696
22
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
4697
22
    register_recycle_task(task_name, start_time);
4698
4699
22
    DORIS_CLOUD_DEFER {
4700
22
        unregister_recycle_task(task_name);
4701
22
        int64_t cost =
4702
22
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4703
22
        metrics_context.finish_report();
4704
22
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
4705
22
                .tag("instance_id", instance_id_)
4706
22
                .tag("num_scanned", num_scanned)
4707
22
                .tag("num_expired", num_expired)
4708
22
                .tag("num_recycled", num_recycled)
4709
22
                .tag("num_recycled.prepare", num_prepare)
4710
22
                .tag("num_recycled.compacted", num_compacted)
4711
22
                .tag("num_recycled.empty_rowset", num_empty_rowset)
4712
22
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
4713
22
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
4714
22
                .tag("expired_rowset_meta_size", expired_rowset_size);
4715
22
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
4699
7
    DORIS_CLOUD_DEFER {
4700
7
        unregister_recycle_task(task_name);
4701
7
        int64_t cost =
4702
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4703
7
        metrics_context.finish_report();
4704
7
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
4705
7
                .tag("instance_id", instance_id_)
4706
7
                .tag("num_scanned", num_scanned)
4707
7
                .tag("num_expired", num_expired)
4708
7
                .tag("num_recycled", num_recycled)
4709
7
                .tag("num_recycled.prepare", num_prepare)
4710
7
                .tag("num_recycled.compacted", num_compacted)
4711
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
4712
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
4713
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
4714
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
4715
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
4699
15
    DORIS_CLOUD_DEFER {
4700
15
        unregister_recycle_task(task_name);
4701
15
        int64_t cost =
4702
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4703
15
        metrics_context.finish_report();
4704
15
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
4705
15
                .tag("instance_id", instance_id_)
4706
15
                .tag("num_scanned", num_scanned)
4707
15
                .tag("num_expired", num_expired)
4708
15
                .tag("num_recycled", num_recycled)
4709
15
                .tag("num_recycled.prepare", num_prepare)
4710
15
                .tag("num_recycled.compacted", num_compacted)
4711
15
                .tag("num_recycled.empty_rowset", num_empty_rowset)
4712
15
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
4713
15
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
4714
15
                .tag("expired_rowset_meta_size", expired_rowset_size);
4715
15
    };
4716
4717
22
    std::vector<std::string> rowset_keys;
4718
    // rowset_id -> rowset_meta
4719
    // store rowset id and meta for statistics rs size when delete
4720
22
    std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
4721
4722
    // Store keys of rowset recycled by background workers
4723
22
    std::mutex async_recycled_rowset_keys_mutex;
4724
22
    std::vector<std::string> async_recycled_rowset_keys;
4725
22
    auto worker_pool = std::make_unique<SimpleThreadPool>(
4726
22
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
4727
22
    worker_pool->start();
4728
    // TODO bacth delete
4729
4.00k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
4730
4.00k
        std::string dbm_start_key =
4731
4.00k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4732
4.00k
        std::string dbm_end_key = dbm_start_key;
4733
4.00k
        encode_int64(INT64_MAX, &dbm_end_key);
4734
4.00k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4735
4.00k
        if (ret != 0) {
4736
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
4737
0
                         << instance_id_;
4738
0
        }
4739
4.00k
        return ret;
4740
4.00k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
4729
2
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
4730
2
        std::string dbm_start_key =
4731
2
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4732
2
        std::string dbm_end_key = dbm_start_key;
4733
2
        encode_int64(INT64_MAX, &dbm_end_key);
4734
2
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4735
2
        if (ret != 0) {
4736
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
4737
0
                         << instance_id_;
4738
0
        }
4739
2
        return ret;
4740
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
4729
4.00k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
4730
4.00k
        std::string dbm_start_key =
4731
4.00k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4732
4.00k
        std::string dbm_end_key = dbm_start_key;
4733
4.00k
        encode_int64(INT64_MAX, &dbm_end_key);
4734
4.00k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4735
4.00k
        if (ret != 0) {
4736
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
4737
0
                         << instance_id_;
4738
0
        }
4739
4.00k
        return ret;
4740
4.00k
    };
4741
22
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
4742
902
                                            int64_t tablet_id, const std::string& rowset_id) {
4743
        // Try to delete rowset data in background thread
4744
902
        int ret = worker_pool->submit_with_timeout(
4745
902
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4746
813
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4747
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4748
0
                        return;
4749
0
                    }
4750
813
                    std::vector<std::string> keys;
4751
813
                    {
4752
813
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4753
813
                        async_recycled_rowset_keys.push_back(std::move(key));
4754
813
                        if (async_recycled_rowset_keys.size() > 100) {
4755
7
                            keys.swap(async_recycled_rowset_keys);
4756
7
                        }
4757
813
                    }
4758
813
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4759
813
                    if (keys.empty()) return;
4760
7
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4761
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4762
0
                                     << instance_id_;
4763
7
                    } else {
4764
7
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4765
7
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4766
7
                                           num_recycled, start_time);
4767
7
                    }
4768
7
                },
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
4745
2
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4746
2
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4747
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4748
0
                        return;
4749
0
                    }
4750
2
                    std::vector<std::string> keys;
4751
2
                    {
4752
2
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4753
2
                        async_recycled_rowset_keys.push_back(std::move(key));
4754
2
                        if (async_recycled_rowset_keys.size() > 100) {
4755
0
                            keys.swap(async_recycled_rowset_keys);
4756
0
                        }
4757
2
                    }
4758
2
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4759
2
                    if (keys.empty()) return;
4760
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4761
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4762
0
                                     << instance_id_;
4763
0
                    } else {
4764
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4765
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4766
0
                                           num_recycled, start_time);
4767
0
                    }
4768
0
                },
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
4745
811
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4746
811
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4747
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4748
0
                        return;
4749
0
                    }
4750
811
                    std::vector<std::string> keys;
4751
811
                    {
4752
811
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4753
811
                        async_recycled_rowset_keys.push_back(std::move(key));
4754
811
                        if (async_recycled_rowset_keys.size() > 100) {
4755
7
                            keys.swap(async_recycled_rowset_keys);
4756
7
                        }
4757
811
                    }
4758
811
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4759
811
                    if (keys.empty()) return;
4760
7
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4761
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4762
0
                                     << instance_id_;
4763
7
                    } else {
4764
7
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4765
7
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4766
7
                                           num_recycled, start_time);
4767
7
                    }
4768
7
                },
4769
902
                0);
4770
902
        if (ret == 0) return 0;
4771
        // Submit task failed, delete rowset data in current thread
4772
89
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4773
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4774
0
            return -1;
4775
0
        }
4776
89
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
4777
0
            return -1;
4778
0
        }
4779
89
        rowset_keys.push_back(std::move(key));
4780
89
        return 0;
4781
89
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
4742
2
                                            int64_t tablet_id, const std::string& rowset_id) {
4743
        // Try to delete rowset data in background thread
4744
2
        int ret = worker_pool->submit_with_timeout(
4745
2
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4746
2
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4747
2
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4748
2
                        return;
4749
2
                    }
4750
2
                    std::vector<std::string> keys;
4751
2
                    {
4752
2
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4753
2
                        async_recycled_rowset_keys.push_back(std::move(key));
4754
2
                        if (async_recycled_rowset_keys.size() > 100) {
4755
2
                            keys.swap(async_recycled_rowset_keys);
4756
2
                        }
4757
2
                    }
4758
2
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4759
2
                    if (keys.empty()) return;
4760
2
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4761
2
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4762
2
                                     << instance_id_;
4763
2
                    } else {
4764
2
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4765
2
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4766
2
                                           num_recycled, start_time);
4767
2
                    }
4768
2
                },
4769
2
                0);
4770
2
        if (ret == 0) return 0;
4771
        // Submit task failed, delete rowset data in current thread
4772
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4773
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4774
0
            return -1;
4775
0
        }
4776
0
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
4777
0
            return -1;
4778
0
        }
4779
0
        rowset_keys.push_back(std::move(key));
4780
0
        return 0;
4781
0
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
4742
900
                                            int64_t tablet_id, const std::string& rowset_id) {
4743
        // Try to delete rowset data in background thread
4744
900
        int ret = worker_pool->submit_with_timeout(
4745
900
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4746
900
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4747
900
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4748
900
                        return;
4749
900
                    }
4750
900
                    std::vector<std::string> keys;
4751
900
                    {
4752
900
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4753
900
                        async_recycled_rowset_keys.push_back(std::move(key));
4754
900
                        if (async_recycled_rowset_keys.size() > 100) {
4755
900
                            keys.swap(async_recycled_rowset_keys);
4756
900
                        }
4757
900
                    }
4758
900
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4759
900
                    if (keys.empty()) return;
4760
900
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4761
900
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4762
900
                                     << instance_id_;
4763
900
                    } else {
4764
900
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4765
900
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4766
900
                                           num_recycled, start_time);
4767
900
                    }
4768
900
                },
4769
900
                0);
4770
900
        if (ret == 0) return 0;
4771
        // Submit task failed, delete rowset data in current thread
4772
89
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4773
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4774
0
            return -1;
4775
0
        }
4776
89
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
4777
0
            return -1;
4778
0
        }
4779
89
        rowset_keys.push_back(std::move(key));
4780
89
        return 0;
4781
89
    };
4782
4783
22
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
4784
4785
7.75k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
4786
7.75k
        ++num_scanned;
4787
7.75k
        total_rowset_key_size += k.size();
4788
7.75k
        total_rowset_value_size += v.size();
4789
7.75k
        RecycleRowsetPB rowset;
4790
7.75k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
4791
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4792
0
            return -1;
4793
0
        }
4794
4795
7.75k
        int64_t current_time = ::time(nullptr);
4796
7.75k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
4797
4798
7.75k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
4799
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
4800
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
4801
7.75k
        if (current_time < expiration) { // not expired
4802
0
            return 0;
4803
0
        }
4804
7.75k
        ++num_expired;
4805
7.75k
        expired_rowset_size += v.size();
4806
4807
7.75k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
4808
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
4809
                // in old version, keep this key-value pair and it needs to be checked manually
4810
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4811
0
                return -1;
4812
0
            }
4813
250
            if (rowset.resource_id().empty()) [[unlikely]] {
4814
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
4815
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
4816
0
                          << hex(k) << " value=" << proto_to_json(rowset);
4817
0
                rowset_keys.emplace_back(k);
4818
0
                return -1;
4819
0
            }
4820
            // decode rowset_id
4821
250
            auto k1 = k;
4822
250
            k1.remove_prefix(1);
4823
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
4824
250
            decode_key(&k1, &out);
4825
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
4826
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
4827
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
4828
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
4829
250
                      << " task_type=" << metrics_context.operation_type;
4830
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
4831
250
                                             rowset.tablet_id(), rowset_id) != 0) {
4832
0
                return -1;
4833
0
            }
4834
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
4835
250
            metrics_context.total_recycled_num++;
4836
250
            segment_metrics_context_.total_recycled_data_size +=
4837
250
                    rowset.rowset_meta().total_disk_size();
4838
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
4839
250
            return 0;
4840
250
        }
4841
4842
7.50k
        auto* rowset_meta = rowset.mutable_rowset_meta();
4843
7.50k
        if (config::enable_mark_delete_rowset_before_recycle) {
4844
7.50k
            int mark_ret = mark_rowset_as_recycled(txn_kv_.get(), instance_id_, k, rowset);
4845
7.50k
            if (mark_ret == -1) {
4846
0
                LOG(WARNING) << "failed to mark rowset as recycled, instance_id=" << instance_id_
4847
0
                             << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4848
0
                             << rowset_meta->start_version() << '-' << rowset_meta->end_version()
4849
0
                             << "]";
4850
0
                return -1;
4851
7.50k
            } else if (mark_ret == 1) {
4852
3.75k
                LOG(INFO)
4853
3.75k
                        << "rowset already marked as recycled, recycler will delete data and kv at "
4854
3.75k
                           "next turn, instance_id="
4855
3.75k
                        << instance_id_ << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4856
3.75k
                        << rowset_meta->start_version() << '-' << rowset_meta->end_version() << "]";
4857
3.75k
                return 0;
4858
3.75k
            }
4859
7.50k
        }
4860
4861
3.75k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
4862
3.75k
            LOG(INFO) << "begin to abort txn or job for related rowset, instance_id="
4863
3.75k
                      << instance_id_ << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4864
3.75k
                      << rowset_meta->start_version() << '-' << rowset_meta->end_version() << "]";
4865
4866
3.75k
            if (rowset_meta->end_version() != 1) {
4867
3.75k
                int ret = abort_txn_or_job_for_recycle(rowset);
4868
4869
3.75k
                if (ret != 0) {
4870
0
                    LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
4871
0
                                 << instance_id_ << " tablet_id=" << rowset.tablet_id()
4872
0
                                 << " version=[" << rowset_meta->start_version() << '-'
4873
0
                                 << rowset_meta->end_version() << "]";
4874
0
                    return ret;
4875
0
                }
4876
3.75k
            }
4877
3.75k
        }
4878
4879
        // TODO(plat1ko): check rowset not referenced
4880
3.75k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
4881
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
4882
0
                LOG_INFO("recycle rowset that has empty resource id");
4883
0
            } else {
4884
                // other situations, keep this key-value pair and it needs to be checked manually
4885
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4886
0
                return -1;
4887
0
            }
4888
0
        }
4889
3.75k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
4890
3.75k
                  << " tablet_id=" << rowset_meta->tablet_id()
4891
3.75k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
4892
3.75k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
4893
3.75k
                  << "] txn_id=" << rowset_meta->txn_id()
4894
3.75k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
4895
3.75k
                  << " rowset_meta_size=" << v.size()
4896
3.75k
                  << " creation_time=" << rowset_meta->creation_time()
4897
3.75k
                  << " task_type=" << metrics_context.operation_type;
4898
3.75k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
4899
            // unable to calculate file path, can only be deleted by rowset id prefix
4900
652
            num_prepare += 1;
4901
652
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
4902
652
                                             rowset_meta->tablet_id(),
4903
652
                                             rowset_meta->rowset_id_v2()) != 0) {
4904
0
                return -1;
4905
0
            }
4906
3.10k
        } else {
4907
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
4908
3.10k
            rowset_keys.emplace_back(k);
4909
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
4910
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
4911
3.10k
                ++num_empty_rowset;
4912
3.10k
            }
4913
3.10k
        }
4914
3.75k
        return 0;
4915
3.75k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
4785
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
4786
7
        ++num_scanned;
4787
7
        total_rowset_key_size += k.size();
4788
7
        total_rowset_value_size += v.size();
4789
7
        RecycleRowsetPB rowset;
4790
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
4791
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4792
0
            return -1;
4793
0
        }
4794
4795
7
        int64_t current_time = ::time(nullptr);
4796
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
4797
4798
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
4799
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
4800
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
4801
7
        if (current_time < expiration) { // not expired
4802
0
            return 0;
4803
0
        }
4804
7
        ++num_expired;
4805
7
        expired_rowset_size += v.size();
4806
4807
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
4808
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
4809
                // in old version, keep this key-value pair and it needs to be checked manually
4810
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4811
0
                return -1;
4812
0
            }
4813
0
            if (rowset.resource_id().empty()) [[unlikely]] {
4814
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
4815
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
4816
0
                          << hex(k) << " value=" << proto_to_json(rowset);
4817
0
                rowset_keys.emplace_back(k);
4818
0
                return -1;
4819
0
            }
4820
            // decode rowset_id
4821
0
            auto k1 = k;
4822
0
            k1.remove_prefix(1);
4823
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
4824
0
            decode_key(&k1, &out);
4825
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
4826
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
4827
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
4828
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
4829
0
                      << " task_type=" << metrics_context.operation_type;
4830
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
4831
0
                                             rowset.tablet_id(), rowset_id) != 0) {
4832
0
                return -1;
4833
0
            }
4834
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
4835
0
            metrics_context.total_recycled_num++;
4836
0
            segment_metrics_context_.total_recycled_data_size +=
4837
0
                    rowset.rowset_meta().total_disk_size();
4838
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
4839
0
            return 0;
4840
0
        }
4841
4842
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
4843
7
        if (config::enable_mark_delete_rowset_before_recycle) {
4844
7
            int mark_ret = mark_rowset_as_recycled(txn_kv_.get(), instance_id_, k, rowset);
4845
7
            if (mark_ret == -1) {
4846
0
                LOG(WARNING) << "failed to mark rowset as recycled, instance_id=" << instance_id_
4847
0
                             << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4848
0
                             << rowset_meta->start_version() << '-' << rowset_meta->end_version()
4849
0
                             << "]";
4850
0
                return -1;
4851
7
            } else if (mark_ret == 1) {
4852
5
                LOG(INFO)
4853
5
                        << "rowset already marked as recycled, recycler will delete data and kv at "
4854
5
                           "next turn, instance_id="
4855
5
                        << instance_id_ << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4856
5
                        << rowset_meta->start_version() << '-' << rowset_meta->end_version() << "]";
4857
5
                return 0;
4858
5
            }
4859
7
        }
4860
4861
2
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
4862
2
            LOG(INFO) << "begin to abort txn or job for related rowset, instance_id="
4863
2
                      << instance_id_ << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4864
2
                      << rowset_meta->start_version() << '-' << rowset_meta->end_version() << "]";
4865
4866
2
            if (rowset_meta->end_version() != 1) {
4867
2
                int ret = abort_txn_or_job_for_recycle(rowset);
4868
4869
2
                if (ret != 0) {
4870
0
                    LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
4871
0
                                 << instance_id_ << " tablet_id=" << rowset.tablet_id()
4872
0
                                 << " version=[" << rowset_meta->start_version() << '-'
4873
0
                                 << rowset_meta->end_version() << "]";
4874
0
                    return ret;
4875
0
                }
4876
2
            }
4877
2
        }
4878
4879
        // TODO(plat1ko): check rowset not referenced
4880
2
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
4881
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
4882
0
                LOG_INFO("recycle rowset that has empty resource id");
4883
0
            } else {
4884
                // other situations, keep this key-value pair and it needs to be checked manually
4885
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4886
0
                return -1;
4887
0
            }
4888
0
        }
4889
2
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
4890
2
                  << " tablet_id=" << rowset_meta->tablet_id()
4891
2
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
4892
2
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
4893
2
                  << "] txn_id=" << rowset_meta->txn_id()
4894
2
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
4895
2
                  << " rowset_meta_size=" << v.size()
4896
2
                  << " creation_time=" << rowset_meta->creation_time()
4897
2
                  << " task_type=" << metrics_context.operation_type;
4898
2
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
4899
            // unable to calculate file path, can only be deleted by rowset id prefix
4900
2
            num_prepare += 1;
4901
2
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
4902
2
                                             rowset_meta->tablet_id(),
4903
2
                                             rowset_meta->rowset_id_v2()) != 0) {
4904
0
                return -1;
4905
0
            }
4906
2
        } else {
4907
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
4908
0
            rowset_keys.emplace_back(k);
4909
0
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
4910
0
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
4911
0
                ++num_empty_rowset;
4912
0
            }
4913
0
        }
4914
2
        return 0;
4915
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
4785
7.75k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
4786
7.75k
        ++num_scanned;
4787
7.75k
        total_rowset_key_size += k.size();
4788
7.75k
        total_rowset_value_size += v.size();
4789
7.75k
        RecycleRowsetPB rowset;
4790
7.75k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
4791
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4792
0
            return -1;
4793
0
        }
4794
4795
7.75k
        int64_t current_time = ::time(nullptr);
4796
7.75k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
4797
4798
7.75k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
4799
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
4800
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
4801
7.75k
        if (current_time < expiration) { // not expired
4802
0
            return 0;
4803
0
        }
4804
7.75k
        ++num_expired;
4805
7.75k
        expired_rowset_size += v.size();
4806
4807
7.75k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
4808
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
4809
                // in old version, keep this key-value pair and it needs to be checked manually
4810
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4811
0
                return -1;
4812
0
            }
4813
250
            if (rowset.resource_id().empty()) [[unlikely]] {
4814
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
4815
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
4816
0
                          << hex(k) << " value=" << proto_to_json(rowset);
4817
0
                rowset_keys.emplace_back(k);
4818
0
                return -1;
4819
0
            }
4820
            // decode rowset_id
4821
250
            auto k1 = k;
4822
250
            k1.remove_prefix(1);
4823
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
4824
250
            decode_key(&k1, &out);
4825
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
4826
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
4827
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
4828
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
4829
250
                      << " task_type=" << metrics_context.operation_type;
4830
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
4831
250
                                             rowset.tablet_id(), rowset_id) != 0) {
4832
0
                return -1;
4833
0
            }
4834
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
4835
250
            metrics_context.total_recycled_num++;
4836
250
            segment_metrics_context_.total_recycled_data_size +=
4837
250
                    rowset.rowset_meta().total_disk_size();
4838
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
4839
250
            return 0;
4840
250
        }
4841
4842
7.50k
        auto* rowset_meta = rowset.mutable_rowset_meta();
4843
7.50k
        if (config::enable_mark_delete_rowset_before_recycle) {
4844
7.50k
            int mark_ret = mark_rowset_as_recycled(txn_kv_.get(), instance_id_, k, rowset);
4845
7.50k
            if (mark_ret == -1) {
4846
0
                LOG(WARNING) << "failed to mark rowset as recycled, instance_id=" << instance_id_
4847
0
                             << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4848
0
                             << rowset_meta->start_version() << '-' << rowset_meta->end_version()
4849
0
                             << "]";
4850
0
                return -1;
4851
7.50k
            } else if (mark_ret == 1) {
4852
3.75k
                LOG(INFO)
4853
3.75k
                        << "rowset already marked as recycled, recycler will delete data and kv at "
4854
3.75k
                           "next turn, instance_id="
4855
3.75k
                        << instance_id_ << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4856
3.75k
                        << rowset_meta->start_version() << '-' << rowset_meta->end_version() << "]";
4857
3.75k
                return 0;
4858
3.75k
            }
4859
7.50k
        }
4860
4861
3.75k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
4862
3.75k
            LOG(INFO) << "begin to abort txn or job for related rowset, instance_id="
4863
3.75k
                      << instance_id_ << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4864
3.75k
                      << rowset_meta->start_version() << '-' << rowset_meta->end_version() << "]";
4865
4866
3.75k
            if (rowset_meta->end_version() != 1) {
4867
3.75k
                int ret = abort_txn_or_job_for_recycle(rowset);
4868
4869
3.75k
                if (ret != 0) {
4870
0
                    LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
4871
0
                                 << instance_id_ << " tablet_id=" << rowset.tablet_id()
4872
0
                                 << " version=[" << rowset_meta->start_version() << '-'
4873
0
                                 << rowset_meta->end_version() << "]";
4874
0
                    return ret;
4875
0
                }
4876
3.75k
            }
4877
3.75k
        }
4878
4879
        // TODO(plat1ko): check rowset not referenced
4880
3.75k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
4881
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
4882
0
                LOG_INFO("recycle rowset that has empty resource id");
4883
0
            } else {
4884
                // other situations, keep this key-value pair and it needs to be checked manually
4885
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4886
0
                return -1;
4887
0
            }
4888
0
        }
4889
3.75k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
4890
3.75k
                  << " tablet_id=" << rowset_meta->tablet_id()
4891
3.75k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
4892
3.75k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
4893
3.75k
                  << "] txn_id=" << rowset_meta->txn_id()
4894
3.75k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
4895
3.75k
                  << " rowset_meta_size=" << v.size()
4896
3.75k
                  << " creation_time=" << rowset_meta->creation_time()
4897
3.75k
                  << " task_type=" << metrics_context.operation_type;
4898
3.75k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
4899
            // unable to calculate file path, can only be deleted by rowset id prefix
4900
650
            num_prepare += 1;
4901
650
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
4902
650
                                             rowset_meta->tablet_id(),
4903
650
                                             rowset_meta->rowset_id_v2()) != 0) {
4904
0
                return -1;
4905
0
            }
4906
3.10k
        } else {
4907
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
4908
3.10k
            rowset_keys.emplace_back(k);
4909
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
4910
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
4911
3.10k
                ++num_empty_rowset;
4912
3.10k
            }
4913
3.10k
        }
4914
3.75k
        return 0;
4915
3.75k
    };
4916
4917
49
    auto loop_done = [&]() -> int {
4918
49
        std::vector<std::string> rowset_keys_to_delete;
4919
        // rowset_id -> rowset_meta
4920
        // store rowset id and meta for statistics rs size when delete
4921
49
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
4922
49
        rowset_keys_to_delete.swap(rowset_keys);
4923
49
        rowsets_to_delete.swap(rowsets);
4924
49
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
4925
49
                             rowsets_to_delete = std::move(rowsets_to_delete)]() {
4926
49
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
4927
49
                                   metrics_context) != 0) {
4928
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
4929
0
                return;
4930
0
            }
4931
3.10k
            for (const auto& [_, rs] : rowsets_to_delete) {
4932
3.10k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
4933
0
                    return;
4934
0
                }
4935
3.10k
            }
4936
49
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
4937
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
4938
0
                return;
4939
0
            }
4940
49
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
4941
49
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
4925
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() {
4926
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
4927
7
                                   metrics_context) != 0) {
4928
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
4929
0
                return;
4930
0
            }
4931
7
            for (const auto& [_, rs] : rowsets_to_delete) {
4932
0
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
4933
0
                    return;
4934
0
                }
4935
0
            }
4936
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
4937
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
4938
0
                return;
4939
0
            }
4940
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
4941
7
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
4925
42
                             rowsets_to_delete = std::move(rowsets_to_delete)]() {
4926
42
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
4927
42
                                   metrics_context) != 0) {
4928
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
4929
0
                return;
4930
0
            }
4931
3.10k
            for (const auto& [_, rs] : rowsets_to_delete) {
4932
3.10k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
4933
0
                    return;
4934
0
                }
4935
3.10k
            }
4936
42
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
4937
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
4938
0
                return;
4939
0
            }
4940
42
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
4941
42
        });
4942
49
        return 0;
4943
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
4917
7
    auto loop_done = [&]() -> int {
4918
7
        std::vector<std::string> rowset_keys_to_delete;
4919
        // rowset_id -> rowset_meta
4920
        // store rowset id and meta for statistics rs size when delete
4921
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
4922
7
        rowset_keys_to_delete.swap(rowset_keys);
4923
7
        rowsets_to_delete.swap(rowsets);
4924
7
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
4925
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() {
4926
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
4927
7
                                   metrics_context) != 0) {
4928
7
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
4929
7
                return;
4930
7
            }
4931
7
            for (const auto& [_, rs] : rowsets_to_delete) {
4932
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
4933
7
                    return;
4934
7
                }
4935
7
            }
4936
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
4937
7
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
4938
7
                return;
4939
7
            }
4940
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
4941
7
        });
4942
7
        return 0;
4943
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
4917
42
    auto loop_done = [&]() -> int {
4918
42
        std::vector<std::string> rowset_keys_to_delete;
4919
        // rowset_id -> rowset_meta
4920
        // store rowset id and meta for statistics rs size when delete
4921
42
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
4922
42
        rowset_keys_to_delete.swap(rowset_keys);
4923
42
        rowsets_to_delete.swap(rowsets);
4924
42
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
4925
42
                             rowsets_to_delete = std::move(rowsets_to_delete)]() {
4926
42
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
4927
42
                                   metrics_context) != 0) {
4928
42
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
4929
42
                return;
4930
42
            }
4931
42
            for (const auto& [_, rs] : rowsets_to_delete) {
4932
42
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
4933
42
                    return;
4934
42
                }
4935
42
            }
4936
42
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
4937
42
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
4938
42
                return;
4939
42
            }
4940
42
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
4941
42
        });
4942
42
        return 0;
4943
42
    };
4944
4945
22
    if (config::enable_recycler_stats_metrics) {
4946
0
        scan_and_statistics_rowsets();
4947
0
    }
4948
    // recycle_func and loop_done for scan and recycle
4949
22
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
4950
22
                               std::move(loop_done));
4951
4952
22
    worker_pool->stop();
4953
4954
22
    if (!async_recycled_rowset_keys.empty()) {
4955
5
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
4956
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
4957
0
            return -1;
4958
5
        } else {
4959
5
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
4960
5
        }
4961
5
    }
4962
4963
    // Report final metrics after all concurrent tasks completed
4964
22
    segment_metrics_context_.report();
4965
22
    metrics_context.report();
4966
4967
22
    return ret;
4968
22
}
4969
4970
13
int InstanceRecycler::recycle_restore_jobs() {
4971
13
    const std::string task_name = "recycle_restore_jobs";
4972
13
    int64_t num_scanned = 0;
4973
13
    int64_t num_expired = 0;
4974
13
    int64_t num_recycled = 0;
4975
13
    int64_t num_aborted = 0;
4976
4977
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
4978
4979
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
4980
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
4981
13
    std::string restore_job_key0;
4982
13
    std::string restore_job_key1;
4983
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
4984
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
4985
4986
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
4987
4988
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
4989
13
    register_recycle_task(task_name, start_time);
4990
4991
13
    DORIS_CLOUD_DEFER {
4992
13
        unregister_recycle_task(task_name);
4993
13
        int64_t cost =
4994
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4995
13
        metrics_context.finish_report();
4996
4997
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
4998
13
                .tag("instance_id", instance_id_)
4999
13
                .tag("num_scanned", num_scanned)
5000
13
                .tag("num_expired", num_expired)
5001
13
                .tag("num_recycled", num_recycled)
5002
13
                .tag("num_aborted", num_aborted);
5003
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
4991
13
    DORIS_CLOUD_DEFER {
4992
13
        unregister_recycle_task(task_name);
4993
13
        int64_t cost =
4994
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4995
13
        metrics_context.finish_report();
4996
4997
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
4998
13
                .tag("instance_id", instance_id_)
4999
13
                .tag("num_scanned", num_scanned)
5000
13
                .tag("num_expired", num_expired)
5001
13
                .tag("num_recycled", num_recycled)
5002
13
                .tag("num_aborted", num_aborted);
5003
13
    };
5004
5005
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5006
5007
13
    std::vector<std::string_view> restore_job_keys;
5008
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5009
41
        ++num_scanned;
5010
41
        RestoreJobCloudPB restore_job_pb;
5011
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5012
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5013
0
            return -1;
5014
0
        }
5015
41
        int64_t expiration =
5016
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5017
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5018
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5019
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5020
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5021
0
                   << " state=" << restore_job_pb.state();
5022
41
        int64_t current_time = ::time(nullptr);
5023
41
        if (current_time < expiration) { // not expired
5024
0
            return 0;
5025
0
        }
5026
41
        ++num_expired;
5027
5028
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5029
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5030
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5031
5032
41
        std::unique_ptr<Transaction> txn;
5033
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5034
41
        if (err != TxnErrorCode::TXN_OK) {
5035
0
            LOG_WARNING("failed to recycle restore job")
5036
0
                    .tag("err", err)
5037
0
                    .tag("tablet id", tablet_id)
5038
0
                    .tag("instance_id", instance_id_)
5039
0
                    .tag("reason", "failed to create txn");
5040
0
            return -1;
5041
0
        }
5042
5043
41
        std::string val;
5044
41
        err = txn->get(k, &val);
5045
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5046
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5047
0
            return 0;
5048
0
        }
5049
41
        if (err != TxnErrorCode::TXN_OK) {
5050
0
            LOG_WARNING("failed to get kv");
5051
0
            return -1;
5052
0
        }
5053
41
        restore_job_pb.Clear();
5054
41
        if (!restore_job_pb.ParseFromString(val)) {
5055
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5056
0
            return -1;
5057
0
        }
5058
5059
        // PREPARED or COMMITTED, change state to DROPPED and return
5060
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5061
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5062
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5063
0
            restore_job_pb.set_need_recycle_data(true);
5064
0
            txn->put(k, restore_job_pb.SerializeAsString());
5065
0
            err = txn->commit();
5066
0
            if (err != TxnErrorCode::TXN_OK) {
5067
0
                LOG_WARNING("failed to commit txn: {}", err);
5068
0
                return -1;
5069
0
            }
5070
0
            num_aborted++;
5071
0
            return 0;
5072
0
        }
5073
5074
        // Change state to RECYCLING
5075
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5076
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5077
21
            txn->put(k, restore_job_pb.SerializeAsString());
5078
21
            err = txn->commit();
5079
21
            if (err != TxnErrorCode::TXN_OK) {
5080
0
                LOG_WARNING("failed to commit txn: {}", err);
5081
0
                return -1;
5082
0
            }
5083
21
            return 0;
5084
21
        }
5085
5086
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5087
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5088
5089
        // Recycle all data associated with the restore job.
5090
        // This includes rowsets, segments, and related resources.
5091
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5092
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5093
0
            LOG_WARNING("failed to recycle tablet")
5094
0
                    .tag("tablet_id", tablet_id)
5095
0
                    .tag("instance_id", instance_id_);
5096
0
            return -1;
5097
0
        }
5098
5099
        // delete all restore job rowset kv
5100
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5101
5102
20
        err = txn->commit();
5103
20
        if (err != TxnErrorCode::TXN_OK) {
5104
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5105
0
                    .tag("err", err)
5106
0
                    .tag("tablet id", tablet_id)
5107
0
                    .tag("instance_id", instance_id_)
5108
0
                    .tag("reason", "failed to commit txn");
5109
0
            return -1;
5110
0
        }
5111
5112
20
        metrics_context.total_recycled_num = ++num_recycled;
5113
20
        metrics_context.report();
5114
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5115
20
        restore_job_keys.push_back(k);
5116
5117
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5118
20
                  << " tablet_id=" << tablet_id;
5119
20
        return 0;
5120
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
5008
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5009
41
        ++num_scanned;
5010
41
        RestoreJobCloudPB restore_job_pb;
5011
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5012
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5013
0
            return -1;
5014
0
        }
5015
41
        int64_t expiration =
5016
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5017
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5018
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5019
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5020
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5021
0
                   << " state=" << restore_job_pb.state();
5022
41
        int64_t current_time = ::time(nullptr);
5023
41
        if (current_time < expiration) { // not expired
5024
0
            return 0;
5025
0
        }
5026
41
        ++num_expired;
5027
5028
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5029
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5030
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5031
5032
41
        std::unique_ptr<Transaction> txn;
5033
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5034
41
        if (err != TxnErrorCode::TXN_OK) {
5035
0
            LOG_WARNING("failed to recycle restore job")
5036
0
                    .tag("err", err)
5037
0
                    .tag("tablet id", tablet_id)
5038
0
                    .tag("instance_id", instance_id_)
5039
0
                    .tag("reason", "failed to create txn");
5040
0
            return -1;
5041
0
        }
5042
5043
41
        std::string val;
5044
41
        err = txn->get(k, &val);
5045
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5046
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5047
0
            return 0;
5048
0
        }
5049
41
        if (err != TxnErrorCode::TXN_OK) {
5050
0
            LOG_WARNING("failed to get kv");
5051
0
            return -1;
5052
0
        }
5053
41
        restore_job_pb.Clear();
5054
41
        if (!restore_job_pb.ParseFromString(val)) {
5055
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5056
0
            return -1;
5057
0
        }
5058
5059
        // PREPARED or COMMITTED, change state to DROPPED and return
5060
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5061
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5062
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5063
0
            restore_job_pb.set_need_recycle_data(true);
5064
0
            txn->put(k, restore_job_pb.SerializeAsString());
5065
0
            err = txn->commit();
5066
0
            if (err != TxnErrorCode::TXN_OK) {
5067
0
                LOG_WARNING("failed to commit txn: {}", err);
5068
0
                return -1;
5069
0
            }
5070
0
            num_aborted++;
5071
0
            return 0;
5072
0
        }
5073
5074
        // Change state to RECYCLING
5075
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5076
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5077
21
            txn->put(k, restore_job_pb.SerializeAsString());
5078
21
            err = txn->commit();
5079
21
            if (err != TxnErrorCode::TXN_OK) {
5080
0
                LOG_WARNING("failed to commit txn: {}", err);
5081
0
                return -1;
5082
0
            }
5083
21
            return 0;
5084
21
        }
5085
5086
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5087
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5088
5089
        // Recycle all data associated with the restore job.
5090
        // This includes rowsets, segments, and related resources.
5091
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5092
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5093
0
            LOG_WARNING("failed to recycle tablet")
5094
0
                    .tag("tablet_id", tablet_id)
5095
0
                    .tag("instance_id", instance_id_);
5096
0
            return -1;
5097
0
        }
5098
5099
        // delete all restore job rowset kv
5100
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5101
5102
20
        err = txn->commit();
5103
20
        if (err != TxnErrorCode::TXN_OK) {
5104
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5105
0
                    .tag("err", err)
5106
0
                    .tag("tablet id", tablet_id)
5107
0
                    .tag("instance_id", instance_id_)
5108
0
                    .tag("reason", "failed to commit txn");
5109
0
            return -1;
5110
0
        }
5111
5112
20
        metrics_context.total_recycled_num = ++num_recycled;
5113
20
        metrics_context.report();
5114
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5115
20
        restore_job_keys.push_back(k);
5116
5117
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5118
20
                  << " tablet_id=" << tablet_id;
5119
20
        return 0;
5120
20
    };
5121
5122
13
    auto loop_done = [&restore_job_keys, this]() -> int {
5123
3
        if (restore_job_keys.empty()) return 0;
5124
1
        DORIS_CLOUD_DEFER {
5125
1
            restore_job_keys.clear();
5126
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5124
1
        DORIS_CLOUD_DEFER {
5125
1
            restore_job_keys.clear();
5126
1
        };
5127
5128
1
        std::unique_ptr<Transaction> txn;
5129
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5130
1
        if (err != TxnErrorCode::TXN_OK) {
5131
0
            LOG_WARNING("failed to recycle restore job")
5132
0
                    .tag("err", err)
5133
0
                    .tag("instance_id", instance_id_)
5134
0
                    .tag("reason", "failed to create txn");
5135
0
            return -1;
5136
0
        }
5137
20
        for (auto& k : restore_job_keys) {
5138
20
            txn->remove(k);
5139
20
        }
5140
1
        err = txn->commit();
5141
1
        if (err != TxnErrorCode::TXN_OK) {
5142
0
            LOG_WARNING("failed to recycle restore job")
5143
0
                    .tag("err", err)
5144
0
                    .tag("instance_id", instance_id_)
5145
0
                    .tag("reason", "failed to commit txn");
5146
0
            return -1;
5147
0
        }
5148
1
        return 0;
5149
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
5122
3
    auto loop_done = [&restore_job_keys, this]() -> int {
5123
3
        if (restore_job_keys.empty()) return 0;
5124
1
        DORIS_CLOUD_DEFER {
5125
1
            restore_job_keys.clear();
5126
1
        };
5127
5128
1
        std::unique_ptr<Transaction> txn;
5129
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5130
1
        if (err != TxnErrorCode::TXN_OK) {
5131
0
            LOG_WARNING("failed to recycle restore job")
5132
0
                    .tag("err", err)
5133
0
                    .tag("instance_id", instance_id_)
5134
0
                    .tag("reason", "failed to create txn");
5135
0
            return -1;
5136
0
        }
5137
20
        for (auto& k : restore_job_keys) {
5138
20
            txn->remove(k);
5139
20
        }
5140
1
        err = txn->commit();
5141
1
        if (err != TxnErrorCode::TXN_OK) {
5142
0
            LOG_WARNING("failed to recycle restore job")
5143
0
                    .tag("err", err)
5144
0
                    .tag("instance_id", instance_id_)
5145
0
                    .tag("reason", "failed to commit txn");
5146
0
            return -1;
5147
0
        }
5148
1
        return 0;
5149
1
    };
5150
5151
13
    if (config::enable_recycler_stats_metrics) {
5152
0
        scan_and_statistics_restore_jobs();
5153
0
    }
5154
5155
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
5156
13
                            std::move(loop_done));
5157
13
}
5158
5159
10
int InstanceRecycler::recycle_versioned_rowsets() {
5160
10
    const std::string task_name = "recycle_rowsets";
5161
10
    int64_t num_scanned = 0;
5162
10
    int64_t num_expired = 0;
5163
10
    int64_t num_prepare = 0;
5164
10
    int64_t num_compacted = 0;
5165
10
    int64_t num_empty_rowset = 0;
5166
10
    size_t total_rowset_key_size = 0;
5167
10
    size_t total_rowset_value_size = 0;
5168
10
    size_t expired_rowset_size = 0;
5169
10
    std::atomic_long num_recycled = 0;
5170
10
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5171
5172
10
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5173
10
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5174
10
    std::string recyc_rs_key0;
5175
10
    std::string recyc_rs_key1;
5176
10
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5177
10
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5178
5179
10
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5180
5181
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5182
10
    register_recycle_task(task_name, start_time);
5183
5184
10
    DORIS_CLOUD_DEFER {
5185
10
        unregister_recycle_task(task_name);
5186
10
        int64_t cost =
5187
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5188
10
        metrics_context.finish_report();
5189
10
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5190
10
                .tag("instance_id", instance_id_)
5191
10
                .tag("num_scanned", num_scanned)
5192
10
                .tag("num_expired", num_expired)
5193
10
                .tag("num_recycled", num_recycled)
5194
10
                .tag("num_recycled.prepare", num_prepare)
5195
10
                .tag("num_recycled.compacted", num_compacted)
5196
10
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5197
10
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5198
10
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5199
10
                .tag("expired_rowset_meta_size", expired_rowset_size);
5200
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
5184
10
    DORIS_CLOUD_DEFER {
5185
10
        unregister_recycle_task(task_name);
5186
10
        int64_t cost =
5187
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5188
10
        metrics_context.finish_report();
5189
10
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5190
10
                .tag("instance_id", instance_id_)
5191
10
                .tag("num_scanned", num_scanned)
5192
10
                .tag("num_expired", num_expired)
5193
10
                .tag("num_recycled", num_recycled)
5194
10
                .tag("num_recycled.prepare", num_prepare)
5195
10
                .tag("num_recycled.compacted", num_compacted)
5196
10
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5197
10
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5198
10
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5199
10
                .tag("expired_rowset_meta_size", expired_rowset_size);
5200
10
    };
5201
5202
10
    std::vector<std::string> orphan_rowset_keys;
5203
5204
    // Store keys of rowset recycled by background workers
5205
10
    std::mutex async_recycled_rowset_keys_mutex;
5206
10
    std::vector<std::string> async_recycled_rowset_keys;
5207
10
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5208
10
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5209
10
    worker_pool->start();
5210
10
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5211
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5212
        // Try to delete rowset data in background thread
5213
400
        int ret = worker_pool->submit_with_timeout(
5214
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5215
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5216
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5217
400
                        return;
5218
400
                    }
5219
                    // The async recycled rowsets are staled format or has not been used,
5220
                    // so we don't need to check the rowset ref count key.
5221
0
                    std::vector<std::string> keys;
5222
0
                    {
5223
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5224
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5225
0
                        if (async_recycled_rowset_keys.size() > 100) {
5226
0
                            keys.swap(async_recycled_rowset_keys);
5227
0
                        }
5228
0
                    }
5229
0
                    if (keys.empty()) return;
5230
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5231
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5232
0
                                     << instance_id_;
5233
0
                    } else {
5234
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5235
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5236
0
                                           num_recycled, start_time);
5237
0
                    }
5238
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
5214
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5215
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5216
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5217
400
                        return;
5218
400
                    }
5219
                    // The async recycled rowsets are staled format or has not been used,
5220
                    // so we don't need to check the rowset ref count key.
5221
0
                    std::vector<std::string> keys;
5222
0
                    {
5223
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5224
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5225
0
                        if (async_recycled_rowset_keys.size() > 100) {
5226
0
                            keys.swap(async_recycled_rowset_keys);
5227
0
                        }
5228
0
                    }
5229
0
                    if (keys.empty()) return;
5230
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5231
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5232
0
                                     << instance_id_;
5233
0
                    } else {
5234
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5235
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5236
0
                                           num_recycled, start_time);
5237
0
                    }
5238
0
                },
5239
400
                0);
5240
400
        if (ret == 0) return 0;
5241
        // Submit task failed, delete rowset data in current thread
5242
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5243
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5244
0
            return -1;
5245
0
        }
5246
0
        orphan_rowset_keys.push_back(std::move(key));
5247
0
        return 0;
5248
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
5211
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5212
        // Try to delete rowset data in background thread
5213
400
        int ret = worker_pool->submit_with_timeout(
5214
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5215
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5216
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5217
400
                        return;
5218
400
                    }
5219
                    // The async recycled rowsets are staled format or has not been used,
5220
                    // so we don't need to check the rowset ref count key.
5221
400
                    std::vector<std::string> keys;
5222
400
                    {
5223
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5224
400
                        async_recycled_rowset_keys.push_back(std::move(key));
5225
400
                        if (async_recycled_rowset_keys.size() > 100) {
5226
400
                            keys.swap(async_recycled_rowset_keys);
5227
400
                        }
5228
400
                    }
5229
400
                    if (keys.empty()) return;
5230
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5231
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5232
400
                                     << instance_id_;
5233
400
                    } else {
5234
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5235
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5236
400
                                           num_recycled, start_time);
5237
400
                    }
5238
400
                },
5239
400
                0);
5240
400
        if (ret == 0) return 0;
5241
        // Submit task failed, delete rowset data in current thread
5242
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5243
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5244
0
            return -1;
5245
0
        }
5246
0
        orphan_rowset_keys.push_back(std::move(key));
5247
0
        return 0;
5248
0
    };
5249
5250
10
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5251
5252
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
5253
2.01k
        ++num_scanned;
5254
2.01k
        total_rowset_key_size += k.size();
5255
2.01k
        total_rowset_value_size += v.size();
5256
2.01k
        RecycleRowsetPB rowset;
5257
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5258
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5259
0
            return -1;
5260
0
        }
5261
5262
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5263
5264
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5265
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
5266
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5267
2.01k
        int64_t current_time = ::time(nullptr);
5268
2.01k
        if (current_time < final_expiration) { // not expired
5269
0
            return 0;
5270
0
        }
5271
2.01k
        ++num_expired;
5272
2.01k
        expired_rowset_size += v.size();
5273
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5274
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5275
                // in old version, keep this key-value pair and it needs to be checked manually
5276
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5277
0
                return -1;
5278
0
            }
5279
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5280
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5281
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5282
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5283
0
                orphan_rowset_keys.emplace_back(k);
5284
0
                return -1;
5285
0
            }
5286
            // decode rowset_id
5287
0
            auto k1 = k;
5288
0
            k1.remove_prefix(1);
5289
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5290
0
            decode_key(&k1, &out);
5291
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5292
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5293
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5294
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
5295
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5296
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5297
0
                return -1;
5298
0
            }
5299
0
            return 0;
5300
0
        }
5301
        // TODO(plat1ko): check rowset not referenced
5302
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
5303
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5304
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5305
0
                LOG_INFO("recycle rowset that has empty resource id");
5306
0
            } else {
5307
                // other situations, keep this key-value pair and it needs to be checked manually
5308
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5309
0
                return -1;
5310
0
            }
5311
0
        }
5312
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5313
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
5314
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5315
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5316
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
5317
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5318
2.01k
                  << " rowset_meta_size=" << v.size()
5319
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
5320
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5321
            // unable to calculate file path, can only be deleted by rowset id prefix
5322
400
            num_prepare += 1;
5323
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5324
400
                                             rowset_meta->tablet_id(),
5325
400
                                             rowset_meta->rowset_id_v2()) != 0) {
5326
0
                return -1;
5327
0
            }
5328
1.61k
        } else {
5329
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
5330
1.61k
            worker_pool->submit(
5331
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5332
                        // The load & compact rowset keys are recycled during recycling operation logs.
5333
1.61k
                        RowsetDeleteTask task;
5334
1.61k
                        task.rowset_meta = rowset_meta;
5335
1.61k
                        task.recycle_rowset_key = k;
5336
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
5337
1.59k
                            return;
5338
1.59k
                        }
5339
14
                        num_compacted += is_compacted;
5340
14
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5341
14
                        if (rowset_meta.num_segments() == 0) {
5342
0
                            ++num_empty_rowset;
5343
0
                        }
5344
14
                    });
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
5331
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5332
                        // The load & compact rowset keys are recycled during recycling operation logs.
5333
1.61k
                        RowsetDeleteTask task;
5334
1.61k
                        task.rowset_meta = rowset_meta;
5335
1.61k
                        task.recycle_rowset_key = k;
5336
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
5337
1.59k
                            return;
5338
1.59k
                        }
5339
14
                        num_compacted += is_compacted;
5340
14
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5341
14
                        if (rowset_meta.num_segments() == 0) {
5342
0
                            ++num_empty_rowset;
5343
0
                        }
5344
14
                    });
5345
1.61k
        }
5346
2.01k
        return 0;
5347
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
5252
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
5253
2.01k
        ++num_scanned;
5254
2.01k
        total_rowset_key_size += k.size();
5255
2.01k
        total_rowset_value_size += v.size();
5256
2.01k
        RecycleRowsetPB rowset;
5257
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5258
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5259
0
            return -1;
5260
0
        }
5261
5262
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5263
5264
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5265
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
5266
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5267
2.01k
        int64_t current_time = ::time(nullptr);
5268
2.01k
        if (current_time < final_expiration) { // not expired
5269
0
            return 0;
5270
0
        }
5271
2.01k
        ++num_expired;
5272
2.01k
        expired_rowset_size += v.size();
5273
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5274
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5275
                // in old version, keep this key-value pair and it needs to be checked manually
5276
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5277
0
                return -1;
5278
0
            }
5279
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5280
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5281
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5282
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5283
0
                orphan_rowset_keys.emplace_back(k);
5284
0
                return -1;
5285
0
            }
5286
            // decode rowset_id
5287
0
            auto k1 = k;
5288
0
            k1.remove_prefix(1);
5289
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5290
0
            decode_key(&k1, &out);
5291
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5292
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5293
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5294
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
5295
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5296
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5297
0
                return -1;
5298
0
            }
5299
0
            return 0;
5300
0
        }
5301
        // TODO(plat1ko): check rowset not referenced
5302
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
5303
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5304
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5305
0
                LOG_INFO("recycle rowset that has empty resource id");
5306
0
            } else {
5307
                // other situations, keep this key-value pair and it needs to be checked manually
5308
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5309
0
                return -1;
5310
0
            }
5311
0
        }
5312
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5313
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
5314
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5315
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5316
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
5317
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5318
2.01k
                  << " rowset_meta_size=" << v.size()
5319
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
5320
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5321
            // unable to calculate file path, can only be deleted by rowset id prefix
5322
400
            num_prepare += 1;
5323
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5324
400
                                             rowset_meta->tablet_id(),
5325
400
                                             rowset_meta->rowset_id_v2()) != 0) {
5326
0
                return -1;
5327
0
            }
5328
1.61k
        } else {
5329
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
5330
1.61k
            worker_pool->submit(
5331
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5332
                        // The load & compact rowset keys are recycled during recycling operation logs.
5333
1.61k
                        RowsetDeleteTask task;
5334
1.61k
                        task.rowset_meta = rowset_meta;
5335
1.61k
                        task.recycle_rowset_key = k;
5336
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
5337
1.61k
                            return;
5338
1.61k
                        }
5339
1.61k
                        num_compacted += is_compacted;
5340
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5341
1.61k
                        if (rowset_meta.num_segments() == 0) {
5342
1.61k
                            ++num_empty_rowset;
5343
1.61k
                        }
5344
1.61k
                    });
5345
1.61k
        }
5346
2.01k
        return 0;
5347
2.01k
    };
5348
5349
10
    if (config::enable_recycler_stats_metrics) {
5350
0
        scan_and_statistics_rowsets();
5351
0
    }
5352
5353
10
    auto loop_done = [&]() -> int {
5354
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
5355
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5356
0
        }
5357
6
        orphan_rowset_keys.clear();
5358
6
        return 0;
5359
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
Line
Count
Source
5353
6
    auto loop_done = [&]() -> int {
5354
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
5355
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5356
0
        }
5357
6
        orphan_rowset_keys.clear();
5358
6
        return 0;
5359
6
    };
5360
5361
    // recycle_func and loop_done for scan and recycle
5362
10
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
5363
10
                               std::move(loop_done));
5364
5365
10
    worker_pool->stop();
5366
5367
10
    if (!async_recycled_rowset_keys.empty()) {
5368
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5369
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5370
0
            return -1;
5371
0
        } else {
5372
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5373
0
        }
5374
0
    }
5375
5376
    // Report final metrics after all concurrent tasks completed
5377
10
    segment_metrics_context_.report();
5378
10
    metrics_context.report();
5379
5380
10
    return ret;
5381
10
}
5382
5383
1.61k
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task) {
5384
1.61k
    constexpr int MAX_RETRY = 10;
5385
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
5386
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
5387
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
5388
1.61k
    std::string_view reference_instance_id = instance_id_;
5389
1.61k
    if (rowset_meta.has_reference_instance_id()) {
5390
8
        reference_instance_id = rowset_meta.reference_instance_id();
5391
8
    }
5392
5393
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
5394
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
5395
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
5396
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
5397
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
5398
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
5399
1.61k
        std::unique_ptr<Transaction> txn;
5400
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5401
1.61k
        if (err != TxnErrorCode::TXN_OK) {
5402
0
            LOG_WARNING("failed to create txn").tag("err", err);
5403
0
            return -1;
5404
0
        }
5405
5406
1.61k
        std::string rowset_ref_count_key =
5407
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
5408
1.61k
        int64_t ref_count = 0;
5409
1.61k
        {
5410
1.61k
            std::string value;
5411
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
5412
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
5413
                // This is the old version rowset, we could recycle it directly.
5414
1.60k
                ref_count = 1;
5415
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
5416
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
5417
0
                return -1;
5418
11
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
5419
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
5420
0
                return -1;
5421
0
            }
5422
1.61k
        }
5423
5424
1.61k
        if (ref_count == 1) {
5425
            // It would not be added since it is recycling.
5426
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
5427
1.60k
                LOG_WARNING("failed to delete rowset data");
5428
1.60k
                return -1;
5429
1.60k
            }
5430
5431
            // Reset the transaction to avoid timeout.
5432
10
            err = txn_kv_->create_txn(&txn);
5433
10
            if (err != TxnErrorCode::TXN_OK) {
5434
0
                LOG_WARNING("failed to create txn").tag("err", err);
5435
0
                return -1;
5436
0
            }
5437
10
            txn->remove(rowset_ref_count_key);
5438
10
            LOG_INFO("delete rowset data ref count key")
5439
10
                    .tag("txn_id", rowset_meta.txn_id())
5440
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
5441
5442
10
            std::string dbm_start_key =
5443
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
5444
10
            std::string dbm_end_key = meta_delete_bitmap_key(
5445
10
                    {reference_instance_id, tablet_id, rowset_id,
5446
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
5447
10
            txn->remove(dbm_start_key, dbm_end_key);
5448
10
            LOG_INFO("remove delete bitmap kv")
5449
10
                    .tag("begin", hex(dbm_start_key))
5450
10
                    .tag("end", hex(dbm_end_key));
5451
5452
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
5453
10
                    {reference_instance_id, tablet_id, rowset_id});
5454
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
5455
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
5456
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
5457
10
            LOG_INFO("remove versioned delete bitmap kv")
5458
10
                    .tag("begin", hex(versioned_dbm_start_key))
5459
10
                    .tag("end", hex(versioned_dbm_end_key));
5460
10
        } else {
5461
            // Decrease the rowset ref count.
5462
            //
5463
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
5464
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
5465
3
            txn->atomic_add(rowset_ref_count_key, -1);
5466
3
            LOG_INFO("decrease rowset data ref count")
5467
3
                    .tag("txn_id", rowset_meta.txn_id())
5468
3
                    .tag("ref_count", ref_count - 1)
5469
3
                    .tag("ref_count_key", hex(rowset_ref_count_key));
5470
3
        }
5471
5472
13
        if (!task.versioned_rowset_key.empty()) {
5473
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
5474
0
                                                          task.versionstamp);
5475
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
5476
0
        }
5477
5478
13
        if (!task.non_versioned_rowset_key.empty()) {
5479
0
            txn->remove(task.non_versioned_rowset_key);
5480
0
            LOG_INFO("remove non versioned rowset key")
5481
0
                    .tag("key", hex(task.non_versioned_rowset_key));
5482
0
        }
5483
5484
        // empty when recycle ref rowsets for deleted instance
5485
13
        if (!task.recycle_rowset_key.empty()) {
5486
13
            txn->remove(task.recycle_rowset_key);
5487
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
5488
13
        }
5489
5490
13
        err = txn->commit();
5491
13
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
5492
            // The rowset ref count key has been changed, we need to retry.
5493
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
5494
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
5495
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
5496
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
5497
0
            continue;
5498
13
        } else if (err != TxnErrorCode::TXN_OK) {
5499
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
5500
0
            return -1;
5501
0
        }
5502
13
        LOG_INFO("recycle rowset meta and data success");
5503
13
        return 0;
5504
13
    }
5505
0
    LOG_WARNING("failed to recycle rowset meta and data after retry")
5506
0
            .tag("tablet_id", tablet_id)
5507
0
            .tag("rowset_id", rowset_id)
5508
0
            .tag("retry", MAX_RETRY);
5509
0
    return -1;
5510
1.61k
}
5511
5512
39
int InstanceRecycler::recycle_tmp_rowsets() {
5513
39
    const std::string task_name = "recycle_tmp_rowsets";
5514
39
    int64_t num_scanned = 0;
5515
39
    int64_t num_expired = 0;
5516
39
    std::atomic_long num_recycled = 0;
5517
39
    size_t expired_rowset_size = 0;
5518
39
    size_t total_rowset_key_size = 0;
5519
39
    size_t total_rowset_value_size = 0;
5520
39
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5521
5522
39
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
5523
39
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
5524
39
    std::string tmp_rs_key0;
5525
39
    std::string tmp_rs_key1;
5526
39
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
5527
39
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
5528
5529
39
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
5530
5531
39
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5532
39
    register_recycle_task(task_name, start_time);
5533
5534
39
    DORIS_CLOUD_DEFER {
5535
39
        unregister_recycle_task(task_name);
5536
39
        int64_t cost =
5537
39
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5538
39
        metrics_context.finish_report();
5539
39
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5540
39
                .tag("instance_id", instance_id_)
5541
39
                .tag("num_scanned", num_scanned)
5542
39
                .tag("num_expired", num_expired)
5543
39
                .tag("num_recycled", num_recycled)
5544
39
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5545
39
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5546
39
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5547
39
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
5534
12
    DORIS_CLOUD_DEFER {
5535
12
        unregister_recycle_task(task_name);
5536
12
        int64_t cost =
5537
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5538
12
        metrics_context.finish_report();
5539
12
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5540
12
                .tag("instance_id", instance_id_)
5541
12
                .tag("num_scanned", num_scanned)
5542
12
                .tag("num_expired", num_expired)
5543
12
                .tag("num_recycled", num_recycled)
5544
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5545
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5546
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5547
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
5534
27
    DORIS_CLOUD_DEFER {
5535
27
        unregister_recycle_task(task_name);
5536
27
        int64_t cost =
5537
27
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5538
27
        metrics_context.finish_report();
5539
27
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5540
27
                .tag("instance_id", instance_id_)
5541
27
                .tag("num_scanned", num_scanned)
5542
27
                .tag("num_expired", num_expired)
5543
27
                .tag("num_recycled", num_recycled)
5544
27
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5545
27
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5546
27
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5547
27
    };
5548
5549
    // Elements in `tmp_rowset_keys` has the same lifetime as `it`
5550
5551
39
    std::vector<std::string> tmp_rowset_keys;
5552
39
    std::vector<std::string> tmp_rowset_ref_count_keys;
5553
5554
    // rowset_id -> rowset_meta
5555
    // store tmp_rowset id and meta for statistics rs size when delete
5556
39
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
5557
39
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5558
39
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
5559
39
    worker_pool->start();
5560
5561
39
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5562
5563
39
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &tmp_rowsets,
5564
39
                             &expired_rowset_size, &total_rowset_key_size, &total_rowset_value_size,
5565
39
                             &earlest_ts, &tmp_rowset_ref_count_keys, this,
5566
106k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5567
106k
        ++num_scanned;
5568
106k
        total_rowset_key_size += k.size();
5569
106k
        total_rowset_value_size += v.size();
5570
106k
        doris::RowsetMetaCloudPB rowset;
5571
106k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5572
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5573
0
            return -1;
5574
0
        }
5575
106k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5576
106k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5577
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5578
0
                   << " txn_expiration=" << rowset.txn_expiration()
5579
0
                   << " rowset_creation_time=" << rowset.creation_time();
5580
106k
        int64_t current_time = ::time(nullptr);
5581
106k
        if (current_time < expiration) { // not expired
5582
0
            return 0;
5583
0
        }
5584
5585
106k
        if (config::enable_mark_delete_rowset_before_recycle) {
5586
106k
            int mark_ret = mark_rowset_as_recycled(txn_kv_.get(), instance_id_, k, rowset);
5587
106k
            if (mark_ret == -1) {
5588
0
                LOG(WARNING) << "failed to mark rowset as recycled, instance_id=" << instance_id_
5589
0
                             << " tablet_id=" << rowset.tablet_id() << " version=["
5590
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5591
0
                return -1;
5592
106k
            } else if (mark_ret == 1) {
5593
52.0k
                LOG(INFO)
5594
52.0k
                        << "rowset already marked as recycled, recycler will delete data and kv at "
5595
52.0k
                           "next turn, instance_id="
5596
52.0k
                        << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5597
52.0k
                        << rowset.start_version() << '-' << rowset.end_version() << "]";
5598
52.0k
                return 0;
5599
52.0k
            }
5600
106k
        }
5601
5602
54.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
5603
54.0k
            LOG(INFO) << "begin to abort txn or job for related rowset, instance_id="
5604
54.0k
                      << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5605
54.0k
                      << rowset.start_version() << '-' << rowset.end_version() << "]";
5606
5607
54.0k
            int ret = abort_txn_or_job_for_recycle(rowset);
5608
54.0k
            if (ret != 0) {
5609
0
                LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
5610
0
                             << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5611
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5612
0
                return ret;
5613
0
            }
5614
54.0k
        }
5615
5616
54.0k
        ++num_expired;
5617
54.0k
        expired_rowset_size += v.size();
5618
54.0k
        if (!rowset.has_resource_id()) {
5619
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
5620
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
5621
0
                return -1;
5622
0
            }
5623
            // might be a delete pred rowset
5624
0
            tmp_rowset_keys.emplace_back(k);
5625
0
            return 0;
5626
0
        }
5627
        // TODO(plat1ko): check rowset not referenced
5628
54.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5629
54.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
5630
54.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
5631
54.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
5632
54.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
5633
54.0k
                  << " num_expired=" << num_expired
5634
54.0k
                  << " task_type=" << metrics_context.operation_type;
5635
5636
54.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
5637
        // Remove the rowset ref count key directly since it has not been used.
5638
54.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
5639
54.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
5640
54.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
5641
54.0k
                  << "key=" << hex(rowset_ref_count_key);
5642
54.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
5643
5644
54.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
5645
54.0k
        return 0;
5646
54.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5566
16
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5567
16
        ++num_scanned;
5568
16
        total_rowset_key_size += k.size();
5569
16
        total_rowset_value_size += v.size();
5570
16
        doris::RowsetMetaCloudPB rowset;
5571
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5572
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5573
0
            return -1;
5574
0
        }
5575
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5576
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5577
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5578
0
                   << " txn_expiration=" << rowset.txn_expiration()
5579
0
                   << " rowset_creation_time=" << rowset.creation_time();
5580
16
        int64_t current_time = ::time(nullptr);
5581
16
        if (current_time < expiration) { // not expired
5582
0
            return 0;
5583
0
        }
5584
5585
16
        if (config::enable_mark_delete_rowset_before_recycle) {
5586
16
            int mark_ret = mark_rowset_as_recycled(txn_kv_.get(), instance_id_, k, rowset);
5587
16
            if (mark_ret == -1) {
5588
0
                LOG(WARNING) << "failed to mark rowset as recycled, instance_id=" << instance_id_
5589
0
                             << " tablet_id=" << rowset.tablet_id() << " version=["
5590
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5591
0
                return -1;
5592
16
            } else if (mark_ret == 1) {
5593
9
                LOG(INFO)
5594
9
                        << "rowset already marked as recycled, recycler will delete data and kv at "
5595
9
                           "next turn, instance_id="
5596
9
                        << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5597
9
                        << rowset.start_version() << '-' << rowset.end_version() << "]";
5598
9
                return 0;
5599
9
            }
5600
16
        }
5601
5602
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
5603
7
            LOG(INFO) << "begin to abort txn or job for related rowset, instance_id="
5604
7
                      << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5605
7
                      << rowset.start_version() << '-' << rowset.end_version() << "]";
5606
5607
7
            int ret = abort_txn_or_job_for_recycle(rowset);
5608
7
            if (ret != 0) {
5609
0
                LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
5610
0
                             << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5611
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5612
0
                return ret;
5613
0
            }
5614
7
        }
5615
5616
7
        ++num_expired;
5617
7
        expired_rowset_size += v.size();
5618
7
        if (!rowset.has_resource_id()) {
5619
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
5620
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
5621
0
                return -1;
5622
0
            }
5623
            // might be a delete pred rowset
5624
0
            tmp_rowset_keys.emplace_back(k);
5625
0
            return 0;
5626
0
        }
5627
        // TODO(plat1ko): check rowset not referenced
5628
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5629
7
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
5630
7
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
5631
7
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
5632
7
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
5633
7
                  << " num_expired=" << num_expired
5634
7
                  << " task_type=" << metrics_context.operation_type;
5635
5636
7
        tmp_rowset_keys.emplace_back(k.data(), k.size());
5637
        // Remove the rowset ref count key directly since it has not been used.
5638
7
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
5639
7
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
5640
7
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
5641
7
                  << "key=" << hex(rowset_ref_count_key);
5642
7
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
5643
5644
7
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
5645
7
        return 0;
5646
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5566
106k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5567
106k
        ++num_scanned;
5568
106k
        total_rowset_key_size += k.size();
5569
106k
        total_rowset_value_size += v.size();
5570
106k
        doris::RowsetMetaCloudPB rowset;
5571
106k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5572
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5573
0
            return -1;
5574
0
        }
5575
106k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5576
106k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5577
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5578
0
                   << " txn_expiration=" << rowset.txn_expiration()
5579
0
                   << " rowset_creation_time=" << rowset.creation_time();
5580
106k
        int64_t current_time = ::time(nullptr);
5581
106k
        if (current_time < expiration) { // not expired
5582
0
            return 0;
5583
0
        }
5584
5585
106k
        if (config::enable_mark_delete_rowset_before_recycle) {
5586
106k
            int mark_ret = mark_rowset_as_recycled(txn_kv_.get(), instance_id_, k, rowset);
5587
106k
            if (mark_ret == -1) {
5588
0
                LOG(WARNING) << "failed to mark rowset as recycled, instance_id=" << instance_id_
5589
0
                             << " tablet_id=" << rowset.tablet_id() << " version=["
5590
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5591
0
                return -1;
5592
106k
            } else if (mark_ret == 1) {
5593
52.0k
                LOG(INFO)
5594
52.0k
                        << "rowset already marked as recycled, recycler will delete data and kv at "
5595
52.0k
                           "next turn, instance_id="
5596
52.0k
                        << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5597
52.0k
                        << rowset.start_version() << '-' << rowset.end_version() << "]";
5598
52.0k
                return 0;
5599
52.0k
            }
5600
106k
        }
5601
5602
54.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
5603
54.0k
            LOG(INFO) << "begin to abort txn or job for related rowset, instance_id="
5604
54.0k
                      << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5605
54.0k
                      << rowset.start_version() << '-' << rowset.end_version() << "]";
5606
5607
54.0k
            int ret = abort_txn_or_job_for_recycle(rowset);
5608
54.0k
            if (ret != 0) {
5609
0
                LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
5610
0
                             << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5611
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5612
0
                return ret;
5613
0
            }
5614
54.0k
        }
5615
5616
54.0k
        ++num_expired;
5617
54.0k
        expired_rowset_size += v.size();
5618
54.0k
        if (!rowset.has_resource_id()) {
5619
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
5620
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
5621
0
                return -1;
5622
0
            }
5623
            // might be a delete pred rowset
5624
0
            tmp_rowset_keys.emplace_back(k);
5625
0
            return 0;
5626
0
        }
5627
        // TODO(plat1ko): check rowset not referenced
5628
54.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5629
54.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
5630
54.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
5631
54.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
5632
54.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
5633
54.0k
                  << " num_expired=" << num_expired
5634
54.0k
                  << " task_type=" << metrics_context.operation_type;
5635
5636
54.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
5637
        // Remove the rowset ref count key directly since it has not been used.
5638
54.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
5639
54.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
5640
54.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
5641
54.0k
                  << "key=" << hex(rowset_ref_count_key);
5642
54.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
5643
5644
54.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
5645
54.0k
        return 0;
5646
54.0k
    };
5647
5648
    // TODO bacth delete
5649
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5650
51.0k
        std::string dbm_start_key =
5651
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5652
51.0k
        std::string dbm_end_key = dbm_start_key;
5653
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
5654
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5655
51.0k
        if (ret != 0) {
5656
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5657
0
                         << instance_id_ << ", tablet_id=" << tablet_id
5658
0
                         << ", rowset_id=" << rowset_id;
5659
0
        }
5660
51.0k
        return ret;
5661
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5649
7
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5650
7
        std::string dbm_start_key =
5651
7
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5652
7
        std::string dbm_end_key = dbm_start_key;
5653
7
        encode_int64(INT64_MAX, &dbm_end_key);
5654
7
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5655
7
        if (ret != 0) {
5656
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5657
0
                         << instance_id_ << ", tablet_id=" << tablet_id
5658
0
                         << ", rowset_id=" << rowset_id;
5659
0
        }
5660
7
        return ret;
5661
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5649
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5650
51.0k
        std::string dbm_start_key =
5651
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5652
51.0k
        std::string dbm_end_key = dbm_start_key;
5653
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
5654
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5655
51.0k
        if (ret != 0) {
5656
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5657
0
                         << instance_id_ << ", tablet_id=" << tablet_id
5658
0
                         << ", rowset_id=" << rowset_id;
5659
0
        }
5660
51.0k
        return ret;
5661
51.0k
    };
5662
5663
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5664
51.0k
        auto delete_bitmap_start =
5665
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
5666
51.0k
        auto delete_bitmap_end =
5667
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
5668
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
5669
51.0k
        if (ret != 0) {
5670
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
5671
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
5672
0
        }
5673
51.0k
        return ret;
5674
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5663
7
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5664
7
        auto delete_bitmap_start =
5665
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
5666
7
        auto delete_bitmap_end =
5667
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
5668
7
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
5669
7
        if (ret != 0) {
5670
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
5671
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
5672
0
        }
5673
7
        return ret;
5674
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5663
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5664
51.0k
        auto delete_bitmap_start =
5665
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
5666
51.0k
        auto delete_bitmap_end =
5667
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
5668
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
5669
51.0k
        if (ret != 0) {
5670
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
5671
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
5672
0
        }
5673
51.0k
        return ret;
5674
51.0k
    };
5675
5676
39
    auto loop_done = [&]() -> int {
5677
32
        DORIS_CLOUD_DEFER {
5678
32
            tmp_rowset_keys.clear();
5679
32
            tmp_rowsets.clear();
5680
32
            tmp_rowset_ref_count_keys.clear();
5681
32
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5677
12
        DORIS_CLOUD_DEFER {
5678
12
            tmp_rowset_keys.clear();
5679
12
            tmp_rowsets.clear();
5680
12
            tmp_rowset_ref_count_keys.clear();
5681
12
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5677
20
        DORIS_CLOUD_DEFER {
5678
20
            tmp_rowset_keys.clear();
5679
20
            tmp_rowsets.clear();
5680
20
            tmp_rowset_ref_count_keys.clear();
5681
20
        };
5682
32
        worker_pool->submit([&, tmp_rowset_keys_to_delete = tmp_rowset_keys,
5683
32
                             tmp_rowsets_to_delete = tmp_rowsets,
5684
32
                             tmp_rowset_ref_count_keys_to_delete = tmp_rowset_ref_count_keys]() {
5685
32
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5686
32
                                   metrics_context) != 0) {
5687
3
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5688
3
                return;
5689
3
            }
5690
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5691
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5692
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5693
0
                                 << rs.ShortDebugString();
5694
0
                    return;
5695
0
                }
5696
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5697
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5698
0
                                 << rs.ShortDebugString();
5699
0
                    return;
5700
0
                }
5701
51.0k
            }
5702
29
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5703
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5704
0
                return;
5705
0
            }
5706
29
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5707
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5708
0
                return;
5709
0
            }
5710
29
            num_recycled += tmp_rowset_keys.size();
5711
29
            return;
5712
29
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
5684
12
                             tmp_rowset_ref_count_keys_to_delete = tmp_rowset_ref_count_keys]() {
5685
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5686
12
                                   metrics_context) != 0) {
5687
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5688
0
                return;
5689
0
            }
5690
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5691
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5692
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5693
0
                                 << rs.ShortDebugString();
5694
0
                    return;
5695
0
                }
5696
7
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5697
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5698
0
                                 << rs.ShortDebugString();
5699
0
                    return;
5700
0
                }
5701
7
            }
5702
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5703
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5704
0
                return;
5705
0
            }
5706
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5707
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5708
0
                return;
5709
0
            }
5710
12
            num_recycled += tmp_rowset_keys.size();
5711
12
            return;
5712
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
5684
20
                             tmp_rowset_ref_count_keys_to_delete = tmp_rowset_ref_count_keys]() {
5685
20
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5686
20
                                   metrics_context) != 0) {
5687
3
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5688
3
                return;
5689
3
            }
5690
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5691
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5692
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5693
0
                                 << rs.ShortDebugString();
5694
0
                    return;
5695
0
                }
5696
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5697
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5698
0
                                 << rs.ShortDebugString();
5699
0
                    return;
5700
0
                }
5701
51.0k
            }
5702
17
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5703
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5704
0
                return;
5705
0
            }
5706
17
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5707
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5708
0
                return;
5709
0
            }
5710
17
            num_recycled += tmp_rowset_keys.size();
5711
17
            return;
5712
17
        });
5713
32
        return 0;
5714
32
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
5676
12
    auto loop_done = [&]() -> int {
5677
12
        DORIS_CLOUD_DEFER {
5678
12
            tmp_rowset_keys.clear();
5679
12
            tmp_rowsets.clear();
5680
12
            tmp_rowset_ref_count_keys.clear();
5681
12
        };
5682
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = tmp_rowset_keys,
5683
12
                             tmp_rowsets_to_delete = tmp_rowsets,
5684
12
                             tmp_rowset_ref_count_keys_to_delete = tmp_rowset_ref_count_keys]() {
5685
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5686
12
                                   metrics_context) != 0) {
5687
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5688
12
                return;
5689
12
            }
5690
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5691
12
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5692
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5693
12
                                 << rs.ShortDebugString();
5694
12
                    return;
5695
12
                }
5696
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5697
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5698
12
                                 << rs.ShortDebugString();
5699
12
                    return;
5700
12
                }
5701
12
            }
5702
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5703
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5704
12
                return;
5705
12
            }
5706
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5707
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5708
12
                return;
5709
12
            }
5710
12
            num_recycled += tmp_rowset_keys.size();
5711
12
            return;
5712
12
        });
5713
12
        return 0;
5714
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
5676
20
    auto loop_done = [&]() -> int {
5677
20
        DORIS_CLOUD_DEFER {
5678
20
            tmp_rowset_keys.clear();
5679
20
            tmp_rowsets.clear();
5680
20
            tmp_rowset_ref_count_keys.clear();
5681
20
        };
5682
20
        worker_pool->submit([&, tmp_rowset_keys_to_delete = tmp_rowset_keys,
5683
20
                             tmp_rowsets_to_delete = tmp_rowsets,
5684
20
                             tmp_rowset_ref_count_keys_to_delete = tmp_rowset_ref_count_keys]() {
5685
20
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5686
20
                                   metrics_context) != 0) {
5687
20
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5688
20
                return;
5689
20
            }
5690
20
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5691
20
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5692
20
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5693
20
                                 << rs.ShortDebugString();
5694
20
                    return;
5695
20
                }
5696
20
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5697
20
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5698
20
                                 << rs.ShortDebugString();
5699
20
                    return;
5700
20
                }
5701
20
            }
5702
20
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5703
20
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5704
20
                return;
5705
20
            }
5706
20
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5707
20
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5708
20
                return;
5709
20
            }
5710
20
            num_recycled += tmp_rowset_keys.size();
5711
20
            return;
5712
20
        });
5713
20
        return 0;
5714
20
    };
5715
5716
39
    if (config::enable_recycler_stats_metrics) {
5717
0
        scan_and_statistics_tmp_rowsets();
5718
0
    }
5719
    // recycle_func and loop_done for scan and recycle
5720
39
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
5721
39
                               std::move(loop_done));
5722
5723
39
    worker_pool->stop();
5724
5725
    // Report final metrics after all concurrent tasks completed
5726
39
    segment_metrics_context_.report();
5727
39
    metrics_context.report();
5728
5729
39
    return ret;
5730
39
}
5731
5732
int InstanceRecycler::scan_and_recycle(
5733
        std::string begin, std::string_view end,
5734
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
5735
268
        std::function<int()> loop_done) {
5736
268
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
5737
268
    int ret = 0;
5738
268
    int64_t cnt = 0;
5739
268
    int get_range_retried = 0;
5740
268
    std::string err;
5741
268
    DORIS_CLOUD_DEFER_COPY(begin, end) {
5742
268
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
5743
268
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
5744
268
                  << " ret=" << ret << " err=" << err;
5745
268
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
5741
31
    DORIS_CLOUD_DEFER_COPY(begin, end) {
5742
31
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
5743
31
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
5744
31
                  << " ret=" << ret << " err=" << err;
5745
31
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
5741
237
    DORIS_CLOUD_DEFER_COPY(begin, end) {
5742
237
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
5743
237
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
5744
237
                  << " ret=" << ret << " err=" << err;
5745
237
    };
5746
5747
268
    std::unique_ptr<RangeGetIterator> it;
5748
321
    do {
5749
321
        if (get_range_retried > 1000) {
5750
0
            err = "txn_get exceeds max retry, may not scan all keys";
5751
0
            ret = -1;
5752
0
            return -1;
5753
0
        }
5754
321
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
5755
321
        if (get_ret != 0) { // txn kv may complain "Request for future version"
5756
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
5757
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
5758
0
                         << " get_range_retried=" << get_range_retried;
5759
0
            ++get_range_retried;
5760
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
5761
0
            continue; // try again
5762
0
        }
5763
321
        if (!it->has_next()) {
5764
140
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
5765
140
            break; // scan finished
5766
140
        }
5767
154k
        while (it->has_next()) {
5768
154k
            ++cnt;
5769
            // recycle corresponding resources
5770
154k
            auto [k, v] = it->next();
5771
154k
            if (!it->has_next()) {
5772
181
                begin = k;
5773
181
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
5774
181
            }
5775
            // if we want to continue scanning, the recycle_func should not return non-zero
5776
154k
            if (recycle_func(k, v) != 0) {
5777
4.00k
                err = "recycle_func error";
5778
4.00k
                ret = -1;
5779
4.00k
            }
5780
154k
        }
5781
181
        begin.push_back('\x00'); // Update to next smallest key for iteration
5782
        // if we want to continue scanning, the recycle_func should not return non-zero
5783
181
        if (loop_done && loop_done() != 0) {
5784
4
            err = "loop_done error";
5785
4
            ret = -1;
5786
4
        }
5787
181
    } while (it->more() && !stopped());
5788
268
    return ret;
5789
268
}
5790
5791
19
int InstanceRecycler::abort_timeout_txn() {
5792
19
    const std::string task_name = "abort_timeout_txn";
5793
19
    int64_t num_scanned = 0;
5794
19
    int64_t num_timeout = 0;
5795
19
    int64_t num_abort = 0;
5796
19
    int64_t num_advance = 0;
5797
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5798
5799
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
5800
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
5801
19
    std::string begin_txn_running_key;
5802
19
    std::string end_txn_running_key;
5803
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
5804
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
5805
5806
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
5807
5808
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5809
19
    register_recycle_task(task_name, start_time);
5810
5811
19
    DORIS_CLOUD_DEFER {
5812
19
        unregister_recycle_task(task_name);
5813
19
        int64_t cost =
5814
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5815
19
        metrics_context.finish_report();
5816
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
5817
19
                .tag("instance_id", instance_id_)
5818
19
                .tag("num_scanned", num_scanned)
5819
19
                .tag("num_timeout", num_timeout)
5820
19
                .tag("num_abort", num_abort)
5821
19
                .tag("num_advance", num_advance);
5822
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
5811
3
    DORIS_CLOUD_DEFER {
5812
3
        unregister_recycle_task(task_name);
5813
3
        int64_t cost =
5814
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5815
3
        metrics_context.finish_report();
5816
3
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
5817
3
                .tag("instance_id", instance_id_)
5818
3
                .tag("num_scanned", num_scanned)
5819
3
                .tag("num_timeout", num_timeout)
5820
3
                .tag("num_abort", num_abort)
5821
3
                .tag("num_advance", num_advance);
5822
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
5811
16
    DORIS_CLOUD_DEFER {
5812
16
        unregister_recycle_task(task_name);
5813
16
        int64_t cost =
5814
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5815
16
        metrics_context.finish_report();
5816
16
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
5817
16
                .tag("instance_id", instance_id_)
5818
16
                .tag("num_scanned", num_scanned)
5819
16
                .tag("num_timeout", num_timeout)
5820
16
                .tag("num_abort", num_abort)
5821
16
                .tag("num_advance", num_advance);
5822
16
    };
5823
5824
19
    int64_t current_time =
5825
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
5826
5827
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
5828
19
                                  &current_time, &metrics_context,
5829
19
                                  this](std::string_view k, std::string_view v) -> int {
5830
9
        ++num_scanned;
5831
5832
9
        std::unique_ptr<Transaction> txn;
5833
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5834
9
        if (err != TxnErrorCode::TXN_OK) {
5835
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
5836
0
            return -1;
5837
0
        }
5838
9
        std::string_view k1 = k;
5839
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
5840
9
        k1.remove_prefix(1); // Remove key space
5841
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5842
9
        if (decode_key(&k1, &out) != 0) {
5843
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
5844
0
            return -1;
5845
0
        }
5846
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
5847
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
5848
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
5849
        // Update txn_info
5850
9
        std::string txn_inf_key, txn_inf_val;
5851
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
5852
9
        err = txn->get(txn_inf_key, &txn_inf_val);
5853
9
        if (err != TxnErrorCode::TXN_OK) {
5854
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
5855
0
            return -1;
5856
0
        }
5857
9
        TxnInfoPB txn_info;
5858
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
5859
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
5860
0
            return -1;
5861
0
        }
5862
5863
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
5864
3
            txn.reset();
5865
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
5866
3
            std::shared_ptr<TxnLazyCommitTask> task =
5867
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
5868
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
5869
3
            if (ret.first != MetaServiceCode::OK) {
5870
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
5871
0
                             << "msg=" << ret.second;
5872
0
                return -1;
5873
0
            }
5874
3
            ++num_advance;
5875
3
            return 0;
5876
6
        } else {
5877
6
            TxnRunningPB txn_running_pb;
5878
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
5879
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
5880
0
                return -1;
5881
0
            }
5882
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
5883
4
                return 0;
5884
4
            }
5885
2
            ++num_timeout;
5886
5887
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
5888
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
5889
2
            txn_info.set_finish_time(current_time);
5890
2
            txn_info.set_reason("timeout");
5891
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
5892
2
            txn_inf_val.clear();
5893
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
5894
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
5895
0
                return -1;
5896
0
            }
5897
2
            txn->put(txn_inf_key, txn_inf_val);
5898
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
5899
            // Put recycle txn key
5900
2
            std::string recyc_txn_key, recyc_txn_val;
5901
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
5902
2
            RecycleTxnPB recycle_txn_pb;
5903
2
            recycle_txn_pb.set_creation_time(current_time);
5904
2
            recycle_txn_pb.set_label(txn_info.label());
5905
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
5906
0
                LOG_WARNING("failed to serialize txn recycle info")
5907
0
                        .tag("key", hex(k))
5908
0
                        .tag("db_id", db_id)
5909
0
                        .tag("txn_id", txn_id);
5910
0
                return -1;
5911
0
            }
5912
2
            txn->put(recyc_txn_key, recyc_txn_val);
5913
            // Remove txn running key
5914
2
            txn->remove(k);
5915
2
            err = txn->commit();
5916
2
            if (err != TxnErrorCode::TXN_OK) {
5917
0
                LOG_WARNING("failed to commit txn err={}", err)
5918
0
                        .tag("key", hex(k))
5919
0
                        .tag("db_id", db_id)
5920
0
                        .tag("txn_id", txn_id);
5921
0
                return -1;
5922
0
            }
5923
2
            metrics_context.total_recycled_num = ++num_abort;
5924
2
            metrics_context.report();
5925
2
        }
5926
5927
2
        return 0;
5928
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5829
3
                                  this](std::string_view k, std::string_view v) -> int {
5830
3
        ++num_scanned;
5831
5832
3
        std::unique_ptr<Transaction> txn;
5833
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5834
3
        if (err != TxnErrorCode::TXN_OK) {
5835
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
5836
0
            return -1;
5837
0
        }
5838
3
        std::string_view k1 = k;
5839
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
5840
3
        k1.remove_prefix(1); // Remove key space
5841
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5842
3
        if (decode_key(&k1, &out) != 0) {
5843
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
5844
0
            return -1;
5845
0
        }
5846
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
5847
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
5848
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
5849
        // Update txn_info
5850
3
        std::string txn_inf_key, txn_inf_val;
5851
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
5852
3
        err = txn->get(txn_inf_key, &txn_inf_val);
5853
3
        if (err != TxnErrorCode::TXN_OK) {
5854
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
5855
0
            return -1;
5856
0
        }
5857
3
        TxnInfoPB txn_info;
5858
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
5859
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
5860
0
            return -1;
5861
0
        }
5862
5863
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
5864
3
            txn.reset();
5865
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
5866
3
            std::shared_ptr<TxnLazyCommitTask> task =
5867
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
5868
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
5869
3
            if (ret.first != MetaServiceCode::OK) {
5870
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
5871
0
                             << "msg=" << ret.second;
5872
0
                return -1;
5873
0
            }
5874
3
            ++num_advance;
5875
3
            return 0;
5876
3
        } else {
5877
0
            TxnRunningPB txn_running_pb;
5878
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
5879
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
5880
0
                return -1;
5881
0
            }
5882
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
5883
0
                return 0;
5884
0
            }
5885
0
            ++num_timeout;
5886
5887
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
5888
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
5889
0
            txn_info.set_finish_time(current_time);
5890
0
            txn_info.set_reason("timeout");
5891
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
5892
0
            txn_inf_val.clear();
5893
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
5894
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
5895
0
                return -1;
5896
0
            }
5897
0
            txn->put(txn_inf_key, txn_inf_val);
5898
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
5899
            // Put recycle txn key
5900
0
            std::string recyc_txn_key, recyc_txn_val;
5901
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
5902
0
            RecycleTxnPB recycle_txn_pb;
5903
0
            recycle_txn_pb.set_creation_time(current_time);
5904
0
            recycle_txn_pb.set_label(txn_info.label());
5905
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
5906
0
                LOG_WARNING("failed to serialize txn recycle info")
5907
0
                        .tag("key", hex(k))
5908
0
                        .tag("db_id", db_id)
5909
0
                        .tag("txn_id", txn_id);
5910
0
                return -1;
5911
0
            }
5912
0
            txn->put(recyc_txn_key, recyc_txn_val);
5913
            // Remove txn running key
5914
0
            txn->remove(k);
5915
0
            err = txn->commit();
5916
0
            if (err != TxnErrorCode::TXN_OK) {
5917
0
                LOG_WARNING("failed to commit txn err={}", err)
5918
0
                        .tag("key", hex(k))
5919
0
                        .tag("db_id", db_id)
5920
0
                        .tag("txn_id", txn_id);
5921
0
                return -1;
5922
0
            }
5923
0
            metrics_context.total_recycled_num = ++num_abort;
5924
0
            metrics_context.report();
5925
0
        }
5926
5927
0
        return 0;
5928
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5829
6
                                  this](std::string_view k, std::string_view v) -> int {
5830
6
        ++num_scanned;
5831
5832
6
        std::unique_ptr<Transaction> txn;
5833
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5834
6
        if (err != TxnErrorCode::TXN_OK) {
5835
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
5836
0
            return -1;
5837
0
        }
5838
6
        std::string_view k1 = k;
5839
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
5840
6
        k1.remove_prefix(1); // Remove key space
5841
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5842
6
        if (decode_key(&k1, &out) != 0) {
5843
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
5844
0
            return -1;
5845
0
        }
5846
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
5847
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
5848
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
5849
        // Update txn_info
5850
6
        std::string txn_inf_key, txn_inf_val;
5851
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
5852
6
        err = txn->get(txn_inf_key, &txn_inf_val);
5853
6
        if (err != TxnErrorCode::TXN_OK) {
5854
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
5855
0
            return -1;
5856
0
        }
5857
6
        TxnInfoPB txn_info;
5858
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
5859
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
5860
0
            return -1;
5861
0
        }
5862
5863
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
5864
0
            txn.reset();
5865
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
5866
0
            std::shared_ptr<TxnLazyCommitTask> task =
5867
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
5868
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
5869
0
            if (ret.first != MetaServiceCode::OK) {
5870
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
5871
0
                             << "msg=" << ret.second;
5872
0
                return -1;
5873
0
            }
5874
0
            ++num_advance;
5875
0
            return 0;
5876
6
        } else {
5877
6
            TxnRunningPB txn_running_pb;
5878
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
5879
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
5880
0
                return -1;
5881
0
            }
5882
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
5883
4
                return 0;
5884
4
            }
5885
2
            ++num_timeout;
5886
5887
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
5888
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
5889
2
            txn_info.set_finish_time(current_time);
5890
2
            txn_info.set_reason("timeout");
5891
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
5892
2
            txn_inf_val.clear();
5893
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
5894
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
5895
0
                return -1;
5896
0
            }
5897
2
            txn->put(txn_inf_key, txn_inf_val);
5898
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
5899
            // Put recycle txn key
5900
2
            std::string recyc_txn_key, recyc_txn_val;
5901
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
5902
2
            RecycleTxnPB recycle_txn_pb;
5903
2
            recycle_txn_pb.set_creation_time(current_time);
5904
2
            recycle_txn_pb.set_label(txn_info.label());
5905
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
5906
0
                LOG_WARNING("failed to serialize txn recycle info")
5907
0
                        .tag("key", hex(k))
5908
0
                        .tag("db_id", db_id)
5909
0
                        .tag("txn_id", txn_id);
5910
0
                return -1;
5911
0
            }
5912
2
            txn->put(recyc_txn_key, recyc_txn_val);
5913
            // Remove txn running key
5914
2
            txn->remove(k);
5915
2
            err = txn->commit();
5916
2
            if (err != TxnErrorCode::TXN_OK) {
5917
0
                LOG_WARNING("failed to commit txn err={}", err)
5918
0
                        .tag("key", hex(k))
5919
0
                        .tag("db_id", db_id)
5920
0
                        .tag("txn_id", txn_id);
5921
0
                return -1;
5922
0
            }
5923
2
            metrics_context.total_recycled_num = ++num_abort;
5924
2
            metrics_context.report();
5925
2
        }
5926
5927
2
        return 0;
5928
6
    };
5929
5930
19
    if (config::enable_recycler_stats_metrics) {
5931
0
        scan_and_statistics_abort_timeout_txn();
5932
0
    }
5933
    // recycle_func and loop_done for scan and recycle
5934
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
5935
19
                            std::move(handle_txn_running_kv));
5936
19
}
5937
5938
19
int InstanceRecycler::recycle_expired_txn_label() {
5939
19
    const std::string task_name = "recycle_expired_txn_label";
5940
19
    int64_t num_scanned = 0;
5941
19
    int64_t num_expired = 0;
5942
19
    std::atomic_long num_recycled = 0;
5943
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5944
19
    int ret = 0;
5945
5946
19
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
5947
19
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
5948
19
    std::string begin_recycle_txn_key;
5949
19
    std::string end_recycle_txn_key;
5950
19
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
5951
19
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
5952
19
    std::vector<std::string> recycle_txn_info_keys;
5953
5954
19
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
5955
5956
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5957
19
    register_recycle_task(task_name, start_time);
5958
19
    DORIS_CLOUD_DEFER {
5959
19
        unregister_recycle_task(task_name);
5960
19
        int64_t cost =
5961
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5962
19
        metrics_context.finish_report();
5963
19
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
5964
19
                .tag("instance_id", instance_id_)
5965
19
                .tag("num_scanned", num_scanned)
5966
19
                .tag("num_expired", num_expired)
5967
19
                .tag("num_recycled", num_recycled);
5968
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
5958
1
    DORIS_CLOUD_DEFER {
5959
1
        unregister_recycle_task(task_name);
5960
1
        int64_t cost =
5961
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5962
1
        metrics_context.finish_report();
5963
1
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
5964
1
                .tag("instance_id", instance_id_)
5965
1
                .tag("num_scanned", num_scanned)
5966
1
                .tag("num_expired", num_expired)
5967
1
                .tag("num_recycled", num_recycled);
5968
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
5958
18
    DORIS_CLOUD_DEFER {
5959
18
        unregister_recycle_task(task_name);
5960
18
        int64_t cost =
5961
18
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5962
18
        metrics_context.finish_report();
5963
18
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
5964
18
                .tag("instance_id", instance_id_)
5965
18
                .tag("num_scanned", num_scanned)
5966
18
                .tag("num_expired", num_expired)
5967
18
                .tag("num_recycled", num_recycled);
5968
18
    };
5969
5970
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5971
5972
19
    SyncExecutor<int> concurrent_delete_executor(
5973
19
            _thread_pool_group.s3_producer_pool,
5974
19
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
5975
23.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
5975
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
5975
23.0k
            [](const int& ret) { return ret != 0; });
5976
5977
19
    int64_t current_time_ms =
5978
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
5979
5980
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
5981
30.0k
        ++num_scanned;
5982
30.0k
        RecycleTxnPB recycle_txn_pb;
5983
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
5984
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
5985
0
            return -1;
5986
0
        }
5987
30.0k
        if ((config::force_immediate_recycle) ||
5988
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
5989
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
5990
30.0k
             current_time_ms)) {
5991
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
5992
23.0k
            num_expired++;
5993
23.0k
            recycle_txn_info_keys.emplace_back(k);
5994
23.0k
        }
5995
30.0k
        return 0;
5996
30.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5980
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
5981
1
        ++num_scanned;
5982
1
        RecycleTxnPB recycle_txn_pb;
5983
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
5984
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
5985
0
            return -1;
5986
0
        }
5987
1
        if ((config::force_immediate_recycle) ||
5988
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
5989
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
5990
1
             current_time_ms)) {
5991
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
5992
1
            num_expired++;
5993
1
            recycle_txn_info_keys.emplace_back(k);
5994
1
        }
5995
1
        return 0;
5996
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5980
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
5981
30.0k
        ++num_scanned;
5982
30.0k
        RecycleTxnPB recycle_txn_pb;
5983
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
5984
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
5985
0
            return -1;
5986
0
        }
5987
30.0k
        if ((config::force_immediate_recycle) ||
5988
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
5989
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
5990
30.0k
             current_time_ms)) {
5991
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
5992
23.0k
            num_expired++;
5993
23.0k
            recycle_txn_info_keys.emplace_back(k);
5994
23.0k
        }
5995
30.0k
        return 0;
5996
30.0k
    };
5997
5998
    // int 0 for success, 1 for conflict, -1 for error
5999
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6000
23.0k
        std::string_view k1 = k;
6001
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6002
23.0k
        k1.remove_prefix(1); // Remove key space
6003
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6004
23.0k
        int ret = decode_key(&k1, &out);
6005
23.0k
        if (ret != 0) {
6006
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6007
0
            return -1;
6008
0
        }
6009
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6010
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6011
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6012
23.0k
        std::unique_ptr<Transaction> txn;
6013
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6014
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6015
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6016
0
            return -1;
6017
0
        }
6018
        // Remove txn index kv
6019
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6020
23.0k
        txn->remove(index_key);
6021
        // Remove txn info kv
6022
23.0k
        std::string info_key, info_val;
6023
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6024
23.0k
        err = txn->get(info_key, &info_val);
6025
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6026
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6027
0
            return -1;
6028
0
        }
6029
23.0k
        TxnInfoPB txn_info;
6030
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6031
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6032
0
            return -1;
6033
0
        }
6034
23.0k
        txn->remove(info_key);
6035
        // Remove sub txn index kvs
6036
23.0k
        std::vector<std::string> sub_txn_index_keys;
6037
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6038
23.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6039
23.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6040
23.0k
        }
6041
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6042
23.0k
            txn->remove(sub_txn_index_key);
6043
23.0k
        }
6044
        // Update txn label
6045
23.0k
        std::string label_key, label_val;
6046
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6047
23.0k
        err = txn->get(label_key, &label_val);
6048
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6049
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6050
0
                         << " err=" << err;
6051
0
            return -1;
6052
0
        }
6053
23.0k
        TxnLabelPB txn_label;
6054
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6055
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6056
0
            return -1;
6057
0
        }
6058
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6059
23.0k
        if (it != txn_label.txn_ids().end()) {
6060
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6061
23.0k
        }
6062
23.0k
        if (txn_label.txn_ids().empty()) {
6063
23.0k
            txn->remove(label_key);
6064
23.0k
            TEST_SYNC_POINT_CALLBACK(
6065
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6066
23.0k
        } else {
6067
73
            if (!txn_label.SerializeToString(&label_val)) {
6068
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6069
0
                return -1;
6070
0
            }
6071
73
            TEST_SYNC_POINT_CALLBACK(
6072
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6073
73
            txn->atomic_set_ver_value(label_key, label_val);
6074
73
            TEST_SYNC_POINT_CALLBACK(
6075
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6076
73
        }
6077
        // Remove recycle txn kv
6078
23.0k
        txn->remove(k);
6079
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6080
23.0k
        err = txn->commit();
6081
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6082
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6083
62
                TEST_SYNC_POINT_CALLBACK(
6084
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6085
                // log the txn_id and label
6086
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6087
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6088
62
                             << " txn_label=" << txn_info.label();
6089
62
                return 1;
6090
62
            }
6091
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6092
0
            return -1;
6093
62
        }
6094
23.0k
        ++num_recycled;
6095
6096
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6097
23.0k
        return 0;
6098
23.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5999
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6000
1
        std::string_view k1 = k;
6001
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6002
1
        k1.remove_prefix(1); // Remove key space
6003
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6004
1
        int ret = decode_key(&k1, &out);
6005
1
        if (ret != 0) {
6006
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6007
0
            return -1;
6008
0
        }
6009
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6010
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6011
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6012
1
        std::unique_ptr<Transaction> txn;
6013
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6014
1
        if (err != TxnErrorCode::TXN_OK) {
6015
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6016
0
            return -1;
6017
0
        }
6018
        // Remove txn index kv
6019
1
        auto index_key = txn_index_key({instance_id_, txn_id});
6020
1
        txn->remove(index_key);
6021
        // Remove txn info kv
6022
1
        std::string info_key, info_val;
6023
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6024
1
        err = txn->get(info_key, &info_val);
6025
1
        if (err != TxnErrorCode::TXN_OK) {
6026
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6027
0
            return -1;
6028
0
        }
6029
1
        TxnInfoPB txn_info;
6030
1
        if (!txn_info.ParseFromString(info_val)) {
6031
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6032
0
            return -1;
6033
0
        }
6034
1
        txn->remove(info_key);
6035
        // Remove sub txn index kvs
6036
1
        std::vector<std::string> sub_txn_index_keys;
6037
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6038
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6039
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
6040
0
        }
6041
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6042
0
            txn->remove(sub_txn_index_key);
6043
0
        }
6044
        // Update txn label
6045
1
        std::string label_key, label_val;
6046
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6047
1
        err = txn->get(label_key, &label_val);
6048
1
        if (err != TxnErrorCode::TXN_OK) {
6049
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6050
0
                         << " err=" << err;
6051
0
            return -1;
6052
0
        }
6053
1
        TxnLabelPB txn_label;
6054
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6055
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6056
0
            return -1;
6057
0
        }
6058
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6059
1
        if (it != txn_label.txn_ids().end()) {
6060
1
            txn_label.mutable_txn_ids()->erase(it);
6061
1
        }
6062
1
        if (txn_label.txn_ids().empty()) {
6063
1
            txn->remove(label_key);
6064
1
            TEST_SYNC_POINT_CALLBACK(
6065
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6066
1
        } else {
6067
0
            if (!txn_label.SerializeToString(&label_val)) {
6068
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6069
0
                return -1;
6070
0
            }
6071
0
            TEST_SYNC_POINT_CALLBACK(
6072
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6073
0
            txn->atomic_set_ver_value(label_key, label_val);
6074
0
            TEST_SYNC_POINT_CALLBACK(
6075
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6076
0
        }
6077
        // Remove recycle txn kv
6078
1
        txn->remove(k);
6079
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6080
1
        err = txn->commit();
6081
1
        if (err != TxnErrorCode::TXN_OK) {
6082
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
6083
0
                TEST_SYNC_POINT_CALLBACK(
6084
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6085
                // log the txn_id and label
6086
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6087
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6088
0
                             << " txn_label=" << txn_info.label();
6089
0
                return 1;
6090
0
            }
6091
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6092
0
            return -1;
6093
0
        }
6094
1
        ++num_recycled;
6095
6096
1
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6097
1
        return 0;
6098
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5999
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6000
23.0k
        std::string_view k1 = k;
6001
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6002
23.0k
        k1.remove_prefix(1); // Remove key space
6003
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6004
23.0k
        int ret = decode_key(&k1, &out);
6005
23.0k
        if (ret != 0) {
6006
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6007
0
            return -1;
6008
0
        }
6009
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6010
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6011
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6012
23.0k
        std::unique_ptr<Transaction> txn;
6013
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6014
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6015
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6016
0
            return -1;
6017
0
        }
6018
        // Remove txn index kv
6019
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6020
23.0k
        txn->remove(index_key);
6021
        // Remove txn info kv
6022
23.0k
        std::string info_key, info_val;
6023
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6024
23.0k
        err = txn->get(info_key, &info_val);
6025
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6026
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6027
0
            return -1;
6028
0
        }
6029
23.0k
        TxnInfoPB txn_info;
6030
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6031
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6032
0
            return -1;
6033
0
        }
6034
23.0k
        txn->remove(info_key);
6035
        // Remove sub txn index kvs
6036
23.0k
        std::vector<std::string> sub_txn_index_keys;
6037
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6038
23.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6039
23.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6040
23.0k
        }
6041
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6042
23.0k
            txn->remove(sub_txn_index_key);
6043
23.0k
        }
6044
        // Update txn label
6045
23.0k
        std::string label_key, label_val;
6046
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6047
23.0k
        err = txn->get(label_key, &label_val);
6048
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6049
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6050
0
                         << " err=" << err;
6051
0
            return -1;
6052
0
        }
6053
23.0k
        TxnLabelPB txn_label;
6054
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6055
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6056
0
            return -1;
6057
0
        }
6058
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6059
23.0k
        if (it != txn_label.txn_ids().end()) {
6060
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6061
23.0k
        }
6062
23.0k
        if (txn_label.txn_ids().empty()) {
6063
23.0k
            txn->remove(label_key);
6064
23.0k
            TEST_SYNC_POINT_CALLBACK(
6065
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6066
23.0k
        } else {
6067
73
            if (!txn_label.SerializeToString(&label_val)) {
6068
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6069
0
                return -1;
6070
0
            }
6071
73
            TEST_SYNC_POINT_CALLBACK(
6072
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6073
73
            txn->atomic_set_ver_value(label_key, label_val);
6074
73
            TEST_SYNC_POINT_CALLBACK(
6075
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6076
73
        }
6077
        // Remove recycle txn kv
6078
23.0k
        txn->remove(k);
6079
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6080
23.0k
        err = txn->commit();
6081
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6082
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6083
62
                TEST_SYNC_POINT_CALLBACK(
6084
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6085
                // log the txn_id and label
6086
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6087
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6088
62
                             << " txn_label=" << txn_info.label();
6089
62
                return 1;
6090
62
            }
6091
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6092
0
            return -1;
6093
62
        }
6094
23.0k
        ++num_recycled;
6095
6096
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6097
23.0k
        return 0;
6098
23.0k
    };
6099
6100
19
    auto loop_done = [&]() -> int {
6101
10
        DORIS_CLOUD_DEFER {
6102
10
            recycle_txn_info_keys.clear();
6103
10
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6101
1
        DORIS_CLOUD_DEFER {
6102
1
            recycle_txn_info_keys.clear();
6103
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6101
9
        DORIS_CLOUD_DEFER {
6102
9
            recycle_txn_info_keys.clear();
6103
9
        };
6104
10
        TEST_SYNC_POINT_CALLBACK(
6105
10
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6106
10
                &recycle_txn_info_keys);
6107
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6108
23.0k
            concurrent_delete_executor.add([&]() {
6109
23.0k
                int ret = delete_recycle_txn_kv(k);
6110
23.0k
                if (ret == 1) {
6111
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6112
54
                    for (int i = 1; i <= max_retry; ++i) {
6113
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6114
54
                        ret = delete_recycle_txn_kv(k);
6115
                        // clang-format off
6116
54
                        TEST_SYNC_POINT_CALLBACK(
6117
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6118
                        // clang-format off
6119
54
                        if (ret != 1) {
6120
18
                            break;
6121
18
                        }
6122
                        // random sleep 0-100 ms to retry
6123
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6124
36
                    }
6125
18
                }
6126
23.0k
                if (ret != 0) {
6127
9
                    LOG_WARNING("failed to delete recycle txn kv")
6128
9
                            .tag("instance id", instance_id_)
6129
9
                            .tag("key", hex(k));
6130
9
                    return -1;
6131
9
                }
6132
23.0k
                return 0;
6133
23.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6108
1
            concurrent_delete_executor.add([&]() {
6109
1
                int ret = delete_recycle_txn_kv(k);
6110
1
                if (ret == 1) {
6111
0
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6112
0
                    for (int i = 1; i <= max_retry; ++i) {
6113
0
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6114
0
                        ret = delete_recycle_txn_kv(k);
6115
                        // clang-format off
6116
0
                        TEST_SYNC_POINT_CALLBACK(
6117
0
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6118
                        // clang-format off
6119
0
                        if (ret != 1) {
6120
0
                            break;
6121
0
                        }
6122
                        // random sleep 0-100 ms to retry
6123
0
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6124
0
                    }
6125
0
                }
6126
1
                if (ret != 0) {
6127
0
                    LOG_WARNING("failed to delete recycle txn kv")
6128
0
                            .tag("instance id", instance_id_)
6129
0
                            .tag("key", hex(k));
6130
0
                    return -1;
6131
0
                }
6132
1
                return 0;
6133
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6108
23.0k
            concurrent_delete_executor.add([&]() {
6109
23.0k
                int ret = delete_recycle_txn_kv(k);
6110
23.0k
                if (ret == 1) {
6111
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6112
54
                    for (int i = 1; i <= max_retry; ++i) {
6113
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6114
54
                        ret = delete_recycle_txn_kv(k);
6115
                        // clang-format off
6116
54
                        TEST_SYNC_POINT_CALLBACK(
6117
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6118
                        // clang-format off
6119
54
                        if (ret != 1) {
6120
18
                            break;
6121
18
                        }
6122
                        // random sleep 0-100 ms to retry
6123
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6124
36
                    }
6125
18
                }
6126
23.0k
                if (ret != 0) {
6127
9
                    LOG_WARNING("failed to delete recycle txn kv")
6128
9
                            .tag("instance id", instance_id_)
6129
9
                            .tag("key", hex(k));
6130
9
                    return -1;
6131
9
                }
6132
23.0k
                return 0;
6133
23.0k
            });
6134
23.0k
        }
6135
10
        bool finished = true;
6136
10
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6137
23.0k
        for (int r : rets) {
6138
23.0k
            if (r != 0) {
6139
9
                ret = -1;
6140
9
            }
6141
23.0k
        }
6142
6143
10
        ret = finished ? ret : -1;
6144
6145
        // Update metrics after all concurrent tasks completed
6146
10
        metrics_context.total_recycled_num = num_recycled.load();
6147
10
        metrics_context.report();
6148
6149
10
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6150
6151
10
        if (ret != 0) {
6152
3
            LOG_WARNING("recycle txn kv ret!=0")
6153
3
                    .tag("finished", finished)
6154
3
                    .tag("ret", ret)
6155
3
                    .tag("instance_id", instance_id_);
6156
3
            return ret;
6157
3
        }
6158
7
        return ret;
6159
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6100
1
    auto loop_done = [&]() -> int {
6101
1
        DORIS_CLOUD_DEFER {
6102
1
            recycle_txn_info_keys.clear();
6103
1
        };
6104
1
        TEST_SYNC_POINT_CALLBACK(
6105
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6106
1
                &recycle_txn_info_keys);
6107
1
        for (const auto& k : recycle_txn_info_keys) {
6108
1
            concurrent_delete_executor.add([&]() {
6109
1
                int ret = delete_recycle_txn_kv(k);
6110
1
                if (ret == 1) {
6111
1
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6112
1
                    for (int i = 1; i <= max_retry; ++i) {
6113
1
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6114
1
                        ret = delete_recycle_txn_kv(k);
6115
                        // clang-format off
6116
1
                        TEST_SYNC_POINT_CALLBACK(
6117
1
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6118
                        // clang-format off
6119
1
                        if (ret != 1) {
6120
1
                            break;
6121
1
                        }
6122
                        // random sleep 0-100 ms to retry
6123
1
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6124
1
                    }
6125
1
                }
6126
1
                if (ret != 0) {
6127
1
                    LOG_WARNING("failed to delete recycle txn kv")
6128
1
                            .tag("instance id", instance_id_)
6129
1
                            .tag("key", hex(k));
6130
1
                    return -1;
6131
1
                }
6132
1
                return 0;
6133
1
            });
6134
1
        }
6135
1
        bool finished = true;
6136
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6137
1
        for (int r : rets) {
6138
1
            if (r != 0) {
6139
0
                ret = -1;
6140
0
            }
6141
1
        }
6142
6143
1
        ret = finished ? ret : -1;
6144
6145
        // Update metrics after all concurrent tasks completed
6146
1
        metrics_context.total_recycled_num = num_recycled.load();
6147
1
        metrics_context.report();
6148
6149
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6150
6151
1
        if (ret != 0) {
6152
0
            LOG_WARNING("recycle txn kv ret!=0")
6153
0
                    .tag("finished", finished)
6154
0
                    .tag("ret", ret)
6155
0
                    .tag("instance_id", instance_id_);
6156
0
            return ret;
6157
0
        }
6158
1
        return ret;
6159
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6100
9
    auto loop_done = [&]() -> int {
6101
9
        DORIS_CLOUD_DEFER {
6102
9
            recycle_txn_info_keys.clear();
6103
9
        };
6104
9
        TEST_SYNC_POINT_CALLBACK(
6105
9
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6106
9
                &recycle_txn_info_keys);
6107
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6108
23.0k
            concurrent_delete_executor.add([&]() {
6109
23.0k
                int ret = delete_recycle_txn_kv(k);
6110
23.0k
                if (ret == 1) {
6111
23.0k
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6112
23.0k
                    for (int i = 1; i <= max_retry; ++i) {
6113
23.0k
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6114
23.0k
                        ret = delete_recycle_txn_kv(k);
6115
                        // clang-format off
6116
23.0k
                        TEST_SYNC_POINT_CALLBACK(
6117
23.0k
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6118
                        // clang-format off
6119
23.0k
                        if (ret != 1) {
6120
23.0k
                            break;
6121
23.0k
                        }
6122
                        // random sleep 0-100 ms to retry
6123
23.0k
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6124
23.0k
                    }
6125
23.0k
                }
6126
23.0k
                if (ret != 0) {
6127
23.0k
                    LOG_WARNING("failed to delete recycle txn kv")
6128
23.0k
                            .tag("instance id", instance_id_)
6129
23.0k
                            .tag("key", hex(k));
6130
23.0k
                    return -1;
6131
23.0k
                }
6132
23.0k
                return 0;
6133
23.0k
            });
6134
23.0k
        }
6135
9
        bool finished = true;
6136
9
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6137
23.0k
        for (int r : rets) {
6138
23.0k
            if (r != 0) {
6139
9
                ret = -1;
6140
9
            }
6141
23.0k
        }
6142
6143
9
        ret = finished ? ret : -1;
6144
6145
        // Update metrics after all concurrent tasks completed
6146
9
        metrics_context.total_recycled_num = num_recycled.load();
6147
9
        metrics_context.report();
6148
6149
9
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6150
6151
9
        if (ret != 0) {
6152
3
            LOG_WARNING("recycle txn kv ret!=0")
6153
3
                    .tag("finished", finished)
6154
3
                    .tag("ret", ret)
6155
3
                    .tag("instance_id", instance_id_);
6156
3
            return ret;
6157
3
        }
6158
6
        return ret;
6159
9
    };
6160
6161
19
    if (config::enable_recycler_stats_metrics) {
6162
0
        scan_and_statistics_expired_txn_label();
6163
0
    }
6164
    // recycle_func and loop_done for scan and recycle
6165
19
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
6166
19
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
6167
19
}
6168
6169
struct CopyJobIdTuple {
6170
    std::string instance_id;
6171
    std::string stage_id;
6172
    long table_id;
6173
    std::string copy_id;
6174
    std::string stage_path;
6175
};
6176
struct BatchObjStoreAccessor {
6177
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
6178
                          TxnKv* txn_kv)
6179
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
6180
3
    ~BatchObjStoreAccessor() {
6181
3
        if (!paths_.empty()) {
6182
3
            consume();
6183
3
        }
6184
3
    }
6185
6186
    /**
6187
    * To implicitely do batch work and submit the batch delete task to s3
6188
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
6189
    *
6190
    * @param copy_job The protubuf struct consists of the copy job files.
6191
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
6192
    *            it would last until we finish the delete task, here we need pass one string value
6193
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
6194
    */
6195
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
6196
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
6197
5
        auto& file_keys = copy_file_keys_[key];
6198
5
        file_keys.log_trace =
6199
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
6200
5
                            instance_id, stage_id, table_id, copy_id, path);
6201
5
        std::string_view log_trace = file_keys.log_trace;
6202
2.03k
        for (const auto& file : copy_job.object_files()) {
6203
2.03k
            auto relative_path = file.relative_path();
6204
2.03k
            paths_.push_back(relative_path);
6205
2.03k
            file_keys.keys.push_back(copy_file_key(
6206
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
6207
2.03k
            LOG_INFO(log_trace)
6208
2.03k
                    .tag("relative_path", relative_path)
6209
2.03k
                    .tag("batch_count", batch_count_);
6210
2.03k
        }
6211
5
        LOG_INFO(log_trace)
6212
5
                .tag("objects_num", copy_job.object_files().size())
6213
5
                .tag("batch_count", batch_count_);
6214
        // 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
6215
        // recommend using delete objects when objects num is less than 10)
6216
5
        if (paths_.size() < 1000) {
6217
3
            return;
6218
3
        }
6219
2
        consume();
6220
2
    }
6221
6222
private:
6223
5
    void consume() {
6224
5
        DORIS_CLOUD_DEFER {
6225
5
            paths_.clear();
6226
5
            copy_file_keys_.clear();
6227
5
            batch_count_++;
6228
6229
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
6230
5
                        batch_count_);
6231
5
        };
6232
6233
5
        StopWatch sw;
6234
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
6235
5
        if (0 != accessor_->delete_files(paths_)) {
6236
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
6237
2
                        paths_.size(), batch_count_, sw.elapsed_us());
6238
2
            return;
6239
2
        }
6240
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
6241
3
                    paths_.size(), batch_count_, sw.elapsed_us());
6242
        // delete fdb's keys
6243
3
        for (auto& file_keys : copy_file_keys_) {
6244
3
            auto& [log_trace, keys] = file_keys.second;
6245
3
            std::unique_ptr<Transaction> txn;
6246
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
6247
0
                LOG(WARNING) << "failed to create txn";
6248
0
                continue;
6249
0
            }
6250
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6251
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6252
            // limited, should not cause the txn commit failed.
6253
1.02k
            for (const auto& key : keys) {
6254
1.02k
                txn->remove(key);
6255
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
6256
1.02k
            }
6257
3
            txn->remove(file_keys.first);
6258
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
6259
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
6260
0
                continue;
6261
0
            }
6262
3
        }
6263
3
    }
6264
    std::shared_ptr<StorageVaultAccessor> accessor_;
6265
    // the path of the s3 files to be deleted
6266
    std::vector<std::string> paths_;
6267
    struct CopyFiles {
6268
        std::string log_trace;
6269
        std::vector<std::string> keys;
6270
    };
6271
    // pair<std::string, std::vector<std::string>>
6272
    // first: instance_id_ stage_id table_id query_id
6273
    // second: keys to be deleted
6274
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
6275
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
6276
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
6277
    // which can together uniquely identifies different tasks for tracing log
6278
    uint64_t& batch_count_;
6279
    TxnKv* txn_kv_;
6280
};
6281
6282
13
int InstanceRecycler::recycle_copy_jobs() {
6283
13
    int64_t num_scanned = 0;
6284
13
    int64_t num_finished = 0;
6285
13
    int64_t num_expired = 0;
6286
13
    int64_t num_recycled = 0;
6287
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
6288
13
    uint64_t batch_count = 0;
6289
13
    const std::string task_name = "recycle_copy_jobs";
6290
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6291
6292
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
6293
6294
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6295
13
    register_recycle_task(task_name, start_time);
6296
6297
13
    DORIS_CLOUD_DEFER {
6298
13
        unregister_recycle_task(task_name);
6299
13
        int64_t cost =
6300
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6301
13
        metrics_context.finish_report();
6302
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
6303
13
                .tag("instance_id", instance_id_)
6304
13
                .tag("num_scanned", num_scanned)
6305
13
                .tag("num_finished", num_finished)
6306
13
                .tag("num_expired", num_expired)
6307
13
                .tag("num_recycled", num_recycled);
6308
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
6297
13
    DORIS_CLOUD_DEFER {
6298
13
        unregister_recycle_task(task_name);
6299
13
        int64_t cost =
6300
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6301
13
        metrics_context.finish_report();
6302
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
6303
13
                .tag("instance_id", instance_id_)
6304
13
                .tag("num_scanned", num_scanned)
6305
13
                .tag("num_finished", num_finished)
6306
13
                .tag("num_expired", num_expired)
6307
13
                .tag("num_recycled", num_recycled);
6308
13
    };
6309
6310
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
6311
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
6312
13
    std::string key0;
6313
13
    std::string key1;
6314
13
    copy_job_key(key_info0, &key0);
6315
13
    copy_job_key(key_info1, &key1);
6316
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
6317
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
6318
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
6319
16
                         this](std::string_view k, std::string_view v) -> int {
6320
16
        ++num_scanned;
6321
16
        CopyJobPB copy_job;
6322
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
6323
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
6324
0
            return -1;
6325
0
        }
6326
6327
        // decode copy job key
6328
16
        auto k1 = k;
6329
16
        k1.remove_prefix(1);
6330
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6331
16
        decode_key(&k1, &out);
6332
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
6333
        // -> CopyJobPB
6334
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
6335
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
6336
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
6337
6338
16
        bool check_storage = true;
6339
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
6340
12
            ++num_finished;
6341
6342
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
6343
7
                auto it = stage_accessor_map.find(stage_id);
6344
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
6345
7
                std::string_view path;
6346
7
                if (it != stage_accessor_map.end()) {
6347
2
                    accessor = it->second;
6348
5
                } else {
6349
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
6350
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
6351
5
                                                      &inner_accessor);
6352
5
                    if (ret < 0) { // error
6353
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
6354
0
                        return -1;
6355
5
                    } else if (ret == 0) {
6356
3
                        path = inner_accessor->uri();
6357
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
6358
3
                                inner_accessor, batch_count, txn_kv_.get());
6359
3
                        stage_accessor_map.emplace(stage_id, accessor);
6360
3
                    } else { // stage not found, skip check storage
6361
2
                        check_storage = false;
6362
2
                    }
6363
5
                }
6364
7
                if (check_storage) {
6365
                    // TODO delete objects with key and etag is not supported
6366
5
                    accessor->add(std::move(copy_job), std::string(k),
6367
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
6368
5
                    return 0;
6369
5
                }
6370
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
6371
5
                int64_t current_time =
6372
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6373
5
                if (copy_job.finish_time_ms() > 0) {
6374
2
                    if (!config::force_immediate_recycle &&
6375
2
                        current_time < copy_job.finish_time_ms() +
6376
2
                                               config::copy_job_max_retention_second * 1000) {
6377
1
                        return 0;
6378
1
                    }
6379
3
                } else {
6380
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
6381
3
                    if (!config::force_immediate_recycle &&
6382
3
                        current_time < copy_job.start_time_ms() +
6383
3
                                               config::copy_job_max_retention_second * 1000) {
6384
1
                        return 0;
6385
1
                    }
6386
3
                }
6387
5
            }
6388
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
6389
4
            int64_t current_time =
6390
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6391
            // if copy job is timeout: delete all copy file kvs and copy job kv
6392
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
6393
2
                return 0;
6394
2
            }
6395
2
            ++num_expired;
6396
2
        }
6397
6398
        // delete all copy files
6399
7
        std::vector<std::string> copy_file_keys;
6400
70
        for (auto& file : copy_job.object_files()) {
6401
70
            copy_file_keys.push_back(copy_file_key(
6402
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
6403
70
        }
6404
7
        std::unique_ptr<Transaction> txn;
6405
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
6406
0
            LOG(WARNING) << "failed to create txn";
6407
0
            return -1;
6408
0
        }
6409
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6410
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6411
        // limited, should not cause the txn commit failed.
6412
70
        for (const auto& key : copy_file_keys) {
6413
70
            txn->remove(key);
6414
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
6415
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
6416
70
                      << ", query_id=" << copy_id;
6417
70
        }
6418
7
        txn->remove(k);
6419
7
        TxnErrorCode err = txn->commit();
6420
7
        if (err != TxnErrorCode::TXN_OK) {
6421
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
6422
0
            return -1;
6423
0
        }
6424
6425
7
        metrics_context.total_recycled_num = ++num_recycled;
6426
7
        metrics_context.report();
6427
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6428
7
        return 0;
6429
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
6319
16
                         this](std::string_view k, std::string_view v) -> int {
6320
16
        ++num_scanned;
6321
16
        CopyJobPB copy_job;
6322
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
6323
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
6324
0
            return -1;
6325
0
        }
6326
6327
        // decode copy job key
6328
16
        auto k1 = k;
6329
16
        k1.remove_prefix(1);
6330
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6331
16
        decode_key(&k1, &out);
6332
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
6333
        // -> CopyJobPB
6334
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
6335
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
6336
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
6337
6338
16
        bool check_storage = true;
6339
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
6340
12
            ++num_finished;
6341
6342
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
6343
7
                auto it = stage_accessor_map.find(stage_id);
6344
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
6345
7
                std::string_view path;
6346
7
                if (it != stage_accessor_map.end()) {
6347
2
                    accessor = it->second;
6348
5
                } else {
6349
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
6350
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
6351
5
                                                      &inner_accessor);
6352
5
                    if (ret < 0) { // error
6353
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
6354
0
                        return -1;
6355
5
                    } else if (ret == 0) {
6356
3
                        path = inner_accessor->uri();
6357
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
6358
3
                                inner_accessor, batch_count, txn_kv_.get());
6359
3
                        stage_accessor_map.emplace(stage_id, accessor);
6360
3
                    } else { // stage not found, skip check storage
6361
2
                        check_storage = false;
6362
2
                    }
6363
5
                }
6364
7
                if (check_storage) {
6365
                    // TODO delete objects with key and etag is not supported
6366
5
                    accessor->add(std::move(copy_job), std::string(k),
6367
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
6368
5
                    return 0;
6369
5
                }
6370
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
6371
5
                int64_t current_time =
6372
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6373
5
                if (copy_job.finish_time_ms() > 0) {
6374
2
                    if (!config::force_immediate_recycle &&
6375
2
                        current_time < copy_job.finish_time_ms() +
6376
2
                                               config::copy_job_max_retention_second * 1000) {
6377
1
                        return 0;
6378
1
                    }
6379
3
                } else {
6380
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
6381
3
                    if (!config::force_immediate_recycle &&
6382
3
                        current_time < copy_job.start_time_ms() +
6383
3
                                               config::copy_job_max_retention_second * 1000) {
6384
1
                        return 0;
6385
1
                    }
6386
3
                }
6387
5
            }
6388
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
6389
4
            int64_t current_time =
6390
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6391
            // if copy job is timeout: delete all copy file kvs and copy job kv
6392
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
6393
2
                return 0;
6394
2
            }
6395
2
            ++num_expired;
6396
2
        }
6397
6398
        // delete all copy files
6399
7
        std::vector<std::string> copy_file_keys;
6400
70
        for (auto& file : copy_job.object_files()) {
6401
70
            copy_file_keys.push_back(copy_file_key(
6402
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
6403
70
        }
6404
7
        std::unique_ptr<Transaction> txn;
6405
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
6406
0
            LOG(WARNING) << "failed to create txn";
6407
0
            return -1;
6408
0
        }
6409
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6410
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6411
        // limited, should not cause the txn commit failed.
6412
70
        for (const auto& key : copy_file_keys) {
6413
70
            txn->remove(key);
6414
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
6415
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
6416
70
                      << ", query_id=" << copy_id;
6417
70
        }
6418
7
        txn->remove(k);
6419
7
        TxnErrorCode err = txn->commit();
6420
7
        if (err != TxnErrorCode::TXN_OK) {
6421
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
6422
0
            return -1;
6423
0
        }
6424
6425
7
        metrics_context.total_recycled_num = ++num_recycled;
6426
7
        metrics_context.report();
6427
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6428
7
        return 0;
6429
7
    };
6430
6431
13
    if (config::enable_recycler_stats_metrics) {
6432
0
        scan_and_statistics_copy_jobs();
6433
0
    }
6434
    // recycle_func and loop_done for scan and recycle
6435
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
6436
13
}
6437
6438
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
6439
                                             const StagePB::StageType& stage_type,
6440
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
6441
5
#ifdef UNIT_TEST
6442
    // In unit test, external use the same accessor as the internal stage
6443
5
    auto it = accessor_map_.find(stage_id);
6444
5
    if (it != accessor_map_.end()) {
6445
3
        *accessor = it->second;
6446
3
    } else {
6447
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
6448
2
        return 1;
6449
2
    }
6450
#else
6451
    // init s3 accessor and add to accessor map
6452
    auto stage_it =
6453
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
6454
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
6455
6456
    if (stage_it == instance_info_.stages().end()) {
6457
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
6458
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
6459
        return 1;
6460
    }
6461
6462
    const auto& object_store_info = stage_it->obj_info();
6463
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
6464
6465
    S3Conf s3_conf;
6466
    if (stage_type == StagePB::EXTERNAL) {
6467
        if (stage_access_type == StagePB::AKSK) {
6468
            auto conf = S3Conf::from_obj_store_info(object_store_info);
6469
            if (!conf) {
6470
                return -1;
6471
            }
6472
6473
            s3_conf = std::move(*conf);
6474
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
6475
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
6476
            if (!conf) {
6477
                return -1;
6478
            }
6479
6480
            s3_conf = std::move(*conf);
6481
            if (instance_info_.ram_user().has_encryption_info()) {
6482
                AkSkPair plain_ak_sk_pair;
6483
                int ret = decrypt_ak_sk_helper(
6484
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
6485
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
6486
                if (ret != 0) {
6487
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
6488
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
6489
                    return -1;
6490
                }
6491
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
6492
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
6493
            } else {
6494
                s3_conf.ak = instance_info_.ram_user().ak();
6495
                s3_conf.sk = instance_info_.ram_user().sk();
6496
            }
6497
        } else {
6498
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
6499
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
6500
            return -1;
6501
        }
6502
    } else if (stage_type == StagePB::INTERNAL) {
6503
        int idx = stoi(object_store_info.id());
6504
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6505
            LOG(WARNING) << "invalid idx: " << idx;
6506
            return -1;
6507
        }
6508
6509
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
6510
        auto conf = S3Conf::from_obj_store_info(old_obj);
6511
        if (!conf) {
6512
            return -1;
6513
        }
6514
6515
        s3_conf = std::move(*conf);
6516
        s3_conf.prefix = object_store_info.prefix();
6517
    } else {
6518
        LOG(WARNING) << "unknown stage type " << stage_type;
6519
        return -1;
6520
    }
6521
6522
    std::shared_ptr<S3Accessor> s3_accessor;
6523
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
6524
    if (ret != 0) {
6525
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
6526
        return -1;
6527
    }
6528
6529
    *accessor = std::move(s3_accessor);
6530
#endif
6531
3
    return 0;
6532
5
}
6533
6534
11
int InstanceRecycler::recycle_stage() {
6535
11
    int64_t num_scanned = 0;
6536
11
    int64_t num_recycled = 0;
6537
11
    const std::string task_name = "recycle_stage";
6538
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6539
6540
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
6541
6542
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6543
11
    register_recycle_task(task_name, start_time);
6544
6545
11
    DORIS_CLOUD_DEFER {
6546
11
        unregister_recycle_task(task_name);
6547
11
        int64_t cost =
6548
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6549
11
        metrics_context.finish_report();
6550
11
        LOG_WARNING("recycle stage, cost={}s", cost)
6551
11
                .tag("instance_id", instance_id_)
6552
11
                .tag("num_scanned", num_scanned)
6553
11
                .tag("num_recycled", num_recycled);
6554
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
6545
11
    DORIS_CLOUD_DEFER {
6546
11
        unregister_recycle_task(task_name);
6547
11
        int64_t cost =
6548
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6549
11
        metrics_context.finish_report();
6550
11
        LOG_WARNING("recycle stage, cost={}s", cost)
6551
11
                .tag("instance_id", instance_id_)
6552
11
                .tag("num_scanned", num_scanned)
6553
11
                .tag("num_recycled", num_recycled);
6554
11
    };
6555
6556
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
6557
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
6558
11
    std::string key0 = recycle_stage_key(key_info0);
6559
11
    std::string key1 = recycle_stage_key(key_info1);
6560
6561
11
    std::vector<std::string_view> stage_keys;
6562
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
6563
11
                         this](std::string_view k, std::string_view v) -> int {
6564
1
        ++num_scanned;
6565
1
        RecycleStagePB recycle_stage;
6566
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
6567
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
6568
0
            return -1;
6569
0
        }
6570
6571
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
6572
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6573
0
            LOG(WARNING) << "invalid idx: " << idx;
6574
0
            return -1;
6575
0
        }
6576
6577
1
        std::shared_ptr<StorageVaultAccessor> accessor;
6578
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
6579
1
                [&] {
6580
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
6581
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
6582
1
                    if (!s3_conf) {
6583
1
                        return -1;
6584
1
                    }
6585
6586
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
6587
1
                    std::shared_ptr<S3Accessor> s3_accessor;
6588
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
6589
1
                    if (ret != 0) {
6590
1
                        return -1;
6591
1
                    }
6592
6593
1
                    accessor = std::move(s3_accessor);
6594
1
                    return 0;
6595
1
                }(),
6596
1
                "recycle_stage:get_accessor", &accessor);
6597
6598
1
        if (ret != 0) {
6599
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
6600
0
            return ret;
6601
0
        }
6602
6603
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
6604
1
                .tag("instance_id", instance_id_)
6605
1
                .tag("stage_id", recycle_stage.stage().stage_id())
6606
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
6607
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
6608
1
                .tag("obj_info_id", idx)
6609
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
6610
1
        ret = accessor->delete_all();
6611
1
        if (ret != 0) {
6612
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
6613
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
6614
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
6615
0
                         << ", ret=" << ret;
6616
0
            return -1;
6617
0
        }
6618
1
        metrics_context.total_recycled_num = ++num_recycled;
6619
1
        metrics_context.report();
6620
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
6621
1
        stage_keys.push_back(k);
6622
1
        return 0;
6623
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6563
1
                         this](std::string_view k, std::string_view v) -> int {
6564
1
        ++num_scanned;
6565
1
        RecycleStagePB recycle_stage;
6566
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
6567
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
6568
0
            return -1;
6569
0
        }
6570
6571
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
6572
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6573
0
            LOG(WARNING) << "invalid idx: " << idx;
6574
0
            return -1;
6575
0
        }
6576
6577
1
        std::shared_ptr<StorageVaultAccessor> accessor;
6578
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
6579
1
                [&] {
6580
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
6581
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
6582
1
                    if (!s3_conf) {
6583
1
                        return -1;
6584
1
                    }
6585
6586
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
6587
1
                    std::shared_ptr<S3Accessor> s3_accessor;
6588
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
6589
1
                    if (ret != 0) {
6590
1
                        return -1;
6591
1
                    }
6592
6593
1
                    accessor = std::move(s3_accessor);
6594
1
                    return 0;
6595
1
                }(),
6596
1
                "recycle_stage:get_accessor", &accessor);
6597
6598
1
        if (ret != 0) {
6599
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
6600
0
            return ret;
6601
0
        }
6602
6603
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
6604
1
                .tag("instance_id", instance_id_)
6605
1
                .tag("stage_id", recycle_stage.stage().stage_id())
6606
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
6607
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
6608
1
                .tag("obj_info_id", idx)
6609
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
6610
1
        ret = accessor->delete_all();
6611
1
        if (ret != 0) {
6612
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
6613
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
6614
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
6615
0
                         << ", ret=" << ret;
6616
0
            return -1;
6617
0
        }
6618
1
        metrics_context.total_recycled_num = ++num_recycled;
6619
1
        metrics_context.report();
6620
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
6621
1
        stage_keys.push_back(k);
6622
1
        return 0;
6623
1
    };
6624
6625
11
    auto loop_done = [&stage_keys, this]() -> int {
6626
1
        if (stage_keys.empty()) return 0;
6627
1
        DORIS_CLOUD_DEFER {
6628
1
            stage_keys.clear();
6629
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6627
1
        DORIS_CLOUD_DEFER {
6628
1
            stage_keys.clear();
6629
1
        };
6630
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
6631
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
6632
0
            return -1;
6633
0
        }
6634
1
        return 0;
6635
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
6625
1
    auto loop_done = [&stage_keys, this]() -> int {
6626
1
        if (stage_keys.empty()) return 0;
6627
1
        DORIS_CLOUD_DEFER {
6628
1
            stage_keys.clear();
6629
1
        };
6630
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
6631
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
6632
0
            return -1;
6633
0
        }
6634
1
        return 0;
6635
1
    };
6636
11
    if (config::enable_recycler_stats_metrics) {
6637
0
        scan_and_statistics_stage();
6638
0
    }
6639
    // recycle_func and loop_done for scan and recycle
6640
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
6641
11
}
6642
6643
10
int InstanceRecycler::recycle_expired_stage_objects() {
6644
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
6645
6646
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6647
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
6648
6649
10
    DORIS_CLOUD_DEFER {
6650
10
        int64_t cost =
6651
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6652
10
        metrics_context.finish_report();
6653
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
6654
10
                .tag("instance_id", instance_id_);
6655
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
6649
10
    DORIS_CLOUD_DEFER {
6650
10
        int64_t cost =
6651
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6652
10
        metrics_context.finish_report();
6653
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
6654
10
                .tag("instance_id", instance_id_);
6655
10
    };
6656
6657
10
    int ret = 0;
6658
6659
10
    if (config::enable_recycler_stats_metrics) {
6660
0
        scan_and_statistics_expired_stage_objects();
6661
0
    }
6662
6663
10
    for (const auto& stage : instance_info_.stages()) {
6664
0
        std::stringstream ss;
6665
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
6666
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
6667
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
6668
0
           << ", prefix=" << stage.obj_info().prefix();
6669
6670
0
        if (stopped()) {
6671
0
            break;
6672
0
        }
6673
0
        if (stage.type() == StagePB::EXTERNAL) {
6674
0
            continue;
6675
0
        }
6676
0
        int idx = stoi(stage.obj_info().id());
6677
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6678
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
6679
0
            continue;
6680
0
        }
6681
6682
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
6683
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
6684
0
        if (!s3_conf) {
6685
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
6686
0
            continue;
6687
0
        }
6688
6689
0
        s3_conf->prefix = stage.obj_info().prefix();
6690
0
        std::shared_ptr<S3Accessor> accessor;
6691
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
6692
0
        if (ret1 != 0) {
6693
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
6694
0
            ret = -1;
6695
0
            continue;
6696
0
        }
6697
6698
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
6699
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
6700
0
            ret = -1;
6701
0
            continue;
6702
0
        }
6703
6704
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
6705
0
        int64_t expiration_time =
6706
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
6707
0
                config::internal_stage_objects_expire_time_second;
6708
0
        if (config::force_immediate_recycle) {
6709
0
            expiration_time = INT64_MAX;
6710
0
        }
6711
0
        ret1 = accessor->delete_all(expiration_time);
6712
0
        if (ret1 != 0) {
6713
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
6714
0
                         << ss.str();
6715
0
            ret = -1;
6716
0
            continue;
6717
0
        }
6718
0
        metrics_context.total_recycled_num++;
6719
0
        metrics_context.report();
6720
0
    }
6721
10
    return ret;
6722
10
}
6723
6724
193
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
6725
193
    std::lock_guard lock(recycle_tasks_mutex);
6726
193
    running_recycle_tasks[task_name] = start_time;
6727
193
}
6728
6729
193
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
6730
193
    std::lock_guard lock(recycle_tasks_mutex);
6731
193
    DCHECK(running_recycle_tasks[task_name] > 0);
6732
193
    running_recycle_tasks.erase(task_name);
6733
193
}
6734
6735
21
bool InstanceRecycler::check_recycle_tasks() {
6736
21
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
6737
21
    {
6738
21
        std::lock_guard lock(recycle_tasks_mutex);
6739
21
        tmp_running_recycle_tasks = running_recycle_tasks;
6740
21
    }
6741
6742
21
    bool found = false;
6743
21
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6744
21
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
6745
20
        int64_t cost = now - start_time;
6746
20
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
6747
20
            LOG_INFO("recycle task cost too much time cost={}s", cost)
6748
20
                    .tag("instance_id", instance_id_)
6749
20
                    .tag("task", task_name);
6750
20
            found = true;
6751
20
        }
6752
20
    }
6753
6754
21
    return found;
6755
21
}
6756
6757
// Scan and statistics indexes that need to be recycled
6758
0
int InstanceRecycler::scan_and_statistics_indexes() {
6759
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
6760
6761
0
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
6762
0
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
6763
0
    std::string index_key0;
6764
0
    std::string index_key1;
6765
0
    recycle_index_key(index_key_info0, &index_key0);
6766
0
    recycle_index_key(index_key_info1, &index_key1);
6767
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6768
6769
0
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
6770
0
        RecycleIndexPB index_pb;
6771
0
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
6772
0
            return 0;
6773
0
        }
6774
0
        int64_t current_time = ::time(nullptr);
6775
0
        if (current_time <
6776
0
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
6777
0
            return 0;
6778
0
        }
6779
        // decode index_id
6780
0
        auto k1 = k;
6781
0
        k1.remove_prefix(1);
6782
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6783
0
        decode_key(&k1, &out);
6784
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
6785
0
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
6786
0
        std::unique_ptr<Transaction> txn;
6787
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6788
0
        if (err != TxnErrorCode::TXN_OK) {
6789
0
            return 0;
6790
0
        }
6791
0
        std::string val;
6792
0
        err = txn->get(k, &val);
6793
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6794
0
            return 0;
6795
0
        }
6796
0
        if (err != TxnErrorCode::TXN_OK) {
6797
0
            return 0;
6798
0
        }
6799
0
        index_pb.Clear();
6800
0
        if (!index_pb.ParseFromString(val)) {
6801
0
            return 0;
6802
0
        }
6803
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
6804
0
            return 0;
6805
0
        }
6806
0
        metrics_context.total_need_recycle_num++;
6807
0
        return 0;
6808
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_
6809
6810
0
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
6811
0
    metrics_context.report(true);
6812
0
    segment_metrics_context_.report(true);
6813
0
    tablet_metrics_context_.report(true);
6814
0
    return ret;
6815
0
}
6816
6817
// Scan and statistics partitions that need to be recycled
6818
0
int InstanceRecycler::scan_and_statistics_partitions() {
6819
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
6820
6821
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
6822
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
6823
0
    std::string part_key0;
6824
0
    std::string part_key1;
6825
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6826
6827
0
    recycle_partition_key(part_key_info0, &part_key0);
6828
0
    recycle_partition_key(part_key_info1, &part_key1);
6829
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
6830
0
        RecyclePartitionPB part_pb;
6831
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
6832
0
            return 0;
6833
0
        }
6834
0
        int64_t current_time = ::time(nullptr);
6835
0
        if (current_time <
6836
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
6837
0
            return 0;
6838
0
        }
6839
        // decode partition_id
6840
0
        auto k1 = k;
6841
0
        k1.remove_prefix(1);
6842
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6843
0
        decode_key(&k1, &out);
6844
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
6845
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
6846
        // Change state to RECYCLING
6847
0
        std::unique_ptr<Transaction> txn;
6848
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6849
0
        if (err != TxnErrorCode::TXN_OK) {
6850
0
            return 0;
6851
0
        }
6852
0
        std::string val;
6853
0
        err = txn->get(k, &val);
6854
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6855
0
            return 0;
6856
0
        }
6857
0
        if (err != TxnErrorCode::TXN_OK) {
6858
0
            return 0;
6859
0
        }
6860
0
        part_pb.Clear();
6861
0
        if (!part_pb.ParseFromString(val)) {
6862
0
            return 0;
6863
0
        }
6864
        // Partitions with PREPARED state MUST have no data
6865
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
6866
0
        int ret = 0;
6867
0
        for (int64_t index_id : part_pb.index_id()) {
6868
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
6869
0
                                            partition_id, is_empty_tablet) != 0) {
6870
0
                ret = 0;
6871
0
            }
6872
0
        }
6873
0
        metrics_context.total_need_recycle_num++;
6874
0
        return ret;
6875
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_
6876
6877
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
6878
0
    metrics_context.report(true);
6879
0
    segment_metrics_context_.report(true);
6880
0
    tablet_metrics_context_.report(true);
6881
0
    return ret;
6882
0
}
6883
6884
// Scan and statistics rowsets that need to be recycled
6885
0
int InstanceRecycler::scan_and_statistics_rowsets() {
6886
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
6887
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
6888
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
6889
0
    std::string recyc_rs_key0;
6890
0
    std::string recyc_rs_key1;
6891
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
6892
0
                recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
6893
0
       int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6894
6895
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6896
0
        RecycleRowsetPB rowset;
6897
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6898
0
            return 0;
6899
0
        }
6900
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
6901
0
        int64_t current_time = ::time(nullptr);
6902
0
        if (current_time <
6903
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
6904
0
            return 0;
6905
0
        }
6906
6907
0
        if (!rowset.has_type()) {
6908
0
            if (!rowset.has_resource_id()) [[unlikely]] {
6909
0
                return 0;
6910
0
            }
6911
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6912
0
                return 0;
6913
0
            }
6914
0
            metrics_context.total_need_recycle_num++;
6915
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
6916
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
6917
0
            segment_metrics_context_.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
6918
0
            return 0;
6919
0
        }
6920
6921
0
        if(!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled()) {
6922
0
            return 0;
6923
0
        }
6924
6925
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
6926
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
6927
0
                return 0;
6928
0
            }
6929
0
        }
6930
0
        metrics_context.total_need_recycle_num++;
6931
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
6932
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
6933
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
6934
0
        return 0;
6935
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_
6936
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
6937
0
    metrics_context.report(true);
6938
0
    segment_metrics_context_.report(true);
6939
0
    return ret;
6940
0
}
6941
6942
// Scan and statistics tmp_rowsets that need to be recycled
6943
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
6944
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
6945
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
6946
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
6947
0
    std::string tmp_rs_key0;
6948
0
    std::string tmp_rs_key1;
6949
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
6950
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
6951
6952
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6953
6954
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
6955
0
        doris::RowsetMetaCloudPB rowset;
6956
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6957
0
            return 0;
6958
0
        }
6959
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6960
0
        int64_t current_time = ::time(nullptr);
6961
0
        if (current_time < expiration) {
6962
0
            return 0;
6963
0
        }
6964
6965
0
        DCHECK_GT(rowset.txn_id(), 0)
6966
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
6967
6968
0
        if(!rowset.has_is_recycled() || !rowset.is_recycled()) {
6969
0
            return 0;
6970
0
        }
6971
6972
0
        if (!rowset.has_resource_id()) {
6973
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6974
0
                return 0;
6975
0
            }
6976
0
            return 0;
6977
0
        }
6978
6979
0
        metrics_context.total_need_recycle_num++;
6980
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
6981
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
6982
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
6983
0
        return 0;
6984
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_
6985
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
6986
0
    metrics_context.report(true);
6987
0
    segment_metrics_context_.report(true);
6988
0
    return ret;
6989
0
}
6990
6991
// Scan and statistics abort_timeout_txn that need to be recycled
6992
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
6993
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
6994
6995
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6996
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6997
0
    std::string begin_txn_running_key;
6998
0
    std::string end_txn_running_key;
6999
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
7000
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
7001
7002
0
    int64_t current_time =
7003
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7004
7005
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
7006
0
                                               std::string_view k, std::string_view v) -> int {
7007
0
        std::unique_ptr<Transaction> txn;
7008
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7009
0
        if (err != TxnErrorCode::TXN_OK) {
7010
0
            return 0;
7011
0
        }
7012
0
        std::string_view k1 = k;
7013
0
        k1.remove_prefix(1);
7014
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7015
0
        if (decode_key(&k1, &out) != 0) {
7016
0
            return 0;
7017
0
        }
7018
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7019
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7020
        // Update txn_info
7021
0
        std::string txn_inf_key, txn_inf_val;
7022
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
7023
0
        err = txn->get(txn_inf_key, &txn_inf_val);
7024
0
        if (err != TxnErrorCode::TXN_OK) {
7025
0
            return 0;
7026
0
        }
7027
0
        TxnInfoPB txn_info;
7028
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
7029
0
            return 0;
7030
0
        }
7031
7032
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
7033
0
            TxnRunningPB txn_running_pb;
7034
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7035
0
                return 0;
7036
0
            }
7037
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7038
0
                return 0;
7039
0
            }
7040
0
            metrics_context.total_need_recycle_num++;
7041
0
        }
7042
0
        return 0;
7043
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_
7044
7045
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key, std::move(handle_abort_timeout_txn_kv));
7046
0
    metrics_context.report(true);
7047
0
    return ret;
7048
0
}
7049
7050
// Scan and statistics expired_txn_label that need to be recycled
7051
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
7052
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
7053
7054
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7055
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7056
0
    std::string begin_recycle_txn_key;
7057
0
    std::string end_recycle_txn_key;
7058
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7059
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7060
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7061
0
    int64_t current_time_ms =
7062
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7063
7064
    // for calculate the total num or bytes of recyled objects
7065
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
7066
0
        RecycleTxnPB recycle_txn_pb;
7067
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7068
0
            return 0;
7069
0
        }
7070
0
        if ((config::force_immediate_recycle) ||
7071
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7072
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7073
0
             current_time_ms)) {
7074
0
            metrics_context.total_need_recycle_num++;
7075
0
        }
7076
0
        return 0;
7077
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_
7078
7079
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key, std::move(handle_expired_txn_label_kv));
7080
0
    metrics_context.report(true);
7081
0
    return ret;
7082
0
}
7083
7084
// Scan and statistics copy_jobs that need to be recycled
7085
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
7086
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
7087
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7088
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7089
0
    std::string key0;
7090
0
    std::string key1;
7091
0
    copy_job_key(key_info0, &key0);
7092
0
    copy_job_key(key_info1, &key1);
7093
7094
    // for calculate the total num or bytes of recyled objects
7095
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
7096
0
        CopyJobPB copy_job;
7097
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7098
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7099
0
            return 0;
7100
0
        }
7101
7102
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7103
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
7104
0
                int64_t current_time =
7105
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7106
0
                if (copy_job.finish_time_ms() > 0) {
7107
0
                    if (!config::force_immediate_recycle &&
7108
0
                        current_time < copy_job.finish_time_ms() +
7109
0
                                               config::copy_job_max_retention_second * 1000) {
7110
0
                        return 0;
7111
0
                    }
7112
0
                } else {
7113
0
                    if (!config::force_immediate_recycle &&
7114
0
                        current_time < copy_job.start_time_ms() +
7115
0
                                               config::copy_job_max_retention_second * 1000) {
7116
0
                        return 0;
7117
0
                    }
7118
0
                }
7119
0
            }
7120
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7121
0
            int64_t current_time =
7122
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7123
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7124
0
                return 0;
7125
0
            }
7126
0
        }
7127
0
        metrics_context.total_need_recycle_num++;
7128
0
        return 0;
7129
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_
7130
7131
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7132
0
    metrics_context.report(true);
7133
0
    return ret;
7134
0
}
7135
7136
// Scan and statistics stage that need to be recycled
7137
0
int InstanceRecycler::scan_and_statistics_stage() {
7138
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
7139
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7140
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7141
0
    std::string key0 = recycle_stage_key(key_info0);
7142
0
    std::string key1 = recycle_stage_key(key_info1);
7143
7144
    // for calculate the total num or bytes of recyled objects
7145
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
7146
0
                                                        std::string_view v) -> int {
7147
0
        RecycleStagePB recycle_stage;
7148
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7149
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7150
0
            return 0;
7151
0
        }
7152
7153
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
7154
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7155
0
            LOG(WARNING) << "invalid idx: " << idx;
7156
0
            return 0;
7157
0
        }
7158
7159
0
        std::shared_ptr<StorageVaultAccessor> accessor;
7160
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7161
0
                [&] {
7162
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7163
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7164
0
                    if (!s3_conf) {
7165
0
                        return 0;
7166
0
                    }
7167
7168
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7169
0
                    std::shared_ptr<S3Accessor> s3_accessor;
7170
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7171
0
                    if (ret != 0) {
7172
0
                        return 0;
7173
0
                    }
7174
7175
0
                    accessor = std::move(s3_accessor);
7176
0
                    return 0;
7177
0
                }(),
7178
0
                "recycle_stage:get_accessor", &accessor);
7179
7180
0
        if (ret != 0) {
7181
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7182
0
            return 0;
7183
0
        }
7184
7185
0
        metrics_context.total_need_recycle_num++;
7186
0
        return 0;
7187
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_
7188
7189
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7190
0
    metrics_context.report(true);
7191
0
    return ret;
7192
0
}
7193
7194
// Scan and statistics expired_stage_objects that need to be recycled
7195
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
7196
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7197
7198
    // for calculate the total num or bytes of recyled objects
7199
0
    auto scan_and_statistics = [&metrics_context, this]() {
7200
0
        for (const auto& stage : instance_info_.stages()) {
7201
0
            if (stopped()) {
7202
0
                break;
7203
0
            }
7204
0
            if (stage.type() == StagePB::EXTERNAL) {
7205
0
                continue;
7206
0
            }
7207
0
            int idx = stoi(stage.obj_info().id());
7208
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
7209
0
                continue;
7210
0
            }
7211
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
7212
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7213
0
            if (!s3_conf) {
7214
0
                continue;
7215
0
            }
7216
0
            s3_conf->prefix = stage.obj_info().prefix();
7217
0
            std::shared_ptr<S3Accessor> accessor;
7218
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
7219
0
            if (ret1 != 0) {
7220
0
                continue;
7221
0
            }
7222
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7223
0
                continue;
7224
0
            }
7225
0
            metrics_context.total_need_recycle_num++;
7226
0
        }
7227
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
7228
7229
0
    scan_and_statistics();
7230
0
    metrics_context.report(true);
7231
0
    return 0;
7232
0
}
7233
7234
// Scan and statistics versions that need to be recycled
7235
0
int InstanceRecycler::scan_and_statistics_versions() {
7236
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
7237
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
7238
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
7239
7240
0
    int64_t last_scanned_table_id = 0;
7241
0
    bool is_recycled = false; // Is last scanned kv recycled
7242
    // for calculate the total num or bytes of recyled objects
7243
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
7244
0
                                       std::string_view k, std::string_view) {
7245
0
        auto k1 = k;
7246
0
        k1.remove_prefix(1);
7247
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
7248
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7249
0
        decode_key(&k1, &out);
7250
0
        DCHECK_EQ(out.size(), 6) << k;
7251
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
7252
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
7253
0
            metrics_context.total_need_recycle_num +=
7254
0
                    is_recycled; // Version kv of this table has been recycled
7255
0
            return 0;
7256
0
        }
7257
0
        last_scanned_table_id = table_id;
7258
0
        is_recycled = false;
7259
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
7260
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
7261
0
        std::unique_ptr<Transaction> txn;
7262
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7263
0
        if (err != TxnErrorCode::TXN_OK) {
7264
0
            return 0;
7265
0
        }
7266
0
        std::unique_ptr<RangeGetIterator> iter;
7267
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
7268
0
        if (err != TxnErrorCode::TXN_OK) {
7269
0
            return 0;
7270
0
        }
7271
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
7272
0
            return 0;
7273
0
        }
7274
0
        metrics_context.total_need_recycle_num++;
7275
0
        is_recycled = true;
7276
0
        return 0;
7277
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_
7278
7279
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
7280
0
    metrics_context.report(true);
7281
0
    return ret;
7282
0
}
7283
7284
// Scan and statistics restore jobs that need to be recycled
7285
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
7286
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
7287
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
7288
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
7289
0
    std::string restore_job_key0;
7290
0
    std::string restore_job_key1;
7291
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
7292
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
7293
7294
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7295
7296
    // for calculate the total num or bytes of recyled objects
7297
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
7298
0
        RestoreJobCloudPB restore_job_pb;
7299
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
7300
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
7301
0
            return 0;
7302
0
        }
7303
0
        int64_t expiration =
7304
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
7305
0
        int64_t current_time = ::time(nullptr);
7306
0
        if (current_time < expiration) { // not expired
7307
0
            return 0;
7308
0
        }
7309
0
        metrics_context.total_need_recycle_num++;
7310
0
        if(restore_job_pb.need_recycle_data()) {
7311
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
7312
0
        }
7313
0
        return 0;
7314
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_
7315
7316
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
7317
0
    metrics_context.report(true);
7318
0
    return ret;
7319
0
}
7320
7321
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
7322
3
    if (!should_recycle_versioned_keys()) {
7323
0
        return;
7324
0
    }
7325
7326
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
7327
7328
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
7329
3
    if (recycle_checker.init() != 0) {
7330
0
        return;
7331
0
    }
7332
7333
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
7334
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
7335
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
7336
7337
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
7338
8
    for (; iter->valid(); iter->next()) {
7339
5
        OperationLogPB operation_log;
7340
5
        if (!iter->parse_value(&operation_log)) {
7341
0
            continue;
7342
0
        }
7343
7344
5
        std::string_view key = iter->key();
7345
5
        Versionstamp log_versionstamp;
7346
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
7347
0
            continue;
7348
0
        }
7349
7350
5
        OperationLogReferenceInfo ref_info;
7351
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
7352
5
                                         &ref_info)) {
7353
4
            metrics_context.total_need_recycle_num++;
7354
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
7355
4
        }
7356
5
    }
7357
7358
3
    metrics_context.report(true);
7359
3
}
7360
7361
int InstanceRecycler::classify_rowset_task_by_ref_count(
7362
60
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
7363
60
    constexpr int MAX_RETRY = 10;
7364
60
    const auto& rowset_meta = task.rowset_meta;
7365
60
    int64_t tablet_id = rowset_meta.tablet_id();
7366
60
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
7367
60
    std::string_view reference_instance_id = instance_id_;
7368
60
    if (rowset_meta.has_reference_instance_id()) {
7369
5
        reference_instance_id = rowset_meta.reference_instance_id();
7370
5
    }
7371
7372
61
    for (int i = 0; i < MAX_RETRY; ++i) {
7373
61
        std::unique_ptr<Transaction> txn;
7374
61
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7375
61
        if (err != TxnErrorCode::TXN_OK) {
7376
0
            LOG_WARNING("failed to create txn when classifying rowset task")
7377
0
                    .tag("instance_id", instance_id_)
7378
0
                    .tag("tablet_id", tablet_id)
7379
0
                    .tag("rowset_id", rowset_id)
7380
0
                    .tag("err", err);
7381
0
            return -1;
7382
0
        }
7383
7384
61
        std::string rowset_ref_count_key =
7385
61
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
7386
61
        task.rowset_ref_count_key = rowset_ref_count_key;
7387
7388
61
        int64_t ref_count = 0;
7389
61
        {
7390
61
            std::string value;
7391
61
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
7392
61
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7393
0
                ref_count = 1;
7394
61
            } else if (err != TxnErrorCode::TXN_OK) {
7395
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
7396
0
                        .tag("instance_id", instance_id_)
7397
0
                        .tag("tablet_id", tablet_id)
7398
0
                        .tag("rowset_id", rowset_id)
7399
0
                        .tag("err", err);
7400
0
                return -1;
7401
61
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
7402
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
7403
0
                        .tag("instance_id", instance_id_)
7404
0
                        .tag("tablet_id", tablet_id)
7405
0
                        .tag("rowset_id", rowset_id)
7406
0
                        .tag("value", hex(value));
7407
0
                return -1;
7408
0
            }
7409
61
        }
7410
7411
61
        if (ref_count > 1) {
7412
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
7413
12
            txn->atomic_add(rowset_ref_count_key, -1);
7414
12
            LOG_INFO("decrease rowset data ref count in classification phase")
7415
12
                    .tag("instance_id", instance_id_)
7416
12
                    .tag("tablet_id", tablet_id)
7417
12
                    .tag("rowset_id", rowset_id)
7418
12
                    .tag("ref_count", ref_count - 1)
7419
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
7420
7421
12
            if (!task.recycle_rowset_key.empty()) {
7422
0
                txn->remove(task.recycle_rowset_key);
7423
0
                LOG_INFO("remove recycle rowset key in classification phase")
7424
0
                        .tag("key", hex(task.recycle_rowset_key));
7425
0
            }
7426
12
            if (!task.non_versioned_rowset_key.empty()) {
7427
12
                txn->remove(task.non_versioned_rowset_key);
7428
12
                LOG_INFO("remove non versioned rowset key in classification phase")
7429
12
                        .tag("key", hex(task.non_versioned_rowset_key));
7430
12
            }
7431
7432
12
            err = txn->commit();
7433
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
7434
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
7435
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
7436
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
7437
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
7438
1
                continue;
7439
11
            } else if (err != TxnErrorCode::TXN_OK) {
7440
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
7441
0
                        .tag("instance_id", instance_id_)
7442
0
                        .tag("tablet_id", tablet_id)
7443
0
                        .tag("rowset_id", rowset_id)
7444
0
                        .tag("err", err);
7445
0
                return -1;
7446
0
            }
7447
11
            return 1; // handled, not added to batch delete
7448
49
        } else {
7449
            // ref_count == 1: Add to batch delete plan without modifying any KV.
7450
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
7451
49
            LOG_INFO("add rowset to batch delete plan")
7452
49
                    .tag("instance_id", instance_id_)
7453
49
                    .tag("tablet_id", tablet_id)
7454
49
                    .tag("rowset_id", rowset_id)
7455
49
                    .tag("resource_id", rowset_meta.resource_id())
7456
49
                    .tag("ref_count", ref_count);
7457
7458
49
            batch_delete_tasks.push_back(std::move(task));
7459
49
            return 0; // added to batch delete
7460
49
        }
7461
61
    }
7462
7463
0
    LOG_WARNING("failed to classify rowset task after retry")
7464
0
            .tag("instance_id", instance_id_)
7465
0
            .tag("tablet_id", tablet_id)
7466
0
            .tag("rowset_id", rowset_id)
7467
0
            .tag("retry", MAX_RETRY);
7468
0
    return -1;
7469
60
}
7470
7471
10
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
7472
10
    int ret = 0;
7473
49
    for (const auto& task : tasks) {
7474
49
        int64_t tablet_id = task.rowset_meta.tablet_id();
7475
49
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
7476
7477
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
7478
        // so we don't need to call it again here.
7479
7480
        // Remove all metadata keys in one transaction
7481
49
        std::unique_ptr<Transaction> txn;
7482
49
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7483
49
        if (err != TxnErrorCode::TXN_OK) {
7484
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
7485
0
                    .tag("instance_id", instance_id_)
7486
0
                    .tag("tablet_id", tablet_id)
7487
0
                    .tag("rowset_id", rowset_id)
7488
0
                    .tag("err", err);
7489
0
            ret = -1;
7490
0
            continue;
7491
0
        }
7492
7493
49
        std::string_view reference_instance_id = instance_id_;
7494
49
        if (task.rowset_meta.has_reference_instance_id()) {
7495
5
            reference_instance_id = task.rowset_meta.reference_instance_id();
7496
5
        }
7497
7498
49
        txn->remove(task.rowset_ref_count_key);
7499
49
        LOG_INFO("delete rowset data ref count key in cleanup phase")
7500
49
                .tag("instance_id", instance_id_)
7501
49
                .tag("tablet_id", tablet_id)
7502
49
                .tag("rowset_id", rowset_id)
7503
49
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
7504
7505
49
        std::string dbm_start_key =
7506
49
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
7507
49
        std::string dbm_end_key = meta_delete_bitmap_key(
7508
49
                {reference_instance_id, tablet_id, rowset_id,
7509
49
                 std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
7510
49
        txn->remove(dbm_start_key, dbm_end_key);
7511
49
        LOG_INFO("remove delete bitmap kv in cleanup phase")
7512
49
                .tag("instance_id", instance_id_)
7513
49
                .tag("tablet_id", tablet_id)
7514
49
                .tag("rowset_id", rowset_id)
7515
49
                .tag("begin", hex(dbm_start_key))
7516
49
                .tag("end", hex(dbm_end_key));
7517
7518
49
        std::string versioned_dbm_start_key =
7519
49
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
7520
49
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
7521
49
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
7522
49
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
7523
49
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
7524
49
                .tag("instance_id", instance_id_)
7525
49
                .tag("tablet_id", tablet_id)
7526
49
                .tag("rowset_id", rowset_id)
7527
49
                .tag("begin", hex(versioned_dbm_start_key))
7528
49
                .tag("end", hex(versioned_dbm_end_key));
7529
7530
        // Remove versioned meta rowset key
7531
49
        if (!task.versioned_rowset_key.empty()) {
7532
49
            versioned::document_remove<RowsetMetaCloudPB>(
7533
49
                txn.get(), task.versioned_rowset_key, task.versionstamp);
7534
49
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
7535
49
                    .tag("instance_id", instance_id_)
7536
49
                    .tag("tablet_id", tablet_id)
7537
49
                    .tag("rowset_id", rowset_id)
7538
49
                    .tag("key_prefix", hex(task.versioned_rowset_key));
7539
49
        }
7540
7541
49
        if (!task.non_versioned_rowset_key.empty()) {
7542
49
            txn->remove(task.non_versioned_rowset_key);
7543
49
            LOG_INFO("remove non versioned rowset key in cleanup phase")
7544
49
                    .tag("instance_id", instance_id_)
7545
49
                    .tag("tablet_id", tablet_id)
7546
49
                    .tag("rowset_id", rowset_id)
7547
49
                    .tag("key", hex(task.non_versioned_rowset_key));
7548
49
        }
7549
7550
        // Remove recycle_rowset_key last to ensure retry safety:
7551
        // if cleanup fails, this key remains and triggers next round retry.
7552
49
        if (!task.recycle_rowset_key.empty()) {
7553
0
            txn->remove(task.recycle_rowset_key);
7554
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
7555
0
                    .tag("instance_id", instance_id_)
7556
0
                    .tag("tablet_id", tablet_id)
7557
0
                    .tag("rowset_id", rowset_id)
7558
0
                    .tag("key", hex(task.recycle_rowset_key));
7559
0
        }
7560
7561
49
        err = txn->commit();
7562
49
        if (err != TxnErrorCode::TXN_OK) {
7563
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
7564
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
7565
0
                    .tag("instance_id", instance_id_)
7566
0
                    .tag("tablet_id", tablet_id)
7567
0
                    .tag("rowset_id", rowset_id)
7568
0
                    .tag("err", err);
7569
0
            ret = -1;
7570
0
            continue;
7571
0
        }
7572
7573
49
        LOG_INFO("cleanup rowset metadata success")
7574
49
                .tag("instance_id", instance_id_)
7575
49
                .tag("tablet_id", tablet_id)
7576
49
                .tag("rowset_id", rowset_id);
7577
49
    }
7578
10
    return ret;
7579
10
}
7580
7581
} // namespace doris::cloud