Coverage Report

Created: 2026-03-04 17:28

/root/doris/cloud/src/recycler/recycler.cpp
Line
Count
Source (jump to first uncovered line)
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "recycler/recycler.h"
19
20
#include <brpc/builtin_service.pb.h>
21
#include <brpc/server.h>
22
#include <butil/endpoint.h>
23
#include <butil/strings/string_split.h>
24
#include <bvar/status.h>
25
#include <gen_cpp/cloud.pb.h>
26
#include <gen_cpp/olap_file.pb.h>
27
28
#include <algorithm>
29
#include <atomic>
30
#include <chrono>
31
#include <cstddef>
32
#include <cstdint>
33
#include <cstdlib>
34
#include <deque>
35
#include <functional>
36
#include <initializer_list>
37
#include <memory>
38
#include <numeric>
39
#include <random>
40
#include <string>
41
#include <string_view>
42
#include <thread>
43
#include <unordered_map>
44
#include <utility>
45
#include <variant>
46
47
#include "common/defer.h"
48
#include "common/stopwatch.h"
49
#include "meta-service/meta_service.h"
50
#include "meta-service/meta_service_helper.h"
51
#include "meta-service/meta_service_schema.h"
52
#include "meta-store/blob_message.h"
53
#include "meta-store/meta_reader.h"
54
#include "meta-store/txn_kv.h"
55
#include "meta-store/txn_kv_error.h"
56
#include "meta-store/versioned_value.h"
57
#include "recycler/checker.h"
58
#ifdef ENABLE_HDFS_STORAGE_VAULT
59
#include "recycler/hdfs_accessor.h"
60
#endif
61
#include "recycler/s3_accessor.h"
62
#include "recycler/storage_vault_accessor.h"
63
#ifdef UNIT_TEST
64
#include "../test/mock_accessor.h"
65
#endif
66
#include "common/bvars.h"
67
#include "common/config.h"
68
#include "common/encryption_util.h"
69
#include "common/logging.h"
70
#include "common/simple_thread_pool.h"
71
#include "common/util.h"
72
#include "cpp/sync_point.h"
73
#include "meta-store/codec.h"
74
#include "meta-store/document_message.h"
75
#include "meta-store/keys.h"
76
#include "recycler/recycler_service.h"
77
#include "recycler/sync_executor.h"
78
#include "recycler/util.h"
79
80
namespace doris::cloud {
81
82
using namespace std::chrono;
83
84
namespace {
85
86
0
int64_t packed_file_retry_sleep_ms() {
87
0
    const int64_t min_ms = std::max<int64_t>(0, config::packed_file_txn_retry_sleep_min_ms);
88
0
    const int64_t max_ms = std::max<int64_t>(min_ms, config::packed_file_txn_retry_sleep_max_ms);
89
0
    thread_local std::mt19937_64 gen(std::random_device {}());
90
0
    std::uniform_int_distribution<int64_t> dist(min_ms, max_ms);
91
0
    return dist(gen);
92
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_126packed_file_retry_sleep_msEv
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_126packed_file_retry_sleep_msEv
93
94
0
void sleep_for_packed_file_retry() {
95
0
    std::this_thread::sleep_for(std::chrono::milliseconds(packed_file_retry_sleep_ms()));
96
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_127sleep_for_packed_file_retryEv
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_127sleep_for_packed_file_retryEv
97
98
} // namespace
99
100
// return 0 for success get a key, 1 for key not found, negative for error
101
0
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
102
0
    std::unique_ptr<Transaction> txn;
103
0
    TxnErrorCode err = txn_kv->create_txn(&txn);
104
0
    if (err != TxnErrorCode::TXN_OK) {
105
0
        return -1;
106
0
    }
107
0
    switch (txn->get(key, &val, true)) {
108
0
    case TxnErrorCode::TXN_OK:
109
0
        return 0;
110
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
111
0
        return 1;
112
0
    default:
113
0
        return -1;
114
0
    };
115
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
116
117
// 0 for success, negative for error
118
static int txn_get(TxnKv* txn_kv, std::string_view begin, std::string_view end,
119
325
                   std::unique_ptr<RangeGetIterator>& it) {
120
325
    std::unique_ptr<Transaction> txn;
121
325
    TxnErrorCode err = txn_kv->create_txn(&txn);
122
325
    if (err != TxnErrorCode::TXN_OK) {
123
0
        return -1;
124
0
    }
125
325
    switch (txn->get(begin, end, &it, true)) {
126
325
    case TxnErrorCode::TXN_OK:
127
325
        return 0;
128
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
129
0
        return 1;
130
0
    default:
131
0
        return -1;
132
325
    };
133
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
119
31
                   std::unique_ptr<RangeGetIterator>& it) {
120
31
    std::unique_ptr<Transaction> txn;
121
31
    TxnErrorCode err = txn_kv->create_txn(&txn);
122
31
    if (err != TxnErrorCode::TXN_OK) {
123
0
        return -1;
124
0
    }
125
31
    switch (txn->get(begin, end, &it, true)) {
126
31
    case TxnErrorCode::TXN_OK:
127
31
        return 0;
128
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
129
0
        return 1;
130
0
    default:
131
0
        return -1;
132
31
    };
133
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
119
294
                   std::unique_ptr<RangeGetIterator>& it) {
120
294
    std::unique_ptr<Transaction> txn;
121
294
    TxnErrorCode err = txn_kv->create_txn(&txn);
122
294
    if (err != TxnErrorCode::TXN_OK) {
123
0
        return -1;
124
0
    }
125
294
    switch (txn->get(begin, end, &it, true)) {
126
294
    case TxnErrorCode::TXN_OK:
127
294
        return 0;
128
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
129
0
        return 1;
130
0
    default:
131
0
        return -1;
132
294
    };
133
0
}
134
135
// return 0 for success otherwise error
136
6
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
137
6
    std::unique_ptr<Transaction> txn;
138
6
    TxnErrorCode err = txn_kv->create_txn(&txn);
139
6
    if (err != TxnErrorCode::TXN_OK) {
140
0
        return -1;
141
0
    }
142
10
    for (auto k : keys) {
143
10
        txn->remove(k);
144
10
    }
145
6
    switch (txn->commit()) {
146
6
    case TxnErrorCode::TXN_OK:
147
6
        return 0;
148
0
    case TxnErrorCode::TXN_CONFLICT:
149
0
        return -1;
150
0
    default:
151
0
        return -1;
152
6
    }
153
6
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
136
1
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
137
1
    std::unique_ptr<Transaction> txn;
138
1
    TxnErrorCode err = txn_kv->create_txn(&txn);
139
1
    if (err != TxnErrorCode::TXN_OK) {
140
0
        return -1;
141
0
    }
142
1
    for (auto k : keys) {
143
1
        txn->remove(k);
144
1
    }
145
1
    switch (txn->commit()) {
146
1
    case TxnErrorCode::TXN_OK:
147
1
        return 0;
148
0
    case TxnErrorCode::TXN_CONFLICT:
149
0
        return -1;
150
0
    default:
151
0
        return -1;
152
1
    }
153
1
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
136
5
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
137
5
    std::unique_ptr<Transaction> txn;
138
5
    TxnErrorCode err = txn_kv->create_txn(&txn);
139
5
    if (err != TxnErrorCode::TXN_OK) {
140
0
        return -1;
141
0
    }
142
9
    for (auto k : keys) {
143
9
        txn->remove(k);
144
9
    }
145
5
    switch (txn->commit()) {
146
5
    case TxnErrorCode::TXN_OK:
147
5
        return 0;
148
0
    case TxnErrorCode::TXN_CONFLICT:
149
0
        return -1;
150
0
    default:
151
0
        return -1;
152
5
    }
153
5
}
154
155
// return 0 for success otherwise error
156
119
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
157
119
    std::unique_ptr<Transaction> txn;
158
119
    TxnErrorCode err = txn_kv->create_txn(&txn);
159
119
    if (err != TxnErrorCode::TXN_OK) {
160
0
        return -1;
161
0
    }
162
105k
    for (auto& k : keys) {
163
105k
        txn->remove(k);
164
105k
    }
165
119
    switch (txn->commit()) {
166
119
    case TxnErrorCode::TXN_OK:
167
119
        return 0;
168
0
    case TxnErrorCode::TXN_CONFLICT:
169
0
        return -1;
170
0
    default:
171
0
        return -1;
172
119
    }
173
119
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
156
33
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
157
33
    std::unique_ptr<Transaction> txn;
158
33
    TxnErrorCode err = txn_kv->create_txn(&txn);
159
33
    if (err != TxnErrorCode::TXN_OK) {
160
0
        return -1;
161
0
    }
162
33
    for (auto& k : keys) {
163
16
        txn->remove(k);
164
16
    }
165
33
    switch (txn->commit()) {
166
33
    case TxnErrorCode::TXN_OK:
167
33
        return 0;
168
0
    case TxnErrorCode::TXN_CONFLICT:
169
0
        return -1;
170
0
    default:
171
0
        return -1;
172
33
    }
173
33
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
156
86
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
157
86
    std::unique_ptr<Transaction> txn;
158
86
    TxnErrorCode err = txn_kv->create_txn(&txn);
159
86
    if (err != TxnErrorCode::TXN_OK) {
160
0
        return -1;
161
0
    }
162
105k
    for (auto& k : keys) {
163
105k
        txn->remove(k);
164
105k
    }
165
86
    switch (txn->commit()) {
166
86
    case TxnErrorCode::TXN_OK:
167
86
        return 0;
168
0
    case TxnErrorCode::TXN_CONFLICT:
169
0
        return -1;
170
0
    default:
171
0
        return -1;
172
86
    }
173
86
}
174
175
// return 0 for success otherwise error
176
[[maybe_unused]] static int txn_remove(TxnKv* txn_kv, std::string_view begin,
177
106k
                                       std::string_view end) {
178
106k
    std::unique_ptr<Transaction> txn;
179
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
180
106k
    if (err != TxnErrorCode::TXN_OK) {
181
0
        return -1;
182
0
    }
183
106k
    txn->remove(begin, end);
184
106k
    switch (txn->commit()) {
185
106k
    case TxnErrorCode::TXN_OK:
186
106k
        return 0;
187
0
    case TxnErrorCode::TXN_CONFLICT:
188
0
        return -1;
189
0
    default:
190
0
        return -1;
191
106k
    }
192
106k
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
177
16
                                       std::string_view end) {
178
16
    std::unique_ptr<Transaction> txn;
179
16
    TxnErrorCode err = txn_kv->create_txn(&txn);
180
16
    if (err != TxnErrorCode::TXN_OK) {
181
0
        return -1;
182
0
    }
183
16
    txn->remove(begin, end);
184
16
    switch (txn->commit()) {
185
16
    case TxnErrorCode::TXN_OK:
186
16
        return 0;
187
0
    case TxnErrorCode::TXN_CONFLICT:
188
0
        return -1;
189
0
    default:
190
0
        return -1;
191
16
    }
192
16
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
177
106k
                                       std::string_view end) {
178
106k
    std::unique_ptr<Transaction> txn;
179
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
180
106k
    if (err != TxnErrorCode::TXN_OK) {
181
0
        return -1;
182
0
    }
183
106k
    txn->remove(begin, end);
184
106k
    switch (txn->commit()) {
185
106k
    case TxnErrorCode::TXN_OK:
186
106k
        return 0;
187
0
    case TxnErrorCode::TXN_CONFLICT:
188
0
        return -1;
189
0
    default:
190
0
        return -1;
191
106k
    }
192
106k
}
193
194
void scan_restore_job_rowset(
195
        Transaction* txn, const std::string& instance_id, int64_t tablet_id, MetaServiceCode& code,
196
        std::string& msg,
197
        std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>* restore_job_rs_metas);
198
199
static inline void check_recycle_task(const std::string& instance_id, const std::string& task_name,
200
                                      int64_t num_scanned, int64_t num_recycled,
201
52
                                      int64_t start_time) {
202
52
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
203
0
        int64_t cost =
204
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
205
0
        if (cost > config::recycle_task_threshold_seconds) {
206
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
207
0
                    .tag("instance_id", instance_id)
208
0
                    .tag("task", task_name)
209
0
                    .tag("num_scanned", num_scanned)
210
0
                    .tag("num_recycled", num_recycled);
211
0
        }
212
0
    }
213
52
    return;
214
52
}
recycler.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
201
2
                                      int64_t start_time) {
202
2
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
203
0
        int64_t cost =
204
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
205
0
        if (cost > config::recycle_task_threshold_seconds) {
206
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
207
0
                    .tag("instance_id", instance_id)
208
0
                    .tag("task", task_name)
209
0
                    .tag("num_scanned", num_scanned)
210
0
                    .tag("num_recycled", num_recycled);
211
0
        }
212
0
    }
213
2
    return;
214
2
}
recycler_test.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
201
50
                                      int64_t start_time) {
202
50
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
203
0
        int64_t cost =
204
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
205
0
        if (cost > config::recycle_task_threshold_seconds) {
206
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
207
0
                    .tag("instance_id", instance_id)
208
0
                    .tag("task", task_name)
209
0
                    .tag("num_scanned", num_scanned)
210
0
                    .tag("num_recycled", num_recycled);
211
0
        }
212
0
    }
213
50
    return;
214
50
}
215
216
4
Recycler::Recycler(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
217
4
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
218
219
4
    auto s3_producer_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
220
4
                                                               "s3_producer_pool");
221
4
    s3_producer_pool->start();
222
4
    auto recycle_tablet_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
223
4
                                                                  "recycle_tablet_pool");
224
4
    recycle_tablet_pool->start();
225
4
    auto group_recycle_function_pool = std::make_shared<SimpleThreadPool>(
226
4
            config::recycle_pool_parallelism, "group_recycle_function_pool");
227
4
    group_recycle_function_pool->start();
228
4
    _thread_pool_group =
229
4
            RecyclerThreadPoolGroup(std::move(s3_producer_pool), std::move(recycle_tablet_pool),
230
4
                                    std::move(group_recycle_function_pool));
231
232
4
    auto resource_mgr = std::make_shared<ResourceManager>(txn_kv_);
233
4
    txn_lazy_committer_ = std::make_shared<TxnLazyCommitter>(txn_kv_, std::move(resource_mgr));
234
4
    snapshot_manager_ = std::make_shared<SnapshotManager>(txn_kv_);
235
4
}
236
237
4
Recycler::~Recycler() {
238
4
    if (!stopped()) {
239
0
        stop();
240
0
    }
241
4
}
242
243
4
void Recycler::instance_scanner_callback() {
244
    // sleep 60 seconds before scheduling for the launch procedure to complete:
245
    // some bad hdfs connection may cause some log to stdout stderr
246
    // which may pollute .out file and affect the script to check success
247
4
    std::this_thread::sleep_for(
248
4
            std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
249
8
    while (!stopped()) {
250
4
        std::vector<InstanceInfoPB> instances;
251
4
        get_all_instances(txn_kv_.get(), instances);
252
        // TODO(plat1ko): delete job recycle kv of non-existent instances
253
4
        LOG(INFO) << "Recycler get instances: " << [&instances] {
254
4
            std::stringstream ss;
255
30
            for (auto& i : instances) ss << ' ' << i.instance_id();
256
4
            return ss.str();
257
4
        }();
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
Line
Count
Source
253
4
        LOG(INFO) << "Recycler get instances: " << [&instances] {
254
4
            std::stringstream ss;
255
30
            for (auto& i : instances) ss << ' ' << i.instance_id();
256
4
            return ss.str();
257
4
        }();
258
4
        if (!instances.empty()) {
259
            // enqueue instances
260
3
            std::lock_guard lock(mtx_);
261
30
            for (auto& instance : instances) {
262
30
                if (instance_filter_.filter_out(instance.instance_id())) continue;
263
30
                auto [_, success] = pending_instance_set_.insert(instance.instance_id());
264
                // skip instance already in pending queue
265
30
                if (success) {
266
30
                    pending_instance_queue_.push_back(std::move(instance));
267
30
                }
268
30
            }
269
3
            pending_instance_cond_.notify_all();
270
3
        }
271
4
        {
272
4
            std::unique_lock lock(mtx_);
273
4
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
274
7
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
274
7
                               [&]() { return stopped(); });
275
4
        }
276
4
    }
277
4
}
278
279
8
void Recycler::recycle_callback() {
280
38
    while (!stopped()) {
281
37
        InstanceInfoPB instance;
282
37
        {
283
37
            std::unique_lock lock(mtx_);
284
37
            pending_instance_cond_.wait(
285
49
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
285
49
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
286
37
            if (stopped()) {
287
7
                return;
288
7
            }
289
30
            instance = std::move(pending_instance_queue_.front());
290
30
            pending_instance_queue_.pop_front();
291
30
            pending_instance_set_.erase(instance.instance_id());
292
30
        }
293
0
        auto& instance_id = instance.instance_id();
294
30
        {
295
30
            std::lock_guard lock(mtx_);
296
            // skip instance in recycling
297
30
            if (recycling_instance_map_.count(instance_id)) continue;
298
30
        }
299
30
        auto instance_recycler = std::make_shared<InstanceRecycler>(
300
30
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
301
302
30
        if (int r = instance_recycler->init(); r != 0) {
303
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
304
0
                         << " ret=" << r;
305
0
            continue;
306
0
        }
307
30
        std::string recycle_job_key;
308
30
        job_recycle_key({instance_id}, &recycle_job_key);
309
30
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
310
30
                                               ip_port_, config::recycle_interval_seconds * 1000);
311
30
        if (ret != 0) { // Prepare failed
312
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
313
20
                         << " ret=" << ret;
314
20
            continue;
315
20
        } else {
316
10
            std::lock_guard lock(mtx_);
317
10
            recycling_instance_map_.emplace(instance_id, instance_recycler);
318
10
        }
319
10
        if (stopped()) return;
320
10
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
321
10
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
322
10
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
323
10
        g_bvar_recycler_instance_recycle_task_status.put({"submitted"}, 1);
324
10
        ret = instance_recycler->do_recycle();
325
        // If instance recycler has been aborted, don't finish this job
326
327
10
        if (!instance_recycler->stopped()) {
328
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
329
10
                                        ret == 0, ctime_ms);
330
10
        }
331
10
        if (instance_recycler->stopped() || ret != 0) {
332
0
            g_bvar_recycler_instance_recycle_task_status.put({"error"}, 1);
333
0
        }
334
10
        {
335
10
            std::lock_guard lock(mtx_);
336
10
            recycling_instance_map_.erase(instance_id);
337
10
        }
338
339
10
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
340
10
        auto elpased_ms = now - ctime_ms;
341
10
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
342
10
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
343
10
        g_bvar_recycler_instance_next_ts.put({instance_id},
344
10
                                             now + config::recycle_interval_seconds * 1000);
345
10
        g_bvar_recycler_instance_recycle_task_status.put({"completed"}, 1);
346
10
        LOG(INFO) << "recycle instance done, "
347
10
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
348
10
                  << " now: " << now;
349
350
10
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
351
352
10
        LOG_WARNING("finish recycle instance")
353
10
                .tag("instance_id", instance_id)
354
10
                .tag("cost_ms", elpased_ms);
355
10
    }
356
8
}
357
358
4
void Recycler::lease_recycle_jobs() {
359
54
    while (!stopped()) {
360
50
        std::vector<std::string> instances;
361
50
        instances.reserve(recycling_instance_map_.size());
362
50
        {
363
50
            std::lock_guard lock(mtx_);
364
50
            for (auto& [id, _] : recycling_instance_map_) {
365
30
                instances.push_back(id);
366
30
            }
367
50
        }
368
50
        for (auto& i : instances) {
369
30
            std::string recycle_job_key;
370
30
            job_recycle_key({i}, &recycle_job_key);
371
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
372
30
            if (ret == 1) {
373
0
                std::lock_guard lock(mtx_);
374
0
                if (auto it = recycling_instance_map_.find(i);
375
0
                    it != recycling_instance_map_.end()) {
376
0
                    it->second->stop();
377
0
                }
378
0
            }
379
30
        }
380
50
        {
381
50
            std::unique_lock lock(mtx_);
382
50
            notifier_.wait_for(lock,
383
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
384
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
384
100
                               [&]() { return stopped(); });
385
50
        }
386
50
    }
387
4
}
388
389
4
void Recycler::check_recycle_tasks() {
390
7
    while (!stopped()) {
391
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
392
3
        {
393
3
            std::lock_guard lock(mtx_);
394
3
            recycling_instance_map = recycling_instance_map_;
395
3
        }
396
3
        for (auto& entry : recycling_instance_map) {
397
0
            entry.second->check_recycle_tasks();
398
0
        }
399
400
3
        std::unique_lock lock(mtx_);
401
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
402
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
402
6
                           [&]() { return stopped(); });
403
3
    }
404
4
}
405
406
4
int Recycler::start(brpc::Server* server) {
407
4
    instance_filter_.reset(config::recycle_whitelist, config::recycle_blacklist);
408
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
409
4
    S3Environment::getInstance();
410
411
4
    if (config::enable_checker) {
412
0
        checker_ = std::make_unique<Checker>(txn_kv_);
413
0
        int ret = checker_->start();
414
0
        std::string msg;
415
0
        if (ret != 0) {
416
0
            msg = "failed to start checker";
417
0
            LOG(ERROR) << msg;
418
0
            std::cerr << msg << std::endl;
419
0
            return ret;
420
0
        }
421
0
        msg = "checker started";
422
0
        LOG(INFO) << msg;
423
0
        std::cout << msg << std::endl;
424
0
    }
425
426
4
    if (server) {
427
        // Add service
428
1
        auto recycler_service =
429
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
430
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
431
1
    }
432
433
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
433
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
434
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
435
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
435
8
        workers_.emplace_back([this] { recycle_callback(); });
436
8
    }
437
438
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
439
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
440
441
4
    if (config::enable_snapshot_data_migrator) {
442
0
        snapshot_data_migrator_ = std::make_shared<SnapshotDataMigrator>(txn_kv_);
443
0
        int ret = snapshot_data_migrator_->start();
444
0
        if (ret != 0) {
445
0
            LOG(ERROR) << "failed to start snapshot data migrator";
446
0
            return ret;
447
0
        }
448
0
        LOG(INFO) << "snapshot data migrator started";
449
0
    }
450
451
4
    if (config::enable_snapshot_chain_compactor) {
452
0
        snapshot_chain_compactor_ = std::make_shared<SnapshotChainCompactor>(txn_kv_);
453
0
        int ret = snapshot_chain_compactor_->start();
454
0
        if (ret != 0) {
455
0
            LOG(ERROR) << "failed to start snapshot chain compactor";
456
0
            return ret;
457
0
        }
458
0
        LOG(INFO) << "snapshot chain compactor started";
459
0
    }
460
461
4
    return 0;
462
4
}
463
464
4
void Recycler::stop() {
465
4
    stopped_ = true;
466
4
    notifier_.notify_all();
467
4
    pending_instance_cond_.notify_all();
468
4
    {
469
4
        std::lock_guard lock(mtx_);
470
4
        for (auto& [_, recycler] : recycling_instance_map_) {
471
0
            recycler->stop();
472
0
        }
473
4
    }
474
20
    for (auto& w : workers_) {
475
20
        if (w.joinable()) w.join();
476
20
    }
477
4
    if (checker_) {
478
0
        checker_->stop();
479
0
    }
480
4
    if (snapshot_data_migrator_) {
481
0
        snapshot_data_migrator_->stop();
482
0
    }
483
4
    if (snapshot_chain_compactor_) {
484
0
        snapshot_chain_compactor_->stop();
485
0
    }
486
4
}
487
488
class InstanceRecycler::InvertedIndexIdCache {
489
public:
490
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
491
130
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
492
493
    // Return 0 if success, 1 if schema kv not found, negative for error
494
    // For the same index_id, schema_version, res, since `get` is not completely atomic
495
    // one thread has not finished inserting, and another thread has not get the index_id and schema_version,
496
    // resulting in repeated addition and inaccuracy.
497
    // however, this approach can reduce the lock range and sacrifice a bit of meta repeated get to improve concurrency performance.
498
    // repeated addition does not affect correctness.
499
28.4k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
500
28.4k
        {
501
28.4k
            std::lock_guard lock(mtx_);
502
28.4k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
503
3.98k
                return 0;
504
3.98k
            }
505
24.4k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
506
24.4k
                it != inverted_index_id_map_.end()) {
507
16.7k
                res = it->second;
508
16.7k
                return 0;
509
16.7k
            }
510
24.4k
        }
511
        // Get schema from kv
512
        // TODO(plat1ko): Single flight
513
7.70k
        std::unique_ptr<Transaction> txn;
514
7.70k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
515
7.70k
        if (err != TxnErrorCode::TXN_OK) {
516
0
            LOG(WARNING) << "failed to create txn, err=" << err;
517
0
            return -1;
518
0
        }
519
7.70k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
520
7.70k
        ValueBuf val_buf;
521
7.70k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
522
7.70k
        if (err != TxnErrorCode::TXN_OK) {
523
504
            LOG(WARNING) << "failed to get schema, err=" << err;
524
504
            return static_cast<int>(err);
525
504
        }
526
7.19k
        doris::TabletSchemaCloudPB schema;
527
7.19k
        if (!parse_schema_value(val_buf, &schema)) {
528
0
            LOG(WARNING) << "malformed schema value, key=" << hex(schema_key);
529
0
            return -1;
530
0
        }
531
7.19k
        if (schema.index_size() > 0) {
532
5.48k
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
533
5.48k
            if (schema.has_inverted_index_storage_format()) {
534
5.47k
                index_format = schema.inverted_index_storage_format();
535
5.47k
            }
536
5.48k
            res.first = index_format;
537
5.48k
            res.second.reserve(schema.index_size());
538
13.2k
            for (auto& i : schema.index()) {
539
13.2k
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
540
13.2k
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
541
13.2k
                }
542
13.2k
            }
543
5.48k
        }
544
7.19k
        insert(index_id, schema_version, res);
545
7.19k
        return 0;
546
7.19k
    }
547
548
    // Empty `ids` means this schema has no inverted index
549
7.19k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
550
7.19k
        if (index_info.second.empty()) {
551
1.71k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
552
1.71k
            std::lock_guard lock(mtx_);
553
1.71k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
554
5.48k
        } else {
555
5.48k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
556
5.48k
            std::lock_guard lock(mtx_);
557
5.48k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
558
5.48k
        }
559
7.19k
    }
560
561
private:
562
    std::string instance_id_;
563
    std::shared_ptr<TxnKv> txn_kv_;
564
565
    std::mutex mtx_;
566
    using Key = std::pair<int64_t, int32_t>; // <index_id, schema_version>
567
    struct HashOfKey {
568
60.0k
        size_t operator()(const Key& key) const {
569
60.0k
            size_t seed = 0;
570
60.0k
            seed = std::hash<int64_t> {}(key.first);
571
60.0k
            seed = std::hash<int32_t> {}(key.second);
572
60.0k
            return seed;
573
60.0k
        }
574
    };
575
    // <index_id, schema_version> -> inverted_index_ids
576
    std::unordered_map<Key, InvertedIndexInfo, HashOfKey> inverted_index_id_map_;
577
    // Store <index_id, schema_version> of schema which doesn't have inverted index
578
    std::unordered_set<Key, HashOfKey> schemas_without_inverted_index_;
579
};
580
581
InstanceRecycler::InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
582
                                   RecyclerThreadPoolGroup thread_pool_group,
583
                                   std::shared_ptr<TxnLazyCommitter> txn_lazy_committer)
584
        : txn_kv_(std::move(txn_kv)),
585
          instance_id_(instance.instance_id()),
586
          instance_info_(instance),
587
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
588
          _thread_pool_group(std::move(thread_pool_group)),
589
          txn_lazy_committer_(std::move(txn_lazy_committer)),
590
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
591
130
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
592
130
    delete_bitmap_lock_white_list_->init();
593
130
    resource_mgr_->init();
594
130
    snapshot_manager_ = std::make_shared<SnapshotManager>(txn_kv_);
595
596
    // Since the recycler's resource manager could not be notified when instance info changes,
597
    // we need to refresh the instance info here to ensure the resource manager has the latest info.
598
130
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
599
130
};
600
601
130
InstanceRecycler::~InstanceRecycler() = default;
602
603
114
int InstanceRecycler::init_obj_store_accessors() {
604
114
    for (const auto& obj_info : instance_info_.obj_info()) {
605
74
#ifdef UNIT_TEST
606
74
        auto accessor = std::make_shared<MockAccessor>();
607
#else
608
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
609
        if (!s3_conf) {
610
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
611
            return -1;
612
        }
613
614
        std::shared_ptr<S3Accessor> accessor;
615
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
616
        if (ret != 0) {
617
            LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
618
                         << " resource_id=" << obj_info.id();
619
            return ret;
620
        }
621
#endif
622
74
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
623
74
    }
624
625
114
    return 0;
626
114
}
627
628
114
int InstanceRecycler::init_storage_vault_accessors() {
629
114
    if (instance_info_.resource_ids().empty()) {
630
107
        return 0;
631
107
    }
632
633
7
    FullRangeGetOptions opts(txn_kv_);
634
7
    opts.prefetch = true;
635
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
636
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
637
638
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
639
18
        auto [k, v] = *kv;
640
18
        StorageVaultPB vault;
641
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
642
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
643
0
            return -1;
644
0
        }
645
18
        std::string recycler_storage_vault_white_list = accumulate(
646
18
                config::recycler_storage_vault_white_list.begin(),
647
18
                config::recycler_storage_vault_white_list.end(), std::string(),
648
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
Line
Count
Source
648
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
649
18
        LOG_INFO("config::recycler_storage_vault_white_list")
650
18
                .tag("", recycler_storage_vault_white_list);
651
18
        if (!config::recycler_storage_vault_white_list.empty()) {
652
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
653
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
654
8
                it == config::recycler_storage_vault_white_list.end()) {
655
2
                LOG_WARNING(
656
2
                        "failed to init accessor for vault because this vault is not in "
657
2
                        "config::recycler_storage_vault_white_list. ")
658
2
                        .tag(" vault name:", vault.name())
659
2
                        .tag(" config::recycler_storage_vault_white_list:",
660
2
                             recycler_storage_vault_white_list);
661
2
                continue;
662
2
            }
663
8
        }
664
16
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
665
16
                                 &accessor_map_, &vault);
666
16
        if (vault.has_hdfs_info()) {
667
9
#ifdef ENABLE_HDFS_STORAGE_VAULT
668
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
669
9
            int ret = accessor->init();
670
9
            if (ret != 0) {
671
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
672
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
673
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
674
4
                continue;
675
4
            }
676
5
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
677
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
678
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
679
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
680
#else
681
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
682
                       << "but HDFS storage vaults were detected";
683
#endif
684
7
        } else if (vault.has_obj_info()) {
685
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
686
7
            if (!s3_conf) {
687
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
688
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
689
1
                continue;
690
1
            }
691
692
6
            std::shared_ptr<S3Accessor> accessor;
693
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
694
6
            if (ret != 0) {
695
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
696
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
697
0
                             << " ret=" << ret
698
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
699
0
                continue;
700
0
            }
701
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
702
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
703
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
704
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
705
6
        }
706
16
    }
707
708
7
    if (!it->is_valid()) {
709
0
        LOG_WARNING("failed to get storage vault kv");
710
0
        return -1;
711
0
    }
712
713
7
    if (accessor_map_.empty()) {
714
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
715
1
        return -2;
716
1
    }
717
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
718
6
             instance_id_);
719
720
6
    return 0;
721
7
}
722
723
114
int InstanceRecycler::init() {
724
114
    int ret = init_obj_store_accessors();
725
114
    if (ret != 0) {
726
0
        return ret;
727
0
    }
728
729
114
    return init_storage_vault_accessors();
730
114
}
731
732
template <typename... Func>
733
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
120
    return [funcs...]() {
735
120
        return [](std::initializer_list<int> ret_vals) {
736
120
            int i = 0;
737
140
            for (int ret : ret_vals) {
738
140
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
140
            }
742
120
            return i;
743
120
        }({funcs()...});
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
20
            for (int ret : ret_vals) {
738
20
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
20
            }
742
10
            return i;
743
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
20
            for (int ret : ret_vals) {
738
20
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
20
            }
742
10
            return i;
743
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
0
                    i = ret;
740
0
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
120
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
120
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
733
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
734
10
    return [funcs...]() {
735
10
        return [](std::initializer_list<int> ret_vals) {
736
10
            int i = 0;
737
10
            for (int ret : ret_vals) {
738
10
                if (ret != 0) {
739
10
                    i = ret;
740
10
                }
741
10
            }
742
10
            return i;
743
10
        }({funcs()...});
744
10
    };
745
10
}
746
747
10
int InstanceRecycler::do_recycle() {
748
10
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
749
10
    tablet_metrics_context_.reset();
750
10
    segment_metrics_context_.reset();
751
10
    DORIS_CLOUD_DEFER {
752
10
        tablet_metrics_context_.finish_report();
753
10
        segment_metrics_context_.finish_report();
754
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
751
10
    DORIS_CLOUD_DEFER {
752
10
        tablet_metrics_context_.finish_report();
753
10
        segment_metrics_context_.finish_report();
754
10
    };
755
10
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
756
0
        int res = recycle_cluster_snapshots();
757
0
        if (res != 0) {
758
0
            return -1;
759
0
        }
760
0
        return recycle_deleted_instance();
761
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
762
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
763
10
                                        fmt::format("instance id {}", instance_id_),
764
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
764
120
                                        [](int r) { return r != 0; });
765
10
        sync_executor
766
10
                .add(task_wrapper(
767
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
767
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
768
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_3clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_3clEv
Line
Count
Source
768
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
769
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
770
                                   // becase they may both recycle the same set of tablets
771
                        // recycle dropped table or idexes(mv, rollup)
772
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
772
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
773
                        // recycle dropped partitions
774
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
774
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
775
10
                .add(task_wrapper(
776
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
776
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
777
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_7clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_7clEv
Line
Count
Source
777
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
778
10
                .add(task_wrapper(
779
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
779
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
780
10
                .add(task_wrapper(
781
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
781
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
782
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
782
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
783
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_11clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_11clEv
Line
Count
Source
783
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
784
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_12clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_12clEv
Line
Count
Source
784
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
785
10
                .add(task_wrapper(
786
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
786
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
787
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_14clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_14clEv
Line
Count
Source
787
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
788
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_15clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_15clEv
Line
Count
Source
788
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
789
10
        bool finished = true;
790
10
        std::vector<int> rets = sync_executor.when_all(&finished);
791
120
        for (int ret : rets) {
792
120
            if (ret != 0) {
793
0
                return ret;
794
0
            }
795
120
        }
796
10
        return finished ? 0 : -1;
797
10
    } else {
798
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
799
0
                     << " instance_id=" << instance_id_;
800
0
        return -1;
801
0
    }
802
10
}
803
804
/**
805
* 1. delete all remote data
806
* 2. delete all kv
807
* 3. remove instance kv
808
*/
809
4
int InstanceRecycler::recycle_deleted_instance() {
810
4
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
811
812
4
    int ret = 0;
813
4
    auto start_time = steady_clock::now();
814
815
4
    DORIS_CLOUD_DEFER {
816
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
817
4
        LOG(WARNING) << (ret == 0 ? "successfully" : "failed to")
818
4
                     << " recycle deleted instance, cost=" << cost
819
4
                     << "s, instance_id=" << instance_id_;
820
4
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
815
4
    DORIS_CLOUD_DEFER {
816
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
817
4
        LOG(WARNING) << (ret == 0 ? "successfully" : "failed to")
818
4
                     << " recycle deleted instance, cost=" << cost
819
4
                     << "s, instance_id=" << instance_id_;
820
4
    };
821
822
    // Step 1: Recycle versioned rowsets in recycle space (already marked for deletion)
823
4
    if (recycle_versioned_rowsets() != 0) {
824
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
825
0
        return -1;
826
0
    }
827
828
    // Step 2: Recycle operation logs (can recycle logs not referenced by snapshots)
829
4
    if (recycle_operation_logs() != 0) {
830
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
831
0
        return -1;
832
0
    }
833
834
    // Step 3: Check if there are still cluster snapshots
835
4
    bool has_snapshots = false;
836
4
    if (has_cluster_snapshots(&has_snapshots) != 0) {
837
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
838
0
        return -1;
839
4
    } else if (has_snapshots) {
840
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
841
1
        return 0;
842
1
    }
843
844
3
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
845
3
                            instance_info().snapshot_switch_status() !=
846
0
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
847
3
    if (snapshot_enabled) {
848
0
        bool has_unrecycled_rowsets = false;
849
0
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
850
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
851
0
            return -1;
852
0
        } else if (has_unrecycled_rowsets) {
853
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
854
0
                    .tag("instance_id", instance_id_);
855
0
            return ret;
856
0
        }
857
3
    } else { // delete all remote data if snapshot is disabled
858
3
        for (auto& [_, accessor] : accessor_map_) {
859
3
            if (stopped()) {
860
0
                return ret;
861
0
            }
862
863
3
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
864
3
            int del_ret = accessor->delete_all();
865
3
            if (del_ret == 0) {
866
3
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
867
3
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
868
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
869
                // so the recycling has been successful.
870
0
                ret = -1;
871
0
            }
872
3
        }
873
874
3
        if (ret != 0) {
875
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
876
0
            return ret;
877
0
        }
878
3
    }
879
880
    // delete all kv
881
3
    std::unique_ptr<Transaction> txn;
882
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
883
3
    if (err != TxnErrorCode::TXN_OK) {
884
0
        LOG(WARNING) << "failed to create txn";
885
0
        ret = -1;
886
0
        return -1;
887
0
    }
888
3
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
889
    // delete kv before deleting objects to prevent the checker from misjudging data loss
890
3
    std::string start_txn_key = txn_key_prefix(instance_id_);
891
3
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
892
3
    txn->remove(start_txn_key, end_txn_key);
893
3
    std::string start_version_key = version_key_prefix(instance_id_);
894
3
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
895
3
    txn->remove(start_version_key, end_version_key);
896
3
    std::string start_meta_key = meta_key_prefix(instance_id_);
897
3
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
898
3
    txn->remove(start_meta_key, end_meta_key);
899
3
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
900
3
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
901
3
    txn->remove(start_recycle_key, end_recycle_key);
902
3
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
903
3
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
904
3
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
905
3
    std::string start_copy_key = copy_key_prefix(instance_id_);
906
3
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
907
3
    txn->remove(start_copy_key, end_copy_key);
908
    // should not remove job key range, because we need to reserve job recycle kv
909
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
910
3
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
911
3
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
912
3
    txn->remove(start_job_tablet_key, end_job_tablet_key);
913
3
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
914
3
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
915
3
    std::string start_vault_key = storage_vault_key(key_info0);
916
3
    std::string end_vault_key = storage_vault_key(key_info1);
917
3
    txn->remove(start_vault_key, end_vault_key);
918
3
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
919
3
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
920
3
    txn->remove(versioned_version_key_start, versioned_version_key_end);
921
3
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
922
3
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
923
3
    txn->remove(versioned_index_key_start, versioned_index_key_end);
924
3
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
925
3
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
926
3
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
927
3
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
928
3
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
929
3
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
930
3
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
931
3
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
932
3
    txn->remove(versioned_data_key_start, versioned_data_key_end);
933
3
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
934
3
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
935
3
    txn->remove(versioned_log_key_start, versioned_log_key_end);
936
3
    err = txn->commit();
937
3
    if (err != TxnErrorCode::TXN_OK) {
938
0
        LOG(WARNING) << "failed to delete all kv, instance_id=" << instance_id_ << ", err=" << err;
939
0
        ret = -1;
940
0
    }
941
942
3
    if (ret == 0) {
943
        // remove instance kv
944
        // ATTN: MUST ensure that cloud platform won't regenerate the same instance id
945
3
        err = txn_kv_->create_txn(&txn);
946
3
        if (err != TxnErrorCode::TXN_OK) {
947
0
            LOG(WARNING) << "failed to create txn";
948
0
            ret = -1;
949
0
            return ret;
950
0
        }
951
3
        std::string key;
952
3
        instance_key({instance_id_}, &key);
953
3
        txn->atomic_add(system_meta_service_instance_update_key(), 1);
954
3
        txn->remove(key);
955
3
        err = txn->commit();
956
3
        if (err != TxnErrorCode::TXN_OK) {
957
0
            LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
958
0
                         << " err=" << err;
959
0
            ret = -1;
960
0
        }
961
3
    }
962
3
    return ret;
963
3
}
964
965
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
966
9
                                          bool* exists, PackedFileRecycleStats* stats) {
967
9
    if (exists == nullptr) {
968
0
        return -1;
969
0
    }
970
9
    *exists = false;
971
972
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
973
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
974
9
    std::string scan_begin = begin;
975
976
9
    while (true) {
977
9
        std::unique_ptr<RangeGetIterator> it_range;
978
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
979
9
        if (get_ret < 0) {
980
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
981
0
                    .tag("instance_id", instance_id_)
982
0
                    .tag("tablet_id", tablet_id)
983
0
                    .tag("ret", get_ret);
984
0
            return -1;
985
0
        }
986
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
987
6
            return 0;
988
6
        }
989
990
3
        std::string last_key;
991
3
        while (it_range->has_next()) {
992
3
            auto [k, v] = it_range->next();
993
3
            last_key.assign(k.data(), k.size());
994
3
            doris::RowsetMetaCloudPB rowset_meta;
995
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
996
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
997
0
                        .tag("instance_id", instance_id_)
998
0
                        .tag("tablet_id", tablet_id)
999
0
                        .tag("key", hex(k));
1000
0
                continue;
1001
0
            }
1002
3
            if (stats) {
1003
3
                ++stats->rowset_scan_count;
1004
3
            }
1005
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1006
3
                *exists = true;
1007
3
                return 0;
1008
3
            }
1009
3
        }
1010
1011
0
        if (!it_range->more()) {
1012
0
            return 0;
1013
0
        }
1014
1015
        // Continue scanning from the next key to keep each transaction short.
1016
0
        scan_begin = std::move(last_key);
1017
0
        scan_begin.push_back('\x00');
1018
0
    }
1019
9
}
1020
1021
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1022
                                                          const std::string& rowset_id,
1023
                                                          int64_t txn_id, bool* recycle_exists,
1024
11
                                                          bool* tmp_exists) {
1025
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1026
0
        return -1;
1027
0
    }
1028
11
    *recycle_exists = false;
1029
11
    *tmp_exists = false;
1030
1031
11
    if (txn_id <= 0) {
1032
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1033
0
                .tag("instance_id", instance_id_)
1034
0
                .tag("tablet_id", tablet_id)
1035
0
                .tag("rowset_id", rowset_id)
1036
0
                .tag("txn_id", txn_id);
1037
0
        return -1;
1038
0
    }
1039
1040
11
    std::unique_ptr<Transaction> txn;
1041
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1042
11
    if (err != TxnErrorCode::TXN_OK) {
1043
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1044
0
                .tag("instance_id", instance_id_)
1045
0
                .tag("tablet_id", tablet_id)
1046
0
                .tag("rowset_id", rowset_id)
1047
0
                .tag("txn_id", txn_id)
1048
0
                .tag("err", err);
1049
0
        return -1;
1050
0
    }
1051
1052
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1053
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1054
11
    if (ret == TxnErrorCode::TXN_OK) {
1055
1
        *recycle_exists = true;
1056
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1057
0
        LOG_WARNING("failed to check recycle rowset existence")
1058
0
                .tag("instance_id", instance_id_)
1059
0
                .tag("tablet_id", tablet_id)
1060
0
                .tag("rowset_id", rowset_id)
1061
0
                .tag("key", hex(recycle_key))
1062
0
                .tag("err", ret);
1063
0
        return -1;
1064
0
    }
1065
1066
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1067
11
    ret = key_exists(txn.get(), tmp_key, true);
1068
11
    if (ret == TxnErrorCode::TXN_OK) {
1069
1
        *tmp_exists = true;
1070
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1071
0
        LOG_WARNING("failed to check tmp rowset existence")
1072
0
                .tag("instance_id", instance_id_)
1073
0
                .tag("tablet_id", tablet_id)
1074
0
                .tag("txn_id", txn_id)
1075
0
                .tag("key", hex(tmp_key))
1076
0
                .tag("err", ret);
1077
0
        return -1;
1078
0
    }
1079
1080
11
    return 0;
1081
11
}
1082
1083
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1084
8
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1085
8
    if (!hint.empty()) {
1086
8
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1087
8
            return {hint, it->second};
1088
8
        }
1089
8
    }
1090
1091
0
    return {"", nullptr};
1092
8
}
1093
1094
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1095
                                               const std::string& packed_file_path,
1096
3
                                               PackedFileRecycleStats* stats) {
1097
3
    bool local_changed = false;
1098
3
    int64_t left_num = 0;
1099
3
    int64_t left_bytes = 0;
1100
3
    bool all_small_files_confirmed = true;
1101
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1102
1103
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1104
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1105
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1106
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1107
14
        LOG_INFO("packed slice correction status")
1108
14
                .tag("instance_id", instance_id_)
1109
14
                .tag("packed_file_path", packed_file_path)
1110
14
                .tag("small_file_path", file.path())
1111
14
                .tag("tablet_id", tablet_id)
1112
14
                .tag("rowset_id", rowset_id)
1113
14
                .tag("txn_id", txn_id)
1114
14
                .tag("size", file.size())
1115
14
                .tag("deleted", file.deleted())
1116
14
                .tag("corrected", file.corrected())
1117
14
                .tag("confirmed_this_round", confirmed_this_round);
1118
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24correct_packed_file_infoEPNS0_16PackedFileInfoPBEPbRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS1_22PackedFileRecycleStatsEENK3$_0clERKNS0_13PackedSlicePBEb
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24correct_packed_file_infoEPNS0_16PackedFileInfoPBEPbRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS1_22PackedFileRecycleStatsEENK3$_0clERKNS0_13PackedSlicePBEb
Line
Count
Source
1103
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1104
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1105
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1106
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1107
14
        LOG_INFO("packed slice correction status")
1108
14
                .tag("instance_id", instance_id_)
1109
14
                .tag("packed_file_path", packed_file_path)
1110
14
                .tag("small_file_path", file.path())
1111
14
                .tag("tablet_id", tablet_id)
1112
14
                .tag("rowset_id", rowset_id)
1113
14
                .tag("txn_id", txn_id)
1114
14
                .tag("size", file.size())
1115
14
                .tag("deleted", file.deleted())
1116
14
                .tag("corrected", file.corrected())
1117
14
                .tag("confirmed_this_round", confirmed_this_round);
1118
14
    };
1119
1120
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1121
14
        auto* small_file = packed_info->mutable_slices(i);
1122
14
        if (small_file->deleted()) {
1123
3
            log_small_file_status(*small_file, small_file->corrected());
1124
3
            continue;
1125
3
        }
1126
1127
11
        if (small_file->corrected()) {
1128
0
            left_num++;
1129
0
            left_bytes += small_file->size();
1130
0
            log_small_file_status(*small_file, true);
1131
0
            continue;
1132
0
        }
1133
1134
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1135
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1136
0
                    .tag("instance_id", instance_id_)
1137
0
                    .tag("small_file_path", small_file->path())
1138
0
                    .tag("index", i);
1139
0
            return -1;
1140
0
        }
1141
1142
11
        int64_t tablet_id = small_file->tablet_id();
1143
11
        const std::string& rowset_id = small_file->rowset_id();
1144
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1145
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1146
0
                    .tag("instance_id", instance_id_)
1147
0
                    .tag("small_file_path", small_file->path())
1148
0
                    .tag("index", i)
1149
0
                    .tag("tablet_id", tablet_id)
1150
0
                    .tag("rowset_id", rowset_id)
1151
0
                    .tag("has_txn_id", small_file->has_txn_id())
1152
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1153
0
            return -1;
1154
0
        }
1155
11
        int64_t txn_id = small_file->txn_id();
1156
11
        bool recycle_exists = false;
1157
11
        bool tmp_exists = false;
1158
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1159
11
                                                &tmp_exists) != 0) {
1160
0
            return -1;
1161
0
        }
1162
1163
11
        bool small_file_confirmed = false;
1164
11
        if (tmp_exists) {
1165
1
            left_num++;
1166
1
            left_bytes += small_file->size();
1167
1
            small_file_confirmed = true;
1168
10
        } else if (recycle_exists) {
1169
1
            left_num++;
1170
1
            left_bytes += small_file->size();
1171
            // keep small_file_confirmed=false so the packed file remains uncorrected
1172
9
        } else {
1173
9
            bool rowset_exists = false;
1174
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1175
0
                return -1;
1176
0
            }
1177
1178
9
            if (!rowset_exists) {
1179
6
                if (!small_file->deleted()) {
1180
6
                    small_file->set_deleted(true);
1181
6
                    local_changed = true;
1182
6
                }
1183
6
                if (!small_file->corrected()) {
1184
6
                    small_file->set_corrected(true);
1185
6
                    local_changed = true;
1186
6
                }
1187
6
                small_file_confirmed = true;
1188
6
            } else {
1189
3
                left_num++;
1190
3
                left_bytes += small_file->size();
1191
3
                small_file_confirmed = true;
1192
3
            }
1193
9
        }
1194
1195
11
        if (!small_file_confirmed) {
1196
1
            all_small_files_confirmed = false;
1197
1
        }
1198
1199
11
        if (small_file->corrected() != small_file_confirmed) {
1200
4
            small_file->set_corrected(small_file_confirmed);
1201
4
            local_changed = true;
1202
4
        }
1203
1204
11
        log_small_file_status(*small_file, small_file_confirmed);
1205
11
    }
1206
1207
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1208
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1209
3
        local_changed = true;
1210
3
    }
1211
3
    if (packed_info->ref_cnt() != left_num) {
1212
3
        auto old_ref_cnt = packed_info->ref_cnt();
1213
3
        packed_info->set_ref_cnt(left_num);
1214
3
        LOG_INFO("corrected packed file ref count")
1215
3
                .tag("instance_id", instance_id_)
1216
3
                .tag("resource_id", packed_info->resource_id())
1217
3
                .tag("packed_file_path", packed_file_path)
1218
3
                .tag("old_ref_cnt", old_ref_cnt)
1219
3
                .tag("new_ref_cnt", left_num);
1220
3
        local_changed = true;
1221
3
    }
1222
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1223
2
        packed_info->set_corrected(all_small_files_confirmed);
1224
2
        local_changed = true;
1225
2
    }
1226
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1227
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1228
1
        local_changed = true;
1229
1
    }
1230
1231
3
    if (changed != nullptr) {
1232
3
        *changed = local_changed;
1233
3
    }
1234
3
    return 0;
1235
3
}
1236
1237
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1238
                                                 const std::string& packed_file_path,
1239
4
                                                 PackedFileRecycleStats* stats) {
1240
4
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1241
4
    bool correction_ok = false;
1242
4
    cloud::PackedFileInfoPB packed_info;
1243
1244
4
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1245
4
        if (stopped()) {
1246
0
            LOG_WARNING("recycler stopped before processing packed file")
1247
0
                    .tag("instance_id", instance_id_)
1248
0
                    .tag("packed_file_path", packed_file_path)
1249
0
                    .tag("attempt", attempt);
1250
0
            return -1;
1251
0
        }
1252
1253
4
        std::unique_ptr<Transaction> txn;
1254
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1255
4
        if (err != TxnErrorCode::TXN_OK) {
1256
0
            LOG_WARNING("failed to create txn when processing packed file")
1257
0
                    .tag("instance_id", instance_id_)
1258
0
                    .tag("packed_file_path", packed_file_path)
1259
0
                    .tag("attempt", attempt)
1260
0
                    .tag("err", err);
1261
0
            return -1;
1262
0
        }
1263
1264
4
        std::string packed_val;
1265
4
        err = txn->get(packed_key, &packed_val);
1266
4
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1267
0
            return 0;
1268
0
        }
1269
4
        if (err != TxnErrorCode::TXN_OK) {
1270
0
            LOG_WARNING("failed to get packed file kv")
1271
0
                    .tag("instance_id", instance_id_)
1272
0
                    .tag("packed_file_path", packed_file_path)
1273
0
                    .tag("attempt", attempt)
1274
0
                    .tag("err", err);
1275
0
            return -1;
1276
0
        }
1277
1278
4
        if (!packed_info.ParseFromString(packed_val)) {
1279
0
            LOG_WARNING("failed to parse packed file info")
1280
0
                    .tag("instance_id", instance_id_)
1281
0
                    .tag("packed_file_path", packed_file_path)
1282
0
                    .tag("attempt", attempt);
1283
0
            return -1;
1284
0
        }
1285
1286
4
        int64_t now_sec = ::time(nullptr);
1287
4
        bool corrected = packed_info.corrected();
1288
4
        bool due = config::force_immediate_recycle ||
1289
4
                   now_sec - packed_info.created_at_sec() >=
1290
4
                           config::packed_file_correction_delay_seconds;
1291
1292
4
        if (!corrected && due) {
1293
3
            bool changed = false;
1294
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1295
0
                LOG_WARNING("correct_packed_file_info failed")
1296
0
                        .tag("instance_id", instance_id_)
1297
0
                        .tag("packed_file_path", packed_file_path)
1298
0
                        .tag("attempt", attempt);
1299
0
                return -1;
1300
0
            }
1301
3
            if (changed) {
1302
3
                std::string updated;
1303
3
                if (!packed_info.SerializeToString(&updated)) {
1304
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1305
0
                            .tag("instance_id", instance_id_)
1306
0
                            .tag("packed_file_path", packed_file_path)
1307
0
                            .tag("attempt", attempt);
1308
0
                    return -1;
1309
0
                }
1310
3
                txn->put(packed_key, updated);
1311
3
                err = txn->commit();
1312
3
                if (err == TxnErrorCode::TXN_OK) {
1313
3
                    if (stats) {
1314
3
                        ++stats->num_corrected;
1315
3
                    }
1316
3
                } else {
1317
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1318
0
                        LOG_WARNING(
1319
0
                                "failed to commit correction for packed file due to conflict, "
1320
0
                                "retrying")
1321
0
                                .tag("instance_id", instance_id_)
1322
0
                                .tag("packed_file_path", packed_file_path)
1323
0
                                .tag("attempt", attempt);
1324
0
                        sleep_for_packed_file_retry();
1325
0
                        packed_info.Clear();
1326
0
                        continue;
1327
0
                    }
1328
0
                    LOG_WARNING("failed to commit correction for packed file")
1329
0
                            .tag("instance_id", instance_id_)
1330
0
                            .tag("packed_file_path", packed_file_path)
1331
0
                            .tag("attempt", attempt)
1332
0
                            .tag("err", err);
1333
0
                    return -1;
1334
0
                }
1335
3
            }
1336
3
        }
1337
1338
4
        correction_ok = true;
1339
4
        break;
1340
4
    }
1341
1342
4
    if (!correction_ok) {
1343
0
        return -1;
1344
0
    }
1345
1346
4
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1347
4
          packed_info.ref_cnt() == 0)) {
1348
3
        return 0;
1349
3
    }
1350
1351
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1352
0
        LOG_WARNING("packed file missing resource id when recycling")
1353
0
                .tag("instance_id", instance_id_)
1354
0
                .tag("packed_file_path", packed_file_path);
1355
0
        return -1;
1356
0
    }
1357
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1358
1
    if (!accessor) {
1359
0
        LOG_WARNING("no accessor available to delete packed file")
1360
0
                .tag("instance_id", instance_id_)
1361
0
                .tag("packed_file_path", packed_file_path)
1362
0
                .tag("resource_id", packed_info.resource_id());
1363
0
        return -1;
1364
0
    }
1365
1
    int del_ret = accessor->delete_file(packed_file_path);
1366
1
    if (del_ret != 0 && del_ret != 1) {
1367
0
        LOG_WARNING("failed to delete packed file")
1368
0
                .tag("instance_id", instance_id_)
1369
0
                .tag("packed_file_path", packed_file_path)
1370
0
                .tag("resource_id", resource_id)
1371
0
                .tag("ret", del_ret);
1372
0
        return -1;
1373
0
    }
1374
1
    if (del_ret == 1) {
1375
0
        LOG_INFO("packed file already removed")
1376
0
                .tag("instance_id", instance_id_)
1377
0
                .tag("packed_file_path", packed_file_path)
1378
0
                .tag("resource_id", resource_id);
1379
1
    } else {
1380
1
        LOG_INFO("deleted packed file")
1381
1
                .tag("instance_id", instance_id_)
1382
1
                .tag("packed_file_path", packed_file_path)
1383
1
                .tag("resource_id", resource_id);
1384
1
    }
1385
1386
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1387
1
        std::unique_ptr<Transaction> del_txn;
1388
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1389
1
        if (err != TxnErrorCode::TXN_OK) {
1390
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1391
0
                    .tag("instance_id", instance_id_)
1392
0
                    .tag("packed_file_path", packed_file_path)
1393
0
                    .tag("del_attempt", del_attempt)
1394
0
                    .tag("err", err);
1395
0
            return -1;
1396
0
        }
1397
1398
1
        std::string latest_val;
1399
1
        err = del_txn->get(packed_key, &latest_val);
1400
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1401
0
            return 0;
1402
0
        }
1403
1
        if (err != TxnErrorCode::TXN_OK) {
1404
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1405
0
                    .tag("instance_id", instance_id_)
1406
0
                    .tag("packed_file_path", packed_file_path)
1407
0
                    .tag("del_attempt", del_attempt)
1408
0
                    .tag("err", err);
1409
0
            return -1;
1410
0
        }
1411
1412
1
        cloud::PackedFileInfoPB latest_info;
1413
1
        if (!latest_info.ParseFromString(latest_val)) {
1414
0
            LOG_WARNING("failed to parse packed file info before removal")
1415
0
                    .tag("instance_id", instance_id_)
1416
0
                    .tag("packed_file_path", packed_file_path)
1417
0
                    .tag("del_attempt", del_attempt);
1418
0
            return -1;
1419
0
        }
1420
1421
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1422
1
              latest_info.ref_cnt() == 0)) {
1423
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1424
0
                    .tag("instance_id", instance_id_)
1425
0
                    .tag("packed_file_path", packed_file_path)
1426
0
                    .tag("del_attempt", del_attempt);
1427
0
            return 0;
1428
0
        }
1429
1430
1
        del_txn->remove(packed_key);
1431
1
        err = del_txn->commit();
1432
1
        if (err == TxnErrorCode::TXN_OK) {
1433
1
            if (stats) {
1434
1
                ++stats->num_deleted;
1435
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1436
1
                                        static_cast<int64_t>(latest_val.size());
1437
1
                if (del_ret == 0 || del_ret == 1) {
1438
1
                    ++stats->num_object_deleted;
1439
1
                    int64_t object_size = latest_info.total_slice_bytes();
1440
1
                    if (object_size <= 0) {
1441
0
                        object_size = packed_info.total_slice_bytes();
1442
0
                    }
1443
1
                    stats->bytes_object_deleted += object_size;
1444
1
                }
1445
1
            }
1446
1
            LOG_INFO("removed packed file metadata")
1447
1
                    .tag("instance_id", instance_id_)
1448
1
                    .tag("packed_file_path", packed_file_path);
1449
1
            return 0;
1450
1
        }
1451
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1452
0
            if (del_attempt >= max_retry_times) {
1453
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1454
0
                        .tag("instance_id", instance_id_)
1455
0
                        .tag("packed_file_path", packed_file_path)
1456
0
                        .tag("del_attempt", del_attempt);
1457
0
                return -1;
1458
0
            }
1459
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1460
0
                    .tag("instance_id", instance_id_)
1461
0
                    .tag("packed_file_path", packed_file_path)
1462
0
                    .tag("del_attempt", del_attempt);
1463
0
            sleep_for_packed_file_retry();
1464
0
            continue;
1465
0
        }
1466
0
        LOG_WARNING("failed to remove packed file kv")
1467
0
                .tag("instance_id", instance_id_)
1468
0
                .tag("packed_file_path", packed_file_path)
1469
0
                .tag("del_attempt", del_attempt)
1470
0
                .tag("err", err);
1471
0
        return -1;
1472
0
    }
1473
1474
0
    return -1;
1475
1
}
1476
1477
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view /*value*/,
1478
4
                                            PackedFileRecycleStats* stats, int* ret) {
1479
4
    if (stats) {
1480
4
        ++stats->num_scanned;
1481
4
    }
1482
4
    std::string packed_file_path;
1483
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1484
0
        LOG_WARNING("failed to decode packed file key")
1485
0
                .tag("instance_id", instance_id_)
1486
0
                .tag("key", hex(key));
1487
0
        if (stats) {
1488
0
            ++stats->num_failed;
1489
0
        }
1490
0
        if (ret) {
1491
0
            *ret = -1;
1492
0
        }
1493
0
        return 0;
1494
0
    }
1495
1496
4
    std::string packed_key(key);
1497
4
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1498
4
    if (process_ret != 0) {
1499
0
        if (stats) {
1500
0
            ++stats->num_failed;
1501
0
        }
1502
0
        if (ret) {
1503
0
            *ret = -1;
1504
0
        }
1505
0
    }
1506
4
    return 0;
1507
4
}
1508
1509
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1510
9.77k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1511
9.77k
    if (config::force_immediate_recycle) {
1512
15
        return 0L;
1513
15
    }
1514
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1515
9.75k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1516
9.75k
    int64_t retention_seconds = config::retention_seconds;
1517
9.75k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1518
7.80k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1519
7.80k
    }
1520
9.75k
    int64_t final_expiration = expiration + retention_seconds;
1521
9.75k
    if (*earlest_ts > final_expiration) {
1522
7
        *earlest_ts = final_expiration;
1523
7
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1524
7
    }
1525
9.75k
    return final_expiration;
1526
9.77k
}
1527
1528
int64_t calculate_partition_expired_time(
1529
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1530
9
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1531
9
    if (config::force_immediate_recycle) {
1532
3
        return 0L;
1533
3
    }
1534
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1535
6
                                                            : partition_meta_pb.creation_time();
1536
6
    int64_t retention_seconds = config::retention_seconds;
1537
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1538
6
        retention_seconds =
1539
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1540
6
    }
1541
6
    int64_t final_expiration = expiration + retention_seconds;
1542
6
    if (*earlest_ts > final_expiration) {
1543
2
        *earlest_ts = final_expiration;
1544
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1545
2
    }
1546
6
    return final_expiration;
1547
9
}
1548
1549
int64_t calculate_index_expired_time(const std::string& instance_id_,
1550
                                     const RecycleIndexPB& index_meta_pb,
1551
10
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1552
10
    if (config::force_immediate_recycle) {
1553
4
        return 0L;
1554
4
    }
1555
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1556
6
                                                        : index_meta_pb.creation_time();
1557
6
    int64_t retention_seconds = config::retention_seconds;
1558
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1559
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1560
6
    }
1561
6
    int64_t final_expiration = expiration + retention_seconds;
1562
6
    if (*earlest_ts > final_expiration) {
1563
2
        *earlest_ts = final_expiration;
1564
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1565
2
    }
1566
6
    return final_expiration;
1567
10
}
1568
1569
int64_t calculate_tmp_rowset_expired_time(
1570
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1571
102k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1572
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1573
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1574
    //  duration or timeout always < `retention_time` in practice.
1575
102k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1576
102k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1577
102k
                                 : tmp_rowset_meta_pb.creation_time();
1578
102k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1579
102k
    int64_t final_expiration = expiration + config::retention_seconds;
1580
102k
    if (*earlest_ts > final_expiration) {
1581
18
        *earlest_ts = final_expiration;
1582
18
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1583
18
    }
1584
102k
    return final_expiration;
1585
102k
}
1586
1587
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1588
30.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1589
30.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1590
30.0k
    if (*earlest_ts > final_expiration / 1000) {
1591
8
        *earlest_ts = final_expiration / 1000;
1592
8
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1593
8
    }
1594
30.0k
    return final_expiration;
1595
30.0k
}
1596
1597
int64_t calculate_restore_job_expired_time(
1598
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1599
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1600
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1601
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1602
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1603
        // final state, recycle immediately
1604
41
        return 0L;
1605
41
    }
1606
    // not final state, wait much longer than the FE's timeout(1 day)
1607
0
    int64_t last_modified_s =
1608
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1609
0
    int64_t expiration = restore_job.expired_at_s() > 0
1610
0
                                 ? last_modified_s + restore_job.expired_at_s()
1611
0
                                 : last_modified_s;
1612
0
    int64_t final_expiration = expiration + config::retention_seconds;
1613
0
    if (*earlest_ts > final_expiration) {
1614
0
        *earlest_ts = final_expiration;
1615
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1616
0
    }
1617
0
    return final_expiration;
1618
41
}
1619
1620
int get_meta_rowset_key(Transaction* txn, const std::string& instance_id, int64_t tablet_id,
1621
                        const std::string& rowset_id, int64_t start_version, int64_t end_version,
1622
0
                        bool load_key, bool* exist) {
1623
0
    std::string key =
1624
0
            load_key ? versioned::meta_rowset_load_key({instance_id, tablet_id, end_version})
1625
0
                     : versioned::meta_rowset_compact_key({instance_id, tablet_id, end_version});
1626
0
    RowsetMetaCloudPB rowset_meta;
1627
0
    Versionstamp version;
1628
0
    TxnErrorCode err = versioned::document_get(txn, key, &rowset_meta, &version);
1629
0
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1630
0
        VLOG_DEBUG << "not found load or compact meta_rowset_key."
1631
0
                   << " rowset_id=" << rowset_id << " start_version=" << start_version
1632
0
                   << " end_version=" << end_version << " key=" << hex(key);
1633
0
    } else if (err != TxnErrorCode::TXN_OK) {
1634
0
        LOG_INFO("failed to get load or compact meta_rowset_key.")
1635
0
                .tag("rowset_id", rowset_id)
1636
0
                .tag("start_version", start_version)
1637
0
                .tag("end_version", end_version)
1638
0
                .tag("key", hex(key))
1639
0
                .tag("error_code", err);
1640
0
        return -1;
1641
0
    } else if (rowset_meta.rowset_id_v2() == rowset_id) {
1642
0
        *exist = true;
1643
0
        VLOG_DEBUG << "found load or compact meta_rowset_key."
1644
0
                   << " rowset_id=" << rowset_id << " start_version=" << start_version
1645
0
                   << " end_version=" << end_version << " key=" << hex(key);
1646
0
    } else {
1647
0
        VLOG_DEBUG << "rowset_id does not match when find load or compact meta_rowset_key."
1648
0
                   << " rowset_id=" << rowset_id << " start_version=" << start_version
1649
0
                   << " end_version=" << end_version << " key=" << hex(key)
1650
0
                   << " found_rowset_id=" << rowset_meta.rowset_id_v2();
1651
0
    }
1652
0
    return 0;
1653
0
}
1654
1655
2
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1656
2
    AbortTxnRequest req;
1657
2
    TxnInfoPB txn_info;
1658
2
    MetaServiceCode code = MetaServiceCode::OK;
1659
2
    std::string msg;
1660
2
    std::stringstream ss;
1661
2
    std::unique_ptr<Transaction> txn;
1662
2
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1663
2
    if (err != TxnErrorCode::TXN_OK) {
1664
0
        LOG_WARNING("failed to create txn").tag("err", err);
1665
0
        return -1;
1666
0
    }
1667
1668
    // get txn index
1669
2
    TxnIndexPB txn_idx_pb;
1670
2
    auto index_key = txn_index_key({instance_id_, txn_id});
1671
2
    std::string index_val;
1672
2
    err = txn->get(index_key, &index_val);
1673
2
    if (err != TxnErrorCode::TXN_OK) {
1674
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1675
            // maybe recycled
1676
0
            LOG_INFO("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1677
0
                    .tag("key", hex(index_key))
1678
0
                    .tag("txn_id", txn_id);
1679
0
            return 0;
1680
0
        }
1681
0
        LOG_WARNING("failed to get txn index")
1682
0
                .tag("err", err)
1683
0
                .tag("key", hex(index_key))
1684
0
                .tag("txn_id", txn_id);
1685
0
        return -1;
1686
0
    }
1687
2
    if (!txn_idx_pb.ParseFromString(index_val)) {
1688
0
        LOG_WARNING("failed to parse txn index")
1689
0
                .tag("err", err)
1690
0
                .tag("key", hex(index_key))
1691
0
                .tag("txn_id", txn_id);
1692
0
        return -1;
1693
0
    }
1694
1695
2
    auto info_key = txn_info_key({instance_id_, txn_idx_pb.tablet_index().db_id(), txn_id});
1696
2
    std::string info_val;
1697
2
    err = txn->get(info_key, &info_val);
1698
2
    if (err != TxnErrorCode::TXN_OK) {
1699
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1700
            // maybe recycled
1701
0
            LOG_INFO("txn info not found, txn_id={} instance_id={}", txn_id, instance_id_)
1702
0
                    .tag("key", hex(info_key))
1703
0
                    .tag("txn_id", txn_id);
1704
0
            return 0;
1705
0
        }
1706
0
        LOG_WARNING("failed to get txn info")
1707
0
                .tag("err", err)
1708
0
                .tag("key", hex(info_key))
1709
0
                .tag("txn_id", txn_id);
1710
0
        return -1;
1711
0
    }
1712
2
    if (!txn_info.ParseFromString(info_val)) {
1713
0
        LOG_WARNING("failed to parse txn info")
1714
0
                .tag("err", err)
1715
0
                .tag("key", hex(info_key))
1716
0
                .tag("txn_id", txn_id);
1717
0
        return -1;
1718
0
    }
1719
1720
2
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
1721
0
        LOG_INFO("txn is not prepared status, txn_id={} status={}", txn_id, txn_info.status())
1722
0
                .tag("key", hex(info_key))
1723
0
                .tag("txn_id", txn_id);
1724
0
        return 0;
1725
0
    }
1726
1727
2
    req.set_txn_id(txn_id);
1728
1729
2
    LOG(INFO) << "begin abort txn for related rowset, txn_id=" << txn_id
1730
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString();
1731
1732
2
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
1733
2
    err = txn->commit();
1734
2
    if (err != TxnErrorCode::TXN_OK) {
1735
0
        code = cast_as<ErrCategory::COMMIT>(err);
1736
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
1737
0
        msg = ss.str();
1738
0
        return -1;
1739
0
    }
1740
1741
2
    LOG(INFO) << "finish abort txn for related rowset, txn_id=" << txn_id
1742
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString()
1743
2
              << " code=" << code << " msg=" << msg;
1744
1745
2
    return 0;
1746
2
}
1747
1748
4
int InstanceRecycler::abort_job_for_related_rowset(const RowsetMetaCloudPB& rowset_meta) {
1749
4
    FinishTabletJobRequest req;
1750
4
    FinishTabletJobResponse res;
1751
4
    req.set_action(FinishTabletJobRequest::ABORT);
1752
4
    MetaServiceCode code = MetaServiceCode::OK;
1753
4
    std::string msg;
1754
4
    std::stringstream ss;
1755
1756
4
    TabletIndexPB tablet_idx;
1757
4
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, rowset_meta.tablet_id(), tablet_idx);
1758
4
    if (ret == 1) {
1759
        // tablet maybe recycled, directly return 0
1760
1
        return 0;
1761
3
    } else if (ret != 0) {
1762
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << rowset_meta.tablet_id()
1763
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
1764
0
        return ret;
1765
0
    }
1766
1767
3
    std::unique_ptr<Transaction> txn;
1768
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1769
3
    if (err != TxnErrorCode::TXN_OK) {
1770
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
1771
0
        return -1;
1772
0
    }
1773
1774
3
    std::string job_key =
1775
3
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
1776
3
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
1777
3
    std::string job_val;
1778
3
    err = txn->get(job_key, &job_val);
1779
3
    if (err != TxnErrorCode::TXN_OK) {
1780
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1781
0
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
1782
0
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
1783
0
            return 0;
1784
0
        }
1785
0
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
1786
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
1787
0
                     << " key=" << hex(job_key);
1788
0
        return -1;
1789
0
    }
1790
1791
3
    TabletJobInfoPB job_pb;
1792
3
    if (!job_pb.ParseFromString(job_val)) {
1793
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
1794
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
1795
0
        return -1;
1796
0
    }
1797
1798
3
    std::string job_id {};
1799
3
    if (!job_pb.compaction().empty()) {
1800
2
        for (const auto& c : job_pb.compaction()) {
1801
2
            if (c.id() == rowset_meta.job_id()) {
1802
2
                job_id = c.id();
1803
2
                break;
1804
2
            }
1805
2
        }
1806
2
    } else if (job_pb.has_schema_change()) {
1807
1
        job_id = job_pb.schema_change().id();
1808
1
    }
1809
1810
3
    if (!job_id.empty() && rowset_meta.job_id() == job_id) {
1811
3
        LOG(INFO) << "begin to abort job for related rowset, job_id=" << rowset_meta.job_id()
1812
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
1813
3
        req.mutable_job()->CopyFrom(job_pb);
1814
3
        req.set_action(FinishTabletJobRequest::ABORT);
1815
3
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
1816
3
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
1817
3
                           ss);
1818
3
        if (code != MetaServiceCode::OK) {
1819
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
1820
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
1821
0
                         << " msg=" << msg;
1822
0
            return -1;
1823
0
        }
1824
3
        LOG(INFO) << "finish abort job for related rowset, job_id=" << rowset_meta.job_id()
1825
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
1826
3
                  << " code=" << code << " msg=" << msg;
1827
3
    } else {
1828
        // clang-format off
1829
0
        LOG(INFO) << "there is no job for related rowset, directly recycle rowset data"
1830
0
                  << ", instance_id=" << instance_id_ 
1831
0
                  << ", tablet_id=" << tablet_idx.tablet_id() 
1832
0
                  << ", job_id=" << job_id
1833
0
                  << ", rowset_id=" << rowset_meta.rowset_id_v2();
1834
        // clang-format on
1835
0
    }
1836
1837
3
    return 0;
1838
3
}
1839
1840
template <typename T>
1841
54.7k
int InstanceRecycler::abort_txn_or_job_for_recycle(T& rowset_meta_pb) {
1842
54.7k
    RowsetMetaCloudPB* rs_meta;
1843
54.7k
    RecycleRowsetPB::Type rowset_type = RecycleRowsetPB::PREPARE;
1844
1845
54.7k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1846
        // For keys that are not in the RecycleRowsetPB::PREPARE state
1847
        // we do not need to check the job or txn state
1848
        // because tmp_rowset_key already exists when this key is generated.
1849
3.75k
        rowset_type = rowset_meta_pb.type();
1850
3.75k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1851
51.0k
    } else {
1852
51.0k
        rs_meta = &rowset_meta_pb;
1853
51.0k
    }
1854
1855
54.7k
    DCHECK(rs_meta != nullptr);
1856
1857
    // compaction/sc will generate recycle_rowset_key for each input rowset with load_id
1858
    // we need skip them because the related txn has been finished
1859
    // load_rowset1 load_rowset2 => pick for compaction => compact_rowset
1860
    // compact_rowset1 compact_rowset2 => pick for compaction/sc job => new_rowset
1861
54.7k
    if (rowset_type == RecycleRowsetPB::PREPARE) {
1862
51.6k
        if (rs_meta->has_load_id()) {
1863
            // load
1864
2
            return abort_txn_for_related_rowset(rs_meta->txn_id());
1865
51.6k
        } else if (rs_meta->has_job_id()) {
1866
            // compaction / schema change
1867
3
            return abort_job_for_related_rowset(*rs_meta);
1868
3
        }
1869
51.6k
    }
1870
1871
54.7k
    return 0;
1872
54.7k
}
_ZN5doris5cloud16InstanceRecycler28abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRT_
Line
Count
Source
1841
3.75k
int InstanceRecycler::abort_txn_or_job_for_recycle(T& rowset_meta_pb) {
1842
3.75k
    RowsetMetaCloudPB* rs_meta;
1843
3.75k
    RecycleRowsetPB::Type rowset_type = RecycleRowsetPB::PREPARE;
1844
1845
3.75k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1846
        // For keys that are not in the RecycleRowsetPB::PREPARE state
1847
        // we do not need to check the job or txn state
1848
        // because tmp_rowset_key already exists when this key is generated.
1849
3.75k
        rowset_type = rowset_meta_pb.type();
1850
3.75k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1851
3.75k
    } else {
1852
3.75k
        rs_meta = &rowset_meta_pb;
1853
3.75k
    }
1854
1855
3.75k
    DCHECK(rs_meta != nullptr);
1856
1857
    // compaction/sc will generate recycle_rowset_key for each input rowset with load_id
1858
    // we need skip them because the related txn has been finished
1859
    // load_rowset1 load_rowset2 => pick for compaction => compact_rowset
1860
    // compact_rowset1 compact_rowset2 => pick for compaction/sc job => new_rowset
1861
3.75k
    if (rowset_type == RecycleRowsetPB::PREPARE) {
1862
652
        if (rs_meta->has_load_id()) {
1863
            // load
1864
1
            return abort_txn_for_related_rowset(rs_meta->txn_id());
1865
651
        } else if (rs_meta->has_job_id()) {
1866
            // compaction / schema change
1867
1
            return abort_job_for_related_rowset(*rs_meta);
1868
1
        }
1869
652
    }
1870
1871
3.75k
    return 0;
1872
3.75k
}
_ZN5doris5cloud16InstanceRecycler28abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRT_
Line
Count
Source
1841
51.0k
int InstanceRecycler::abort_txn_or_job_for_recycle(T& rowset_meta_pb) {
1842
51.0k
    RowsetMetaCloudPB* rs_meta;
1843
51.0k
    RecycleRowsetPB::Type rowset_type = RecycleRowsetPB::PREPARE;
1844
1845
51.0k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1846
        // For keys that are not in the RecycleRowsetPB::PREPARE state
1847
        // we do not need to check the job or txn state
1848
        // because tmp_rowset_key already exists when this key is generated.
1849
51.0k
        rowset_type = rowset_meta_pb.type();
1850
51.0k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1851
51.0k
    } else {
1852
51.0k
        rs_meta = &rowset_meta_pb;
1853
51.0k
    }
1854
1855
51.0k
    DCHECK(rs_meta != nullptr);
1856
1857
    // compaction/sc will generate recycle_rowset_key for each input rowset with load_id
1858
    // we need skip them because the related txn has been finished
1859
    // load_rowset1 load_rowset2 => pick for compaction => compact_rowset
1860
    // compact_rowset1 compact_rowset2 => pick for compaction/sc job => new_rowset
1861
51.0k
    if (rowset_type == RecycleRowsetPB::PREPARE) {
1862
51.0k
        if (rs_meta->has_load_id()) {
1863
            // load
1864
1
            return abort_txn_for_related_rowset(rs_meta->txn_id());
1865
51.0k
        } else if (rs_meta->has_job_id()) {
1866
            // compaction / schema change
1867
2
            return abort_job_for_related_rowset(*rs_meta);
1868
2
        }
1869
51.0k
    }
1870
1871
51.0k
    return 0;
1872
51.0k
}
1873
1874
template <typename T>
1875
int mark_rowset_as_recycled(TxnKv* txn_kv, const std::string& instance_id, std::string_view key,
1876
109k
                            T& rowset_meta_pb) {
1877
109k
    RowsetMetaCloudPB* rs_meta;
1878
1879
109k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1880
102k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1881
102k
    } else {
1882
102k
        rs_meta = &rowset_meta_pb;
1883
102k
    }
1884
1885
109k
    bool need_write_back = false;
1886
109k
    if ((!rs_meta->has_is_recycled() || !rs_meta->is_recycled())) {
1887
54.7k
        need_write_back = true;
1888
54.7k
        rs_meta->set_is_recycled(true);
1889
54.7k
    }
1890
1891
109k
    if (need_write_back) {
1892
54.7k
        std::unique_ptr<Transaction> txn;
1893
54.7k
        TxnErrorCode err = txn_kv->create_txn(&txn);
1894
54.7k
        if (err != TxnErrorCode::TXN_OK) {
1895
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1896
0
            return -1;
1897
0
        }
1898
        // double check becase of new transaction
1899
54.7k
        T rowset_meta;
1900
54.7k
        std::string val;
1901
54.7k
        err = txn->get(key, &val);
1902
54.7k
        if (!rowset_meta.ParseFromString(val)) {
1903
0
            LOG(WARNING) << "failed to parse rs_meta, instance_id=" << instance_id;
1904
0
            return -1;
1905
0
        }
1906
54.7k
        if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1907
51.0k
            rs_meta = rowset_meta.mutable_rowset_meta();
1908
51.0k
        } else {
1909
51.0k
            rs_meta = &rowset_meta;
1910
51.0k
        }
1911
54.7k
        if ((rs_meta->has_is_recycled() && rs_meta->is_recycled())) {
1912
0
            return 0;
1913
0
        }
1914
54.7k
        rs_meta->set_is_recycled(true);
1915
54.7k
        val.clear();
1916
54.7k
        rowset_meta.SerializeToString(&val);
1917
54.7k
        txn->put(key, val);
1918
54.7k
        err = txn->commit();
1919
54.7k
        if (err != TxnErrorCode::TXN_OK) {
1920
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
1921
0
            return -1;
1922
0
        }
1923
54.7k
    }
1924
109k
    return need_write_back ? 1 : 0;
1925
109k
}
_ZN5doris5cloud23mark_rowset_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS8_ERT_
Line
Count
Source
1876
7.50k
                            T& rowset_meta_pb) {
1877
7.50k
    RowsetMetaCloudPB* rs_meta;
1878
1879
7.50k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1880
7.50k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1881
7.50k
    } else {
1882
7.50k
        rs_meta = &rowset_meta_pb;
1883
7.50k
    }
1884
1885
7.50k
    bool need_write_back = false;
1886
7.50k
    if ((!rs_meta->has_is_recycled() || !rs_meta->is_recycled())) {
1887
3.75k
        need_write_back = true;
1888
3.75k
        rs_meta->set_is_recycled(true);
1889
3.75k
    }
1890
1891
7.50k
    if (need_write_back) {
1892
3.75k
        std::unique_ptr<Transaction> txn;
1893
3.75k
        TxnErrorCode err = txn_kv->create_txn(&txn);
1894
3.75k
        if (err != TxnErrorCode::TXN_OK) {
1895
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1896
0
            return -1;
1897
0
        }
1898
        // double check becase of new transaction
1899
3.75k
        T rowset_meta;
1900
3.75k
        std::string val;
1901
3.75k
        err = txn->get(key, &val);
1902
3.75k
        if (!rowset_meta.ParseFromString(val)) {
1903
0
            LOG(WARNING) << "failed to parse rs_meta, instance_id=" << instance_id;
1904
0
            return -1;
1905
0
        }
1906
3.75k
        if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1907
3.75k
            rs_meta = rowset_meta.mutable_rowset_meta();
1908
3.75k
        } else {
1909
3.75k
            rs_meta = &rowset_meta;
1910
3.75k
        }
1911
3.75k
        if ((rs_meta->has_is_recycled() && rs_meta->is_recycled())) {
1912
0
            return 0;
1913
0
        }
1914
3.75k
        rs_meta->set_is_recycled(true);
1915
3.75k
        val.clear();
1916
3.75k
        rowset_meta.SerializeToString(&val);
1917
3.75k
        txn->put(key, val);
1918
3.75k
        err = txn->commit();
1919
3.75k
        if (err != TxnErrorCode::TXN_OK) {
1920
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
1921
0
            return -1;
1922
0
        }
1923
3.75k
    }
1924
7.50k
    return need_write_back ? 1 : 0;
1925
7.50k
}
_ZN5doris5cloud23mark_rowset_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS8_ERT_
Line
Count
Source
1876
102k
                            T& rowset_meta_pb) {
1877
102k
    RowsetMetaCloudPB* rs_meta;
1878
1879
102k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1880
102k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1881
102k
    } else {
1882
102k
        rs_meta = &rowset_meta_pb;
1883
102k
    }
1884
1885
102k
    bool need_write_back = false;
1886
102k
    if ((!rs_meta->has_is_recycled() || !rs_meta->is_recycled())) {
1887
51.0k
        need_write_back = true;
1888
51.0k
        rs_meta->set_is_recycled(true);
1889
51.0k
    }
1890
1891
102k
    if (need_write_back) {
1892
51.0k
        std::unique_ptr<Transaction> txn;
1893
51.0k
        TxnErrorCode err = txn_kv->create_txn(&txn);
1894
51.0k
        if (err != TxnErrorCode::TXN_OK) {
1895
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1896
0
            return -1;
1897
0
        }
1898
        // double check becase of new transaction
1899
51.0k
        T rowset_meta;
1900
51.0k
        std::string val;
1901
51.0k
        err = txn->get(key, &val);
1902
51.0k
        if (!rowset_meta.ParseFromString(val)) {
1903
0
            LOG(WARNING) << "failed to parse rs_meta, instance_id=" << instance_id;
1904
0
            return -1;
1905
0
        }
1906
51.0k
        if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1907
51.0k
            rs_meta = rowset_meta.mutable_rowset_meta();
1908
51.0k
        } else {
1909
51.0k
            rs_meta = &rowset_meta;
1910
51.0k
        }
1911
51.0k
        if ((rs_meta->has_is_recycled() && rs_meta->is_recycled())) {
1912
0
            return 0;
1913
0
        }
1914
51.0k
        rs_meta->set_is_recycled(true);
1915
51.0k
        val.clear();
1916
51.0k
        rowset_meta.SerializeToString(&val);
1917
51.0k
        txn->put(key, val);
1918
51.0k
        err = txn->commit();
1919
51.0k
        if (err != TxnErrorCode::TXN_OK) {
1920
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
1921
0
            return -1;
1922
0
        }
1923
51.0k
    }
1924
102k
    return need_write_back ? 1 : 0;
1925
102k
}
1926
1927
0
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
1928
0
    const std::string task_name = "recycle_ref_rowsets";
1929
0
    *has_unrecycled_rowsets = false;
1930
1931
0
    std::string data_rowset_ref_count_key_start =
1932
0
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
1933
0
    std::string data_rowset_ref_count_key_end =
1934
0
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
1935
1936
0
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
1937
1938
0
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
1939
0
    register_recycle_task(task_name, start_time);
1940
1941
0
    DORIS_CLOUD_DEFER {
1942
0
        unregister_recycle_task(task_name);
1943
0
        int64_t cost =
1944
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
1945
0
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
1946
0
                .tag("instance_id", instance_id_);
1947
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
1948
1949
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
1950
0
    std::set<int64_t> tablets_with_refs;
1951
0
    int64_t num_scanned = 0;
1952
1953
0
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
1954
0
        ++num_scanned;
1955
0
        int64_t tablet_id;
1956
0
        std::string rowset_id;
1957
0
        std::string_view key(k);
1958
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
1959
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
1960
0
            return 0; // Continue scanning
1961
0
        }
1962
1963
0
        tablets_with_refs.insert(tablet_id);
1964
0
        return 0;
1965
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
1966
1967
0
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
1968
0
                         std::move(scan_func)) != 0) {
1969
0
        LOG_WARNING("failed to scan data rowset ref count keys");
1970
0
        return -1;
1971
0
    }
1972
1973
0
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
1974
0
             tablets_with_refs.size(), num_scanned)
1975
0
            .tag("instance_id", instance_id_);
1976
1977
    // Phase 2: Recycle each tablet
1978
0
    int64_t num_recycled_tablets = 0;
1979
0
    for (int64_t tablet_id : tablets_with_refs) {
1980
0
        if (stopped()) {
1981
0
            LOG_INFO("recycler stopped, skip remaining tablets")
1982
0
                    .tag("instance_id", instance_id_)
1983
0
                    .tag("tablets_processed", num_recycled_tablets)
1984
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
1985
0
            break;
1986
0
        }
1987
1988
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
1989
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
1990
0
            LOG_WARNING("failed to recycle tablet")
1991
0
                    .tag("instance_id", instance_id_)
1992
0
                    .tag("tablet_id", tablet_id);
1993
0
            return -1;
1994
0
        }
1995
0
        ++num_recycled_tablets;
1996
0
    }
1997
1998
0
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
1999
0
            .tag("instance_id", instance_id_)
2000
0
            .tag("total_tablets", tablets_with_refs.size());
2001
2002
    // Phase 3: Scan again to check if any ref count keys still exist
2003
0
    std::unique_ptr<Transaction> txn;
2004
0
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2005
0
    if (err != TxnErrorCode::TXN_OK) {
2006
0
        LOG_WARNING("failed to create txn for final check")
2007
0
                .tag("instance_id", instance_id_)
2008
0
                .tag("err", err);
2009
0
        return -1;
2010
0
    }
2011
2012
0
    std::unique_ptr<RangeGetIterator> iter;
2013
0
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2014
0
    if (err != TxnErrorCode::TXN_OK) {
2015
0
        LOG_WARNING("failed to create range iterator for final check")
2016
0
                .tag("instance_id", instance_id_)
2017
0
                .tag("err", err);
2018
0
        return -1;
2019
0
    }
2020
2021
0
    *has_unrecycled_rowsets = iter->has_next();
2022
0
    if (*has_unrecycled_rowsets) {
2023
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2024
0
                .tag("instance_id", instance_id_);
2025
0
    }
2026
2027
0
    return 0;
2028
0
}
2029
2030
17
int InstanceRecycler::recycle_indexes() {
2031
17
    const std::string task_name = "recycle_indexes";
2032
17
    int64_t num_scanned = 0;
2033
17
    int64_t num_expired = 0;
2034
17
    int64_t num_recycled = 0;
2035
17
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2036
2037
17
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2038
17
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2039
17
    std::string index_key0;
2040
17
    std::string index_key1;
2041
17
    recycle_index_key(index_key_info0, &index_key0);
2042
17
    recycle_index_key(index_key_info1, &index_key1);
2043
2044
17
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2045
2046
17
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2047
17
    register_recycle_task(task_name, start_time);
2048
2049
17
    DORIS_CLOUD_DEFER {
2050
17
        unregister_recycle_task(task_name);
2051
17
        int64_t cost =
2052
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2053
17
        metrics_context.finish_report();
2054
17
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2055
17
                .tag("instance_id", instance_id_)
2056
17
                .tag("num_scanned", num_scanned)
2057
17
                .tag("num_expired", num_expired)
2058
17
                .tag("num_recycled", num_recycled);
2059
17
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2049
2
    DORIS_CLOUD_DEFER {
2050
2
        unregister_recycle_task(task_name);
2051
2
        int64_t cost =
2052
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2053
2
        metrics_context.finish_report();
2054
2
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2055
2
                .tag("instance_id", instance_id_)
2056
2
                .tag("num_scanned", num_scanned)
2057
2
                .tag("num_expired", num_expired)
2058
2
                .tag("num_recycled", num_recycled);
2059
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2049
15
    DORIS_CLOUD_DEFER {
2050
15
        unregister_recycle_task(task_name);
2051
15
        int64_t cost =
2052
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2053
15
        metrics_context.finish_report();
2054
15
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2055
15
                .tag("instance_id", instance_id_)
2056
15
                .tag("num_scanned", num_scanned)
2057
15
                .tag("num_expired", num_expired)
2058
15
                .tag("num_recycled", num_recycled);
2059
15
    };
2060
2061
17
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2062
2063
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2064
17
    std::vector<std::string_view> index_keys;
2065
17
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2066
10
        ++num_scanned;
2067
10
        RecycleIndexPB index_pb;
2068
10
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2069
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2070
0
            return -1;
2071
0
        }
2072
10
        int64_t current_time = ::time(nullptr);
2073
10
        if (current_time <
2074
10
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2075
0
            return 0;
2076
0
        }
2077
10
        ++num_expired;
2078
        // decode index_id
2079
10
        auto k1 = k;
2080
10
        k1.remove_prefix(1);
2081
10
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2082
10
        decode_key(&k1, &out);
2083
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2084
10
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2085
10
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2086
10
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2087
10
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2088
        // Change state to RECYCLING
2089
10
        std::unique_ptr<Transaction> txn;
2090
10
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2091
10
        if (err != TxnErrorCode::TXN_OK) {
2092
0
            LOG_WARNING("failed to create txn").tag("err", err);
2093
0
            return -1;
2094
0
        }
2095
10
        std::string val;
2096
10
        err = txn->get(k, &val);
2097
10
        if (err ==
2098
10
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2099
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2100
0
            return 0;
2101
0
        }
2102
10
        if (err != TxnErrorCode::TXN_OK) {
2103
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2104
0
            return -1;
2105
0
        }
2106
10
        index_pb.Clear();
2107
10
        if (!index_pb.ParseFromString(val)) {
2108
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2109
0
            return -1;
2110
0
        }
2111
10
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2112
9
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2113
9
            txn->put(k, index_pb.SerializeAsString());
2114
9
            err = txn->commit();
2115
9
            if (err != TxnErrorCode::TXN_OK) {
2116
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2117
0
                return -1;
2118
0
            }
2119
9
        }
2120
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2121
1
            LOG_WARNING("failed to recycle tablets under index")
2122
1
                    .tag("table_id", index_pb.table_id())
2123
1
                    .tag("instance_id", instance_id_)
2124
1
                    .tag("index_id", index_id);
2125
1
            return -1;
2126
1
        }
2127
2128
9
        if (index_pb.has_db_id()) {
2129
            // Recycle the versioned keys
2130
3
            std::unique_ptr<Transaction> txn;
2131
3
            err = txn_kv_->create_txn(&txn);
2132
3
            if (err != TxnErrorCode::TXN_OK) {
2133
0
                LOG_WARNING("failed to create txn").tag("err", err);
2134
0
                return -1;
2135
0
            }
2136
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2137
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2138
3
            std::string index_inverted_key = versioned::index_inverted_key(
2139
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2140
3
            versioned_remove_all(txn.get(), meta_key);
2141
3
            txn->remove(index_key);
2142
3
            txn->remove(index_inverted_key);
2143
3
            err = txn->commit();
2144
3
            if (err != TxnErrorCode::TXN_OK) {
2145
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2146
0
                return -1;
2147
0
            }
2148
3
        }
2149
2150
9
        metrics_context.total_recycled_num = ++num_recycled;
2151
9
        metrics_context.report();
2152
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2153
9
        index_keys.push_back(k);
2154
9
        return 0;
2155
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2065
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2066
2
        ++num_scanned;
2067
2
        RecycleIndexPB index_pb;
2068
2
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2069
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2070
0
            return -1;
2071
0
        }
2072
2
        int64_t current_time = ::time(nullptr);
2073
2
        if (current_time <
2074
2
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2075
0
            return 0;
2076
0
        }
2077
2
        ++num_expired;
2078
        // decode index_id
2079
2
        auto k1 = k;
2080
2
        k1.remove_prefix(1);
2081
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2082
2
        decode_key(&k1, &out);
2083
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2084
2
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2085
2
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2086
2
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2087
2
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2088
        // Change state to RECYCLING
2089
2
        std::unique_ptr<Transaction> txn;
2090
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2091
2
        if (err != TxnErrorCode::TXN_OK) {
2092
0
            LOG_WARNING("failed to create txn").tag("err", err);
2093
0
            return -1;
2094
0
        }
2095
2
        std::string val;
2096
2
        err = txn->get(k, &val);
2097
2
        if (err ==
2098
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2099
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2100
0
            return 0;
2101
0
        }
2102
2
        if (err != TxnErrorCode::TXN_OK) {
2103
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2104
0
            return -1;
2105
0
        }
2106
2
        index_pb.Clear();
2107
2
        if (!index_pb.ParseFromString(val)) {
2108
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2109
0
            return -1;
2110
0
        }
2111
2
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2112
1
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2113
1
            txn->put(k, index_pb.SerializeAsString());
2114
1
            err = txn->commit();
2115
1
            if (err != TxnErrorCode::TXN_OK) {
2116
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2117
0
                return -1;
2118
0
            }
2119
1
        }
2120
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2121
1
            LOG_WARNING("failed to recycle tablets under index")
2122
1
                    .tag("table_id", index_pb.table_id())
2123
1
                    .tag("instance_id", instance_id_)
2124
1
                    .tag("index_id", index_id);
2125
1
            return -1;
2126
1
        }
2127
2128
1
        if (index_pb.has_db_id()) {
2129
            // Recycle the versioned keys
2130
1
            std::unique_ptr<Transaction> txn;
2131
1
            err = txn_kv_->create_txn(&txn);
2132
1
            if (err != TxnErrorCode::TXN_OK) {
2133
0
                LOG_WARNING("failed to create txn").tag("err", err);
2134
0
                return -1;
2135
0
            }
2136
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2137
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2138
1
            std::string index_inverted_key = versioned::index_inverted_key(
2139
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2140
1
            versioned_remove_all(txn.get(), meta_key);
2141
1
            txn->remove(index_key);
2142
1
            txn->remove(index_inverted_key);
2143
1
            err = txn->commit();
2144
1
            if (err != TxnErrorCode::TXN_OK) {
2145
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2146
0
                return -1;
2147
0
            }
2148
1
        }
2149
2150
1
        metrics_context.total_recycled_num = ++num_recycled;
2151
1
        metrics_context.report();
2152
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2153
1
        index_keys.push_back(k);
2154
1
        return 0;
2155
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2065
8
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2066
8
        ++num_scanned;
2067
8
        RecycleIndexPB index_pb;
2068
8
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2069
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2070
0
            return -1;
2071
0
        }
2072
8
        int64_t current_time = ::time(nullptr);
2073
8
        if (current_time <
2074
8
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2075
0
            return 0;
2076
0
        }
2077
8
        ++num_expired;
2078
        // decode index_id
2079
8
        auto k1 = k;
2080
8
        k1.remove_prefix(1);
2081
8
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2082
8
        decode_key(&k1, &out);
2083
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2084
8
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2085
8
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2086
8
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2087
8
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2088
        // Change state to RECYCLING
2089
8
        std::unique_ptr<Transaction> txn;
2090
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2091
8
        if (err != TxnErrorCode::TXN_OK) {
2092
0
            LOG_WARNING("failed to create txn").tag("err", err);
2093
0
            return -1;
2094
0
        }
2095
8
        std::string val;
2096
8
        err = txn->get(k, &val);
2097
8
        if (err ==
2098
8
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2099
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2100
0
            return 0;
2101
0
        }
2102
8
        if (err != TxnErrorCode::TXN_OK) {
2103
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2104
0
            return -1;
2105
0
        }
2106
8
        index_pb.Clear();
2107
8
        if (!index_pb.ParseFromString(val)) {
2108
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2109
0
            return -1;
2110
0
        }
2111
8
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2112
8
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2113
8
            txn->put(k, index_pb.SerializeAsString());
2114
8
            err = txn->commit();
2115
8
            if (err != TxnErrorCode::TXN_OK) {
2116
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2117
0
                return -1;
2118
0
            }
2119
8
        }
2120
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2121
0
            LOG_WARNING("failed to recycle tablets under index")
2122
0
                    .tag("table_id", index_pb.table_id())
2123
0
                    .tag("instance_id", instance_id_)
2124
0
                    .tag("index_id", index_id);
2125
0
            return -1;
2126
0
        }
2127
2128
8
        if (index_pb.has_db_id()) {
2129
            // Recycle the versioned keys
2130
2
            std::unique_ptr<Transaction> txn;
2131
2
            err = txn_kv_->create_txn(&txn);
2132
2
            if (err != TxnErrorCode::TXN_OK) {
2133
0
                LOG_WARNING("failed to create txn").tag("err", err);
2134
0
                return -1;
2135
0
            }
2136
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2137
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2138
2
            std::string index_inverted_key = versioned::index_inverted_key(
2139
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2140
2
            versioned_remove_all(txn.get(), meta_key);
2141
2
            txn->remove(index_key);
2142
2
            txn->remove(index_inverted_key);
2143
2
            err = txn->commit();
2144
2
            if (err != TxnErrorCode::TXN_OK) {
2145
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2146
0
                return -1;
2147
0
            }
2148
2
        }
2149
2150
8
        metrics_context.total_recycled_num = ++num_recycled;
2151
8
        metrics_context.report();
2152
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2153
8
        index_keys.push_back(k);
2154
8
        return 0;
2155
8
    };
2156
2157
17
    auto loop_done = [&index_keys, this]() -> int {
2158
6
        if (index_keys.empty()) return 0;
2159
5
        DORIS_CLOUD_DEFER {
2160
5
            index_keys.clear();
2161
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2159
1
        DORIS_CLOUD_DEFER {
2160
1
            index_keys.clear();
2161
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2159
4
        DORIS_CLOUD_DEFER {
2160
4
            index_keys.clear();
2161
4
        };
2162
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2163
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2164
0
            return -1;
2165
0
        }
2166
5
        return 0;
2167
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2157
2
    auto loop_done = [&index_keys, this]() -> int {
2158
2
        if (index_keys.empty()) return 0;
2159
1
        DORIS_CLOUD_DEFER {
2160
1
            index_keys.clear();
2161
1
        };
2162
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2163
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2164
0
            return -1;
2165
0
        }
2166
1
        return 0;
2167
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2157
4
    auto loop_done = [&index_keys, this]() -> int {
2158
4
        if (index_keys.empty()) return 0;
2159
4
        DORIS_CLOUD_DEFER {
2160
4
            index_keys.clear();
2161
4
        };
2162
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2163
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2164
0
            return -1;
2165
0
        }
2166
4
        return 0;
2167
4
    };
2168
2169
17
    if (config::enable_recycler_stats_metrics) {
2170
0
        scan_and_statistics_indexes();
2171
0
    }
2172
    // recycle_func and loop_done for scan and recycle
2173
17
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
2174
17
}
2175
2176
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
2177
8.24k
                             int64_t tablet_id) {
2178
8.24k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
2179
2180
8.24k
    std::unique_ptr<Transaction> txn;
2181
8.24k
    TxnErrorCode err = txn_kv->create_txn(&txn);
2182
8.24k
    if (err != TxnErrorCode::TXN_OK) {
2183
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
2184
0
                     << " tablet_id=" << tablet_id << " err=" << err;
2185
0
        return false;
2186
0
    }
2187
2188
8.24k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
2189
8.24k
    std::string tablet_idx_val;
2190
8.24k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
2191
8.24k
    if (TxnErrorCode::TXN_OK != err) {
2192
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
2193
0
                     << " tablet_id=" << tablet_id << " err=" << err
2194
0
                     << " key=" << hex(tablet_idx_key);
2195
0
        return false;
2196
0
    }
2197
2198
8.24k
    TabletIndexPB tablet_idx_pb;
2199
8.24k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
2200
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
2201
0
                     << " tablet_id=" << tablet_id;
2202
0
        return false;
2203
0
    }
2204
2205
8.24k
    if (!tablet_idx_pb.has_db_id()) {
2206
        // In the previous version, the db_id was not set in the index_pb.
2207
        // If updating to the version which enable txn lazy commit, the db_id will be set.
2208
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
2209
0
                  << " instance_id=" << instance_id
2210
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
2211
0
        return true;
2212
0
    }
2213
2214
8.24k
    std::string ver_val;
2215
8.24k
    std::string ver_key =
2216
8.24k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
2217
8.24k
                                   tablet_idx_pb.partition_id()});
2218
8.24k
    err = txn->get(ver_key, &ver_val);
2219
2220
8.24k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
2221
204
        LOG(INFO) << ""
2222
204
                     "partition version not found, instance_id="
2223
204
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
2224
204
                  << " table_id=" << tablet_idx_pb.table_id()
2225
204
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
2226
204
                  << " key=" << hex(ver_key);
2227
204
        return true;
2228
204
    }
2229
2230
8.03k
    if (TxnErrorCode::TXN_OK != err) {
2231
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
2232
0
                     << " db_id=" << tablet_idx_pb.db_id()
2233
0
                     << " table_id=" << tablet_idx_pb.table_id()
2234
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2235
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
2236
0
        return false;
2237
0
    }
2238
2239
8.03k
    VersionPB version_pb;
2240
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
2241
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
2242
0
                     << " db_id=" << tablet_idx_pb.db_id()
2243
0
                     << " table_id=" << tablet_idx_pb.table_id()
2244
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2245
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
2246
0
        return false;
2247
0
    }
2248
2249
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
2250
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
2251
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
2252
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
2253
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
2254
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
2255
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
2256
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
2257
4.00k
                     << " key=" << hex(ver_key);
2258
4.00k
        return false;
2259
4.00k
    }
2260
4.03k
    return true;
2261
8.03k
}
2262
2263
15
int InstanceRecycler::recycle_partitions() {
2264
15
    const std::string task_name = "recycle_partitions";
2265
15
    int64_t num_scanned = 0;
2266
15
    int64_t num_expired = 0;
2267
15
    int64_t num_recycled = 0;
2268
15
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2269
2270
15
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
2271
15
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
2272
15
    std::string part_key0;
2273
15
    std::string part_key1;
2274
15
    recycle_partition_key(part_key_info0, &part_key0);
2275
15
    recycle_partition_key(part_key_info1, &part_key1);
2276
2277
15
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
2278
2279
15
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2280
15
    register_recycle_task(task_name, start_time);
2281
2282
15
    DORIS_CLOUD_DEFER {
2283
15
        unregister_recycle_task(task_name);
2284
15
        int64_t cost =
2285
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2286
15
        metrics_context.finish_report();
2287
15
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2288
15
                .tag("instance_id", instance_id_)
2289
15
                .tag("num_scanned", num_scanned)
2290
15
                .tag("num_expired", num_expired)
2291
15
                .tag("num_recycled", num_recycled);
2292
15
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2282
2
    DORIS_CLOUD_DEFER {
2283
2
        unregister_recycle_task(task_name);
2284
2
        int64_t cost =
2285
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2286
2
        metrics_context.finish_report();
2287
2
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2288
2
                .tag("instance_id", instance_id_)
2289
2
                .tag("num_scanned", num_scanned)
2290
2
                .tag("num_expired", num_expired)
2291
2
                .tag("num_recycled", num_recycled);
2292
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2282
13
    DORIS_CLOUD_DEFER {
2283
13
        unregister_recycle_task(task_name);
2284
13
        int64_t cost =
2285
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2286
13
        metrics_context.finish_report();
2287
13
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2288
13
                .tag("instance_id", instance_id_)
2289
13
                .tag("num_scanned", num_scanned)
2290
13
                .tag("num_expired", num_expired)
2291
13
                .tag("num_recycled", num_recycled);
2292
13
    };
2293
2294
15
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2295
2296
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
2297
15
    std::vector<std::string_view> partition_keys;
2298
15
    std::vector<std::string> partition_version_keys;
2299
15
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2300
9
        ++num_scanned;
2301
9
        RecyclePartitionPB part_pb;
2302
9
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2303
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2304
0
            return -1;
2305
0
        }
2306
9
        int64_t current_time = ::time(nullptr);
2307
9
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2308
9
                                                            &earlest_ts)) { // not expired
2309
0
            return 0;
2310
0
        }
2311
9
        ++num_expired;
2312
        // decode partition_id
2313
9
        auto k1 = k;
2314
9
        k1.remove_prefix(1);
2315
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2316
9
        decode_key(&k1, &out);
2317
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2318
9
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2319
9
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2320
9
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2321
9
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2322
        // Change state to RECYCLING
2323
9
        std::unique_ptr<Transaction> txn;
2324
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2325
9
        if (err != TxnErrorCode::TXN_OK) {
2326
0
            LOG_WARNING("failed to create txn").tag("err", err);
2327
0
            return -1;
2328
0
        }
2329
9
        std::string val;
2330
9
        err = txn->get(k, &val);
2331
9
        if (err ==
2332
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2333
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2334
0
            return 0;
2335
0
        }
2336
9
        if (err != TxnErrorCode::TXN_OK) {
2337
0
            LOG_WARNING("failed to get kv");
2338
0
            return -1;
2339
0
        }
2340
9
        part_pb.Clear();
2341
9
        if (!part_pb.ParseFromString(val)) {
2342
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2343
0
            return -1;
2344
0
        }
2345
        // Partitions with PREPARED state MUST have no data
2346
9
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2347
8
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2348
8
            txn->put(k, part_pb.SerializeAsString());
2349
8
            err = txn->commit();
2350
8
            if (err != TxnErrorCode::TXN_OK) {
2351
0
                LOG_WARNING("failed to commit txn: {}", err);
2352
0
                return -1;
2353
0
            }
2354
8
        }
2355
2356
9
        int ret = 0;
2357
33
        for (int64_t index_id : part_pb.index_id()) {
2358
33
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2359
1
                LOG_WARNING("failed to recycle tablets under partition")
2360
1
                        .tag("table_id", part_pb.table_id())
2361
1
                        .tag("instance_id", instance_id_)
2362
1
                        .tag("index_id", index_id)
2363
1
                        .tag("partition_id", partition_id);
2364
1
                ret = -1;
2365
1
            }
2366
33
        }
2367
9
        if (ret == 0 && part_pb.has_db_id()) {
2368
            // Recycle the versioned keys
2369
8
            std::unique_ptr<Transaction> txn;
2370
8
            err = txn_kv_->create_txn(&txn);
2371
8
            if (err != TxnErrorCode::TXN_OK) {
2372
0
                LOG_WARNING("failed to create txn").tag("err", err);
2373
0
                return -1;
2374
0
            }
2375
8
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2376
8
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2377
8
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2378
8
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2379
8
            std::string partition_version_key =
2380
8
                    versioned::partition_version_key({instance_id_, partition_id});
2381
8
            versioned_remove_all(txn.get(), meta_key);
2382
8
            txn->remove(index_key);
2383
8
            txn->remove(inverted_index_key);
2384
8
            versioned_remove_all(txn.get(), partition_version_key);
2385
8
            err = txn->commit();
2386
8
            if (err != TxnErrorCode::TXN_OK) {
2387
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2388
0
                return -1;
2389
0
            }
2390
8
        }
2391
2392
9
        if (ret == 0) {
2393
8
            ++num_recycled;
2394
8
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2395
8
            partition_keys.push_back(k);
2396
8
            if (part_pb.db_id() > 0) {
2397
8
                partition_version_keys.push_back(partition_version_key(
2398
8
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2399
8
            }
2400
8
            metrics_context.total_recycled_num = num_recycled;
2401
8
            metrics_context.report();
2402
8
        }
2403
9
        return ret;
2404
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2299
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2300
2
        ++num_scanned;
2301
2
        RecyclePartitionPB part_pb;
2302
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2303
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2304
0
            return -1;
2305
0
        }
2306
2
        int64_t current_time = ::time(nullptr);
2307
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2308
2
                                                            &earlest_ts)) { // not expired
2309
0
            return 0;
2310
0
        }
2311
2
        ++num_expired;
2312
        // decode partition_id
2313
2
        auto k1 = k;
2314
2
        k1.remove_prefix(1);
2315
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2316
2
        decode_key(&k1, &out);
2317
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2318
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2319
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2320
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2321
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2322
        // Change state to RECYCLING
2323
2
        std::unique_ptr<Transaction> txn;
2324
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2325
2
        if (err != TxnErrorCode::TXN_OK) {
2326
0
            LOG_WARNING("failed to create txn").tag("err", err);
2327
0
            return -1;
2328
0
        }
2329
2
        std::string val;
2330
2
        err = txn->get(k, &val);
2331
2
        if (err ==
2332
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2333
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2334
0
            return 0;
2335
0
        }
2336
2
        if (err != TxnErrorCode::TXN_OK) {
2337
0
            LOG_WARNING("failed to get kv");
2338
0
            return -1;
2339
0
        }
2340
2
        part_pb.Clear();
2341
2
        if (!part_pb.ParseFromString(val)) {
2342
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2343
0
            return -1;
2344
0
        }
2345
        // Partitions with PREPARED state MUST have no data
2346
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2347
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2348
1
            txn->put(k, part_pb.SerializeAsString());
2349
1
            err = txn->commit();
2350
1
            if (err != TxnErrorCode::TXN_OK) {
2351
0
                LOG_WARNING("failed to commit txn: {}", err);
2352
0
                return -1;
2353
0
            }
2354
1
        }
2355
2356
2
        int ret = 0;
2357
2
        for (int64_t index_id : part_pb.index_id()) {
2358
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2359
1
                LOG_WARNING("failed to recycle tablets under partition")
2360
1
                        .tag("table_id", part_pb.table_id())
2361
1
                        .tag("instance_id", instance_id_)
2362
1
                        .tag("index_id", index_id)
2363
1
                        .tag("partition_id", partition_id);
2364
1
                ret = -1;
2365
1
            }
2366
2
        }
2367
2
        if (ret == 0 && part_pb.has_db_id()) {
2368
            // Recycle the versioned keys
2369
1
            std::unique_ptr<Transaction> txn;
2370
1
            err = txn_kv_->create_txn(&txn);
2371
1
            if (err != TxnErrorCode::TXN_OK) {
2372
0
                LOG_WARNING("failed to create txn").tag("err", err);
2373
0
                return -1;
2374
0
            }
2375
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2376
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2377
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2378
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2379
1
            std::string partition_version_key =
2380
1
                    versioned::partition_version_key({instance_id_, partition_id});
2381
1
            versioned_remove_all(txn.get(), meta_key);
2382
1
            txn->remove(index_key);
2383
1
            txn->remove(inverted_index_key);
2384
1
            versioned_remove_all(txn.get(), partition_version_key);
2385
1
            err = txn->commit();
2386
1
            if (err != TxnErrorCode::TXN_OK) {
2387
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2388
0
                return -1;
2389
0
            }
2390
1
        }
2391
2392
2
        if (ret == 0) {
2393
1
            ++num_recycled;
2394
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2395
1
            partition_keys.push_back(k);
2396
1
            if (part_pb.db_id() > 0) {
2397
1
                partition_version_keys.push_back(partition_version_key(
2398
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2399
1
            }
2400
1
            metrics_context.total_recycled_num = num_recycled;
2401
1
            metrics_context.report();
2402
1
        }
2403
2
        return ret;
2404
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2299
7
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2300
7
        ++num_scanned;
2301
7
        RecyclePartitionPB part_pb;
2302
7
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2303
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2304
0
            return -1;
2305
0
        }
2306
7
        int64_t current_time = ::time(nullptr);
2307
7
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2308
7
                                                            &earlest_ts)) { // not expired
2309
0
            return 0;
2310
0
        }
2311
7
        ++num_expired;
2312
        // decode partition_id
2313
7
        auto k1 = k;
2314
7
        k1.remove_prefix(1);
2315
7
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2316
7
        decode_key(&k1, &out);
2317
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2318
7
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2319
7
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2320
7
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2321
7
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2322
        // Change state to RECYCLING
2323
7
        std::unique_ptr<Transaction> txn;
2324
7
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2325
7
        if (err != TxnErrorCode::TXN_OK) {
2326
0
            LOG_WARNING("failed to create txn").tag("err", err);
2327
0
            return -1;
2328
0
        }
2329
7
        std::string val;
2330
7
        err = txn->get(k, &val);
2331
7
        if (err ==
2332
7
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2333
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2334
0
            return 0;
2335
0
        }
2336
7
        if (err != TxnErrorCode::TXN_OK) {
2337
0
            LOG_WARNING("failed to get kv");
2338
0
            return -1;
2339
0
        }
2340
7
        part_pb.Clear();
2341
7
        if (!part_pb.ParseFromString(val)) {
2342
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2343
0
            return -1;
2344
0
        }
2345
        // Partitions with PREPARED state MUST have no data
2346
7
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2347
7
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2348
7
            txn->put(k, part_pb.SerializeAsString());
2349
7
            err = txn->commit();
2350
7
            if (err != TxnErrorCode::TXN_OK) {
2351
0
                LOG_WARNING("failed to commit txn: {}", err);
2352
0
                return -1;
2353
0
            }
2354
7
        }
2355
2356
7
        int ret = 0;
2357
31
        for (int64_t index_id : part_pb.index_id()) {
2358
31
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2359
0
                LOG_WARNING("failed to recycle tablets under partition")
2360
0
                        .tag("table_id", part_pb.table_id())
2361
0
                        .tag("instance_id", instance_id_)
2362
0
                        .tag("index_id", index_id)
2363
0
                        .tag("partition_id", partition_id);
2364
0
                ret = -1;
2365
0
            }
2366
31
        }
2367
7
        if (ret == 0 && part_pb.has_db_id()) {
2368
            // Recycle the versioned keys
2369
7
            std::unique_ptr<Transaction> txn;
2370
7
            err = txn_kv_->create_txn(&txn);
2371
7
            if (err != TxnErrorCode::TXN_OK) {
2372
0
                LOG_WARNING("failed to create txn").tag("err", err);
2373
0
                return -1;
2374
0
            }
2375
7
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2376
7
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2377
7
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2378
7
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2379
7
            std::string partition_version_key =
2380
7
                    versioned::partition_version_key({instance_id_, partition_id});
2381
7
            versioned_remove_all(txn.get(), meta_key);
2382
7
            txn->remove(index_key);
2383
7
            txn->remove(inverted_index_key);
2384
7
            versioned_remove_all(txn.get(), partition_version_key);
2385
7
            err = txn->commit();
2386
7
            if (err != TxnErrorCode::TXN_OK) {
2387
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2388
0
                return -1;
2389
0
            }
2390
7
        }
2391
2392
7
        if (ret == 0) {
2393
7
            ++num_recycled;
2394
7
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2395
7
            partition_keys.push_back(k);
2396
7
            if (part_pb.db_id() > 0) {
2397
7
                partition_version_keys.push_back(partition_version_key(
2398
7
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2399
7
            }
2400
7
            metrics_context.total_recycled_num = num_recycled;
2401
7
            metrics_context.report();
2402
7
        }
2403
7
        return ret;
2404
7
    };
2405
2406
15
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2407
5
        if (partition_keys.empty()) return 0;
2408
4
        DORIS_CLOUD_DEFER {
2409
4
            partition_keys.clear();
2410
4
            partition_version_keys.clear();
2411
4
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2408
1
        DORIS_CLOUD_DEFER {
2409
1
            partition_keys.clear();
2410
1
            partition_version_keys.clear();
2411
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2408
3
        DORIS_CLOUD_DEFER {
2409
3
            partition_keys.clear();
2410
3
            partition_version_keys.clear();
2411
3
        };
2412
4
        std::unique_ptr<Transaction> txn;
2413
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2414
4
        if (err != TxnErrorCode::TXN_OK) {
2415
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2416
0
            return -1;
2417
0
        }
2418
8
        for (auto& k : partition_keys) {
2419
8
            txn->remove(k);
2420
8
        }
2421
8
        for (auto& k : partition_version_keys) {
2422
8
            txn->remove(k);
2423
8
        }
2424
4
        err = txn->commit();
2425
4
        if (err != TxnErrorCode::TXN_OK) {
2426
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2427
0
                         << " err=" << err;
2428
0
            return -1;
2429
0
        }
2430
4
        return 0;
2431
4
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2406
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2407
2
        if (partition_keys.empty()) return 0;
2408
1
        DORIS_CLOUD_DEFER {
2409
1
            partition_keys.clear();
2410
1
            partition_version_keys.clear();
2411
1
        };
2412
1
        std::unique_ptr<Transaction> txn;
2413
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2414
1
        if (err != TxnErrorCode::TXN_OK) {
2415
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2416
0
            return -1;
2417
0
        }
2418
1
        for (auto& k : partition_keys) {
2419
1
            txn->remove(k);
2420
1
        }
2421
1
        for (auto& k : partition_version_keys) {
2422
1
            txn->remove(k);
2423
1
        }
2424
1
        err = txn->commit();
2425
1
        if (err != TxnErrorCode::TXN_OK) {
2426
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2427
0
                         << " err=" << err;
2428
0
            return -1;
2429
0
        }
2430
1
        return 0;
2431
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2406
3
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2407
3
        if (partition_keys.empty()) return 0;
2408
3
        DORIS_CLOUD_DEFER {
2409
3
            partition_keys.clear();
2410
3
            partition_version_keys.clear();
2411
3
        };
2412
3
        std::unique_ptr<Transaction> txn;
2413
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2414
3
        if (err != TxnErrorCode::TXN_OK) {
2415
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2416
0
            return -1;
2417
0
        }
2418
7
        for (auto& k : partition_keys) {
2419
7
            txn->remove(k);
2420
7
        }
2421
7
        for (auto& k : partition_version_keys) {
2422
7
            txn->remove(k);
2423
7
        }
2424
3
        err = txn->commit();
2425
3
        if (err != TxnErrorCode::TXN_OK) {
2426
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2427
0
                         << " err=" << err;
2428
0
            return -1;
2429
0
        }
2430
3
        return 0;
2431
3
    };
2432
2433
15
    if (config::enable_recycler_stats_metrics) {
2434
0
        scan_and_statistics_partitions();
2435
0
    }
2436
    // recycle_func and loop_done for scan and recycle
2437
15
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
2438
15
}
2439
2440
14
int InstanceRecycler::recycle_versions() {
2441
14
    if (should_recycle_versioned_keys()) {
2442
2
        return recycle_orphan_partitions();
2443
2
    }
2444
2445
12
    int64_t num_scanned = 0;
2446
12
    int64_t num_recycled = 0;
2447
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
2448
2449
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
2450
2451
12
    auto start_time = steady_clock::now();
2452
2453
12
    DORIS_CLOUD_DEFER {
2454
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2455
12
        metrics_context.finish_report();
2456
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
2457
12
                .tag("instance_id", instance_id_)
2458
12
                .tag("num_scanned", num_scanned)
2459
12
                .tag("num_recycled", num_recycled);
2460
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
2453
12
    DORIS_CLOUD_DEFER {
2454
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2455
12
        metrics_context.finish_report();
2456
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
2457
12
                .tag("instance_id", instance_id_)
2458
12
                .tag("num_scanned", num_scanned)
2459
12
                .tag("num_recycled", num_recycled);
2460
12
    };
2461
2462
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
2463
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
2464
12
    int64_t last_scanned_table_id = 0;
2465
12
    bool is_recycled = false; // Is last scanned kv recycled
2466
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
2467
12
                         &metrics_context, this](std::string_view k, std::string_view) {
2468
2
        ++num_scanned;
2469
2
        auto k1 = k;
2470
2
        k1.remove_prefix(1);
2471
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
2472
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2473
2
        decode_key(&k1, &out);
2474
2
        DCHECK_EQ(out.size(), 6) << k;
2475
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
2476
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
2477
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
2478
0
            return 0;
2479
0
        }
2480
2
        last_scanned_table_id = table_id;
2481
2
        is_recycled = false;
2482
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
2483
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
2484
2
        std::unique_ptr<Transaction> txn;
2485
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2486
2
        if (err != TxnErrorCode::TXN_OK) {
2487
0
            return -1;
2488
0
        }
2489
2
        std::unique_ptr<RangeGetIterator> iter;
2490
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
2491
2
        if (err != TxnErrorCode::TXN_OK) {
2492
0
            return -1;
2493
0
        }
2494
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
2495
1
            return 0;
2496
1
        }
2497
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2498
        // 1. Remove all partition version kvs of this table
2499
1
        auto partition_version_key_begin =
2500
1
                partition_version_key({instance_id_, db_id, table_id, 0});
2501
1
        auto partition_version_key_end =
2502
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
2503
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
2504
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
2505
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
2506
1
                     << " table_id=" << table_id;
2507
        // 2. Remove the table version kv of this table
2508
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
2509
1
        txn->remove(tbl_version_key);
2510
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
2511
        // 3. Remove mow delete bitmap update lock and tablet job lock
2512
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2513
1
        txn->remove(lock_key);
2514
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2515
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2516
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2517
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
2518
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2519
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2520
1
                     << " table_id=" << table_id;
2521
1
        err = txn->commit();
2522
1
        if (err != TxnErrorCode::TXN_OK) {
2523
0
            return -1;
2524
0
        }
2525
1
        metrics_context.total_recycled_num = ++num_recycled;
2526
1
        metrics_context.report();
2527
1
        is_recycled = true;
2528
1
        return 0;
2529
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2467
2
                         &metrics_context, this](std::string_view k, std::string_view) {
2468
2
        ++num_scanned;
2469
2
        auto k1 = k;
2470
2
        k1.remove_prefix(1);
2471
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
2472
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2473
2
        decode_key(&k1, &out);
2474
2
        DCHECK_EQ(out.size(), 6) << k;
2475
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
2476
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
2477
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
2478
0
            return 0;
2479
0
        }
2480
2
        last_scanned_table_id = table_id;
2481
2
        is_recycled = false;
2482
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
2483
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
2484
2
        std::unique_ptr<Transaction> txn;
2485
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2486
2
        if (err != TxnErrorCode::TXN_OK) {
2487
0
            return -1;
2488
0
        }
2489
2
        std::unique_ptr<RangeGetIterator> iter;
2490
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
2491
2
        if (err != TxnErrorCode::TXN_OK) {
2492
0
            return -1;
2493
0
        }
2494
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
2495
1
            return 0;
2496
1
        }
2497
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2498
        // 1. Remove all partition version kvs of this table
2499
1
        auto partition_version_key_begin =
2500
1
                partition_version_key({instance_id_, db_id, table_id, 0});
2501
1
        auto partition_version_key_end =
2502
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
2503
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
2504
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
2505
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
2506
1
                     << " table_id=" << table_id;
2507
        // 2. Remove the table version kv of this table
2508
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
2509
1
        txn->remove(tbl_version_key);
2510
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
2511
        // 3. Remove mow delete bitmap update lock and tablet job lock
2512
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2513
1
        txn->remove(lock_key);
2514
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2515
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2516
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2517
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
2518
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2519
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2520
1
                     << " table_id=" << table_id;
2521
1
        err = txn->commit();
2522
1
        if (err != TxnErrorCode::TXN_OK) {
2523
0
            return -1;
2524
0
        }
2525
1
        metrics_context.total_recycled_num = ++num_recycled;
2526
1
        metrics_context.report();
2527
1
        is_recycled = true;
2528
1
        return 0;
2529
1
    };
2530
2531
12
    if (config::enable_recycler_stats_metrics) {
2532
0
        scan_and_statistics_versions();
2533
0
    }
2534
    // recycle_func and loop_done for scan and recycle
2535
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
2536
14
}
2537
2538
3
int InstanceRecycler::recycle_orphan_partitions() {
2539
3
    int64_t num_scanned = 0;
2540
3
    int64_t num_recycled = 0;
2541
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
2542
2543
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
2544
3
            .tag("instance_id", instance_id_);
2545
2546
3
    auto start_time = steady_clock::now();
2547
2548
3
    DORIS_CLOUD_DEFER {
2549
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2550
3
        metrics_context.finish_report();
2551
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
2552
3
                .tag("instance_id", instance_id_)
2553
3
                .tag("num_scanned", num_scanned)
2554
3
                .tag("num_recycled", num_recycled);
2555
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
2548
3
    DORIS_CLOUD_DEFER {
2549
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2550
3
        metrics_context.finish_report();
2551
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
2552
3
                .tag("instance_id", instance_id_)
2553
3
                .tag("num_scanned", num_scanned)
2554
3
                .tag("num_recycled", num_recycled);
2555
3
    };
2556
2557
3
    bool is_empty_table = false;        // whether the table has no indexes
2558
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
2559
3
    int64_t current_table_id = 0;       // current scanning table id
2560
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
2561
3
                         &current_table_id, &is_table_kvs_recycled,
2562
3
                         this](std::string_view k, std::string_view) {
2563
2
        ++num_scanned;
2564
2565
2
        std::string_view k1(k);
2566
2
        int64_t db_id, table_id, partition_id;
2567
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
2568
2
                                                            &partition_id)) {
2569
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
2570
0
            return -1;
2571
2
        } else if (table_id != current_table_id) {
2572
2
            current_table_id = table_id;
2573
2
            is_table_kvs_recycled = false;
2574
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
2575
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
2576
2
            if (err != TxnErrorCode::TXN_OK) {
2577
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
2578
0
                             << " table_id=" << table_id << " err=" << err;
2579
0
                return -1;
2580
0
            }
2581
2
        }
2582
2583
2
        if (!is_empty_table) {
2584
            // table is not empty, skip recycle
2585
1
            return 0;
2586
1
        }
2587
2588
1
        std::unique_ptr<Transaction> txn;
2589
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2590
1
        if (err != TxnErrorCode::TXN_OK) {
2591
0
            return -1;
2592
0
        }
2593
2594
        // 1. Remove all partition related kvs
2595
1
        std::string partition_meta_key =
2596
1
                versioned::meta_partition_key({instance_id_, partition_id});
2597
1
        std::string partition_index_key =
2598
1
                versioned::partition_index_key({instance_id_, partition_id});
2599
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
2600
1
                {instance_id_, db_id, table_id, partition_id});
2601
1
        std::string partition_version_key =
2602
1
                versioned::partition_version_key({instance_id_, partition_id});
2603
1
        txn->remove(partition_index_key);
2604
1
        txn->remove(partition_inverted_key);
2605
1
        versioned_remove_all(txn.get(), partition_meta_key);
2606
1
        versioned_remove_all(txn.get(), partition_version_key);
2607
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
2608
1
                     << " table_id=" << table_id << " db_id=" << db_id
2609
1
                     << " partition_meta_key=" << hex(partition_meta_key)
2610
1
                     << " partition_version_key=" << hex(partition_version_key);
2611
2612
1
        if (!is_table_kvs_recycled) {
2613
1
            is_table_kvs_recycled = true;
2614
2615
            // 2. Remove the table version kv of this table
2616
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
2617
1
            versioned_remove_all(txn.get(), table_version_key);
2618
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
2619
            // 3. Remove mow delete bitmap update lock and tablet job lock
2620
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2621
1
            txn->remove(lock_key);
2622
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2623
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2624
1
            std::string tablet_job_key_end =
2625
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2626
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
2627
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2628
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2629
1
                         << " table_id=" << table_id;
2630
1
        }
2631
2632
1
        err = txn->commit();
2633
1
        if (err != TxnErrorCode::TXN_OK) {
2634
0
            return -1;
2635
0
        }
2636
1
        metrics_context.total_recycled_num = ++num_recycled;
2637
1
        metrics_context.report();
2638
1
        return 0;
2639
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
2562
2
                         this](std::string_view k, std::string_view) {
2563
2
        ++num_scanned;
2564
2565
2
        std::string_view k1(k);
2566
2
        int64_t db_id, table_id, partition_id;
2567
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
2568
2
                                                            &partition_id)) {
2569
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
2570
0
            return -1;
2571
2
        } else if (table_id != current_table_id) {
2572
2
            current_table_id = table_id;
2573
2
            is_table_kvs_recycled = false;
2574
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
2575
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
2576
2
            if (err != TxnErrorCode::TXN_OK) {
2577
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
2578
0
                             << " table_id=" << table_id << " err=" << err;
2579
0
                return -1;
2580
0
            }
2581
2
        }
2582
2583
2
        if (!is_empty_table) {
2584
            // table is not empty, skip recycle
2585
1
            return 0;
2586
1
        }
2587
2588
1
        std::unique_ptr<Transaction> txn;
2589
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2590
1
        if (err != TxnErrorCode::TXN_OK) {
2591
0
            return -1;
2592
0
        }
2593
2594
        // 1. Remove all partition related kvs
2595
1
        std::string partition_meta_key =
2596
1
                versioned::meta_partition_key({instance_id_, partition_id});
2597
1
        std::string partition_index_key =
2598
1
                versioned::partition_index_key({instance_id_, partition_id});
2599
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
2600
1
                {instance_id_, db_id, table_id, partition_id});
2601
1
        std::string partition_version_key =
2602
1
                versioned::partition_version_key({instance_id_, partition_id});
2603
1
        txn->remove(partition_index_key);
2604
1
        txn->remove(partition_inverted_key);
2605
1
        versioned_remove_all(txn.get(), partition_meta_key);
2606
1
        versioned_remove_all(txn.get(), partition_version_key);
2607
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
2608
1
                     << " table_id=" << table_id << " db_id=" << db_id
2609
1
                     << " partition_meta_key=" << hex(partition_meta_key)
2610
1
                     << " partition_version_key=" << hex(partition_version_key);
2611
2612
1
        if (!is_table_kvs_recycled) {
2613
1
            is_table_kvs_recycled = true;
2614
2615
            // 2. Remove the table version kv of this table
2616
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
2617
1
            versioned_remove_all(txn.get(), table_version_key);
2618
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
2619
            // 3. Remove mow delete bitmap update lock and tablet job lock
2620
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2621
1
            txn->remove(lock_key);
2622
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2623
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2624
1
            std::string tablet_job_key_end =
2625
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2626
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
2627
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2628
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2629
1
                         << " table_id=" << table_id;
2630
1
        }
2631
2632
1
        err = txn->commit();
2633
1
        if (err != TxnErrorCode::TXN_OK) {
2634
0
            return -1;
2635
0
        }
2636
1
        metrics_context.total_recycled_num = ++num_recycled;
2637
1
        metrics_context.report();
2638
1
        return 0;
2639
1
    };
2640
2641
    // recycle_func and loop_done for scan and recycle
2642
3
    return scan_and_recycle(
2643
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
2644
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
2645
3
            std::move(recycle_func));
2646
3
}
2647
2648
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
2649
                                      RecyclerMetricsContext& metrics_context,
2650
49
                                      int64_t partition_id) {
2651
49
    bool is_multi_version =
2652
49
            instance_info_.has_multi_version_status() &&
2653
49
            instance_info_.multi_version_status() != MultiVersionStatus::MULTI_VERSION_DISABLED;
2654
49
    int64_t num_scanned = 0;
2655
49
    std::atomic_long num_recycled = 0;
2656
2657
49
    std::string tablet_key_begin, tablet_key_end;
2658
49
    std::string stats_key_begin, stats_key_end;
2659
49
    std::string job_key_begin, job_key_end;
2660
2661
49
    std::string tablet_belongs;
2662
49
    if (partition_id > 0) {
2663
        // recycle tablets in a partition belonging to the index
2664
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
2665
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
2666
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
2667
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
2668
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
2669
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
2670
33
        tablet_belongs = "partition";
2671
33
    } else {
2672
        // recycle tablets in the index
2673
16
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
2674
16
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
2675
16
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
2676
16
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
2677
16
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
2678
16
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
2679
16
        tablet_belongs = "index";
2680
16
    }
2681
2682
49
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
2683
49
            .tag("table_id", table_id)
2684
49
            .tag("index_id", index_id)
2685
49
            .tag("partition_id", partition_id);
2686
2687
49
    auto start_time = steady_clock::now();
2688
2689
49
    DORIS_CLOUD_DEFER {
2690
49
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2691
49
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
2692
49
                .tag("instance_id", instance_id_)
2693
49
                .tag("table_id", table_id)
2694
49
                .tag("index_id", index_id)
2695
49
                .tag("partition_id", partition_id)
2696
49
                .tag("num_scanned", num_scanned)
2697
49
                .tag("num_recycled", num_recycled);
2698
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
2689
4
    DORIS_CLOUD_DEFER {
2690
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2691
4
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
2692
4
                .tag("instance_id", instance_id_)
2693
4
                .tag("table_id", table_id)
2694
4
                .tag("index_id", index_id)
2695
4
                .tag("partition_id", partition_id)
2696
4
                .tag("num_scanned", num_scanned)
2697
4
                .tag("num_recycled", num_recycled);
2698
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
2689
45
    DORIS_CLOUD_DEFER {
2690
45
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2691
45
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
2692
45
                .tag("instance_id", instance_id_)
2693
45
                .tag("table_id", table_id)
2694
45
                .tag("index_id", index_id)
2695
45
                .tag("partition_id", partition_id)
2696
45
                .tag("num_scanned", num_scanned)
2697
45
                .tag("num_recycled", num_recycled);
2698
45
    };
2699
2700
    // The first string_view represents the tablet key which has been recycled
2701
    // The second bool represents whether the following fdb's tablet key deletion could be done using range move or not
2702
49
    using TabletKeyPair = std::pair<std::string_view, bool>;
2703
49
    SyncExecutor<TabletKeyPair> sync_executor(
2704
49
            _thread_pool_group.recycle_tablet_pool,
2705
49
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
2706
49
                        index_id, partition_id),
2707
4.23k
            [](const TabletKeyPair& k) { return k.first.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKSt4pairISt17basic_string_viewIcSt11char_traitsIcEEbE
Line
Count
Source
2707
4.00k
            [](const TabletKeyPair& k) { return k.first.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKSt4pairISt17basic_string_viewIcSt11char_traitsIcEEbE
Line
Count
Source
2707
237
            [](const TabletKeyPair& k) { return k.first.empty(); });
2708
2709
    // Elements in `tablet_keys` has the same lifetime as `it` in `scan_and_recycle`
2710
49
    std::vector<std::string> tablet_idx_keys;
2711
49
    std::vector<std::string> restore_job_keys;
2712
49
    std::vector<std::string> init_rs_keys;
2713
49
    std::vector<std::string> tablet_compact_stats_keys;
2714
49
    std::vector<std::string> tablet_load_stats_keys;
2715
49
    std::vector<std::string> versioned_meta_tablet_keys;
2716
8.24k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2717
8.24k
        bool use_range_remove = true;
2718
8.24k
        ++num_scanned;
2719
8.24k
        doris::TabletMetaCloudPB tablet_meta_pb;
2720
8.24k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
2721
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
2722
0
            use_range_remove = false;
2723
0
            return -1;
2724
0
        }
2725
8.24k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
2726
2727
8.24k
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
2728
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
2729
4.00k
            return -1;
2730
4.00k
        }
2731
2732
4.24k
        tablet_idx_keys.push_back(meta_tablet_idx_key({instance_id_, tablet_id}));
2733
4.24k
        restore_job_keys.push_back(job_restore_tablet_key({instance_id_, tablet_id}));
2734
4.24k
        if (is_multi_version) {
2735
            // The tablet index/inverted index are recycled in recycle_versioned_tablet.
2736
6
            tablet_compact_stats_keys.push_back(
2737
6
                    versioned::tablet_compact_stats_key({instance_id_, tablet_id}));
2738
6
            tablet_load_stats_keys.push_back(
2739
6
                    versioned::tablet_load_stats_key({instance_id_, tablet_id}));
2740
6
            versioned_meta_tablet_keys.push_back(
2741
6
                    versioned::meta_tablet_key({instance_id_, tablet_id}));
2742
6
        }
2743
4.24k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
2744
4.23k
        sync_executor.add([this, &num_recycled, tid = tablet_id, range_move = use_range_remove,
2745
4.23k
                           &metrics_context, k]() mutable -> TabletKeyPair {
2746
4.23k
            if (recycle_tablet(tid, metrics_context) != 0) {
2747
1
                LOG_WARNING("failed to recycle tablet")
2748
1
                        .tag("instance_id", instance_id_)
2749
1
                        .tag("tablet_id", tid);
2750
1
                range_move = false;
2751
1
                return {std::string_view(), range_move};
2752
1
            }
2753
4.23k
            ++num_recycled;
2754
4.23k
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2755
4.23k
            return {k, range_move};
2756
4.23k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENUlvE_clEv
Line
Count
Source
2745
4.00k
                           &metrics_context, k]() mutable -> TabletKeyPair {
2746
4.00k
            if (recycle_tablet(tid, metrics_context) != 0) {
2747
0
                LOG_WARNING("failed to recycle tablet")
2748
0
                        .tag("instance_id", instance_id_)
2749
0
                        .tag("tablet_id", tid);
2750
0
                range_move = false;
2751
0
                return {std::string_view(), range_move};
2752
0
            }
2753
4.00k
            ++num_recycled;
2754
4.00k
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2755
4.00k
            return {k, range_move};
2756
4.00k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENUlvE_clEv
Line
Count
Source
2745
237
                           &metrics_context, k]() mutable -> TabletKeyPair {
2746
237
            if (recycle_tablet(tid, metrics_context) != 0) {
2747
1
                LOG_WARNING("failed to recycle tablet")
2748
1
                        .tag("instance_id", instance_id_)
2749
1
                        .tag("tablet_id", tid);
2750
1
                range_move = false;
2751
1
                return {std::string_view(), range_move};
2752
1
            }
2753
236
            ++num_recycled;
2754
236
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2755
236
            return {k, range_move};
2756
237
        });
2757
4.23k
        return 0;
2758
4.24k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
2716
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2717
8.00k
        bool use_range_remove = true;
2718
8.00k
        ++num_scanned;
2719
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
2720
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
2721
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
2722
0
            use_range_remove = false;
2723
0
            return -1;
2724
0
        }
2725
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
2726
2727
8.00k
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
2728
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
2729
4.00k
            return -1;
2730
4.00k
        }
2731
2732
4.00k
        tablet_idx_keys.push_back(meta_tablet_idx_key({instance_id_, tablet_id}));
2733
4.00k
        restore_job_keys.push_back(job_restore_tablet_key({instance_id_, tablet_id}));
2734
4.00k
        if (is_multi_version) {
2735
            // The tablet index/inverted index are recycled in recycle_versioned_tablet.
2736
0
            tablet_compact_stats_keys.push_back(
2737
0
                    versioned::tablet_compact_stats_key({instance_id_, tablet_id}));
2738
0
            tablet_load_stats_keys.push_back(
2739
0
                    versioned::tablet_load_stats_key({instance_id_, tablet_id}));
2740
0
            versioned_meta_tablet_keys.push_back(
2741
0
                    versioned::meta_tablet_key({instance_id_, tablet_id}));
2742
0
        }
2743
4.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
2744
4.00k
        sync_executor.add([this, &num_recycled, tid = tablet_id, range_move = use_range_remove,
2745
4.00k
                           &metrics_context, k]() mutable -> TabletKeyPair {
2746
4.00k
            if (recycle_tablet(tid, metrics_context) != 0) {
2747
4.00k
                LOG_WARNING("failed to recycle tablet")
2748
4.00k
                        .tag("instance_id", instance_id_)
2749
4.00k
                        .tag("tablet_id", tid);
2750
4.00k
                range_move = false;
2751
4.00k
                return {std::string_view(), range_move};
2752
4.00k
            }
2753
4.00k
            ++num_recycled;
2754
4.00k
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2755
4.00k
            return {k, range_move};
2756
4.00k
        });
2757
4.00k
        return 0;
2758
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
2716
240
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2717
240
        bool use_range_remove = true;
2718
240
        ++num_scanned;
2719
240
        doris::TabletMetaCloudPB tablet_meta_pb;
2720
240
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
2721
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
2722
0
            use_range_remove = false;
2723
0
            return -1;
2724
0
        }
2725
240
        int64_t tablet_id = tablet_meta_pb.tablet_id();
2726
2727
240
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
2728
0
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
2729
0
            return -1;
2730
0
        }
2731
2732
240
        tablet_idx_keys.push_back(meta_tablet_idx_key({instance_id_, tablet_id}));
2733
240
        restore_job_keys.push_back(job_restore_tablet_key({instance_id_, tablet_id}));
2734
240
        if (is_multi_version) {
2735
            // The tablet index/inverted index are recycled in recycle_versioned_tablet.
2736
6
            tablet_compact_stats_keys.push_back(
2737
6
                    versioned::tablet_compact_stats_key({instance_id_, tablet_id}));
2738
6
            tablet_load_stats_keys.push_back(
2739
6
                    versioned::tablet_load_stats_key({instance_id_, tablet_id}));
2740
6
            versioned_meta_tablet_keys.push_back(
2741
6
                    versioned::meta_tablet_key({instance_id_, tablet_id}));
2742
6
        }
2743
240
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
2744
237
        sync_executor.add([this, &num_recycled, tid = tablet_id, range_move = use_range_remove,
2745
237
                           &metrics_context, k]() mutable -> TabletKeyPair {
2746
237
            if (recycle_tablet(tid, metrics_context) != 0) {
2747
237
                LOG_WARNING("failed to recycle tablet")
2748
237
                        .tag("instance_id", instance_id_)
2749
237
                        .tag("tablet_id", tid);
2750
237
                range_move = false;
2751
237
                return {std::string_view(), range_move};
2752
237
            }
2753
237
            ++num_recycled;
2754
237
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2755
237
            return {k, range_move};
2756
237
        });
2757
237
        return 0;
2758
240
    };
2759
2760
    // TODO(AlexYue): Add one ut to cover use_range_remove = false
2761
49
    auto loop_done = [&, this]() -> int {
2762
49
        bool finished = true;
2763
49
        auto tablet_keys = sync_executor.when_all(&finished);
2764
49
        if (!finished) {
2765
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
2766
1
            return -1;
2767
1
        }
2768
48
        if (tablet_keys.empty() && tablet_idx_keys.empty()) return 0;
2769
46
        if (!tablet_keys.empty() &&
2770
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
2770
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
2770
42
            std::ranges::all_of(tablet_keys, [](const auto& k) { return k.first.empty(); })) {
2771
0
            return -1;
2772
0
        }
2773
        // sort the vector using key's order
2774
46
        std::sort(tablet_keys.begin(), tablet_keys.end(),
2775
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
2775
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
2775
944
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
2776
46
        bool use_range_remove = true;
2777
4.23k
        for (auto& [_, remove] : tablet_keys) {
2778
4.23k
            if (!remove) {
2779
0
                use_range_remove = remove;
2780
0
                break;
2781
0
            }
2782
4.23k
        }
2783
46
        DORIS_CLOUD_DEFER {
2784
46
            tablet_idx_keys.clear();
2785
46
            restore_job_keys.clear();
2786
46
            init_rs_keys.clear();
2787
46
            tablet_compact_stats_keys.clear();
2788
46
            tablet_load_stats_keys.clear();
2789
46
            versioned_meta_tablet_keys.clear();
2790
46
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2783
2
        DORIS_CLOUD_DEFER {
2784
2
            tablet_idx_keys.clear();
2785
2
            restore_job_keys.clear();
2786
2
            init_rs_keys.clear();
2787
2
            tablet_compact_stats_keys.clear();
2788
2
            tablet_load_stats_keys.clear();
2789
2
            versioned_meta_tablet_keys.clear();
2790
2
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2783
44
        DORIS_CLOUD_DEFER {
2784
44
            tablet_idx_keys.clear();
2785
44
            restore_job_keys.clear();
2786
44
            init_rs_keys.clear();
2787
44
            tablet_compact_stats_keys.clear();
2788
44
            tablet_load_stats_keys.clear();
2789
44
            versioned_meta_tablet_keys.clear();
2790
44
        };
2791
46
        std::unique_ptr<Transaction> txn;
2792
46
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2793
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
2794
0
            return -1;
2795
0
        }
2796
46
        std::string tablet_key_end;
2797
46
        if (!tablet_keys.empty()) {
2798
44
            if (use_range_remove) {
2799
44
                tablet_key_end = std::string(tablet_keys.back().first) + '\x00';
2800
44
                txn->remove(tablet_keys.front().first, tablet_key_end);
2801
44
            } else {
2802
0
                for (auto& [k, _] : tablet_keys) {
2803
0
                    txn->remove(k);
2804
0
                }
2805
0
            }
2806
44
        }
2807
46
        if (is_multi_version) {
2808
6
            for (auto& k : tablet_compact_stats_keys) {
2809
                // Remove all versions of tablet compact stats for recycled tablet
2810
6
                LOG_INFO("remove versioned tablet compact stats key")
2811
6
                        .tag("compact_stats_key", hex(k));
2812
6
                versioned_remove_all(txn.get(), k);
2813
6
            }
2814
6
            for (auto& k : tablet_load_stats_keys) {
2815
                // Remove all versions of tablet load stats for recycled tablet
2816
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
2817
6
                versioned_remove_all(txn.get(), k);
2818
6
            }
2819
6
            for (auto& k : versioned_meta_tablet_keys) {
2820
                // Remove all versions of meta tablet for recycled tablet
2821
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
2822
6
                versioned_remove_all(txn.get(), k);
2823
6
            }
2824
5
        }
2825
4.24k
        for (auto& k : tablet_idx_keys) {
2826
4.24k
            txn->remove(k);
2827
4.24k
        }
2828
4.24k
        for (auto& k : restore_job_keys) {
2829
4.24k
            txn->remove(k);
2830
4.24k
        }
2831
46
        for (auto& k : init_rs_keys) {
2832
0
            txn->remove(k);
2833
0
        }
2834
46
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
2835
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
2836
0
                         << ", err=" << err;
2837
0
            return -1;
2838
0
        }
2839
46
        return 0;
2840
46
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
2761
4
    auto loop_done = [&, this]() -> int {
2762
4
        bool finished = true;
2763
4
        auto tablet_keys = sync_executor.when_all(&finished);
2764
4
        if (!finished) {
2765
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
2766
0
            return -1;
2767
0
        }
2768
4
        if (tablet_keys.empty() && tablet_idx_keys.empty()) return 0;
2769
2
        if (!tablet_keys.empty() &&
2770
2
            std::ranges::all_of(tablet_keys, [](const auto& k) { return k.first.empty(); })) {
2771
0
            return -1;
2772
0
        }
2773
        // sort the vector using key's order
2774
2
        std::sort(tablet_keys.begin(), tablet_keys.end(),
2775
2
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
2776
2
        bool use_range_remove = true;
2777
4.00k
        for (auto& [_, remove] : tablet_keys) {
2778
4.00k
            if (!remove) {
2779
0
                use_range_remove = remove;
2780
0
                break;
2781
0
            }
2782
4.00k
        }
2783
2
        DORIS_CLOUD_DEFER {
2784
2
            tablet_idx_keys.clear();
2785
2
            restore_job_keys.clear();
2786
2
            init_rs_keys.clear();
2787
2
            tablet_compact_stats_keys.clear();
2788
2
            tablet_load_stats_keys.clear();
2789
2
            versioned_meta_tablet_keys.clear();
2790
2
        };
2791
2
        std::unique_ptr<Transaction> txn;
2792
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2793
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
2794
0
            return -1;
2795
0
        }
2796
2
        std::string tablet_key_end;
2797
2
        if (!tablet_keys.empty()) {
2798
2
            if (use_range_remove) {
2799
2
                tablet_key_end = std::string(tablet_keys.back().first) + '\x00';
2800
2
                txn->remove(tablet_keys.front().first, tablet_key_end);
2801
2
            } else {
2802
0
                for (auto& [k, _] : tablet_keys) {
2803
0
                    txn->remove(k);
2804
0
                }
2805
0
            }
2806
2
        }
2807
2
        if (is_multi_version) {
2808
0
            for (auto& k : tablet_compact_stats_keys) {
2809
                // Remove all versions of tablet compact stats for recycled tablet
2810
0
                LOG_INFO("remove versioned tablet compact stats key")
2811
0
                        .tag("compact_stats_key", hex(k));
2812
0
                versioned_remove_all(txn.get(), k);
2813
0
            }
2814
0
            for (auto& k : tablet_load_stats_keys) {
2815
                // Remove all versions of tablet load stats for recycled tablet
2816
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
2817
0
                versioned_remove_all(txn.get(), k);
2818
0
            }
2819
0
            for (auto& k : versioned_meta_tablet_keys) {
2820
                // Remove all versions of meta tablet for recycled tablet
2821
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
2822
0
                versioned_remove_all(txn.get(), k);
2823
0
            }
2824
0
        }
2825
4.00k
        for (auto& k : tablet_idx_keys) {
2826
4.00k
            txn->remove(k);
2827
4.00k
        }
2828
4.00k
        for (auto& k : restore_job_keys) {
2829
4.00k
            txn->remove(k);
2830
4.00k
        }
2831
2
        for (auto& k : init_rs_keys) {
2832
0
            txn->remove(k);
2833
0
        }
2834
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
2835
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
2836
0
                         << ", err=" << err;
2837
0
            return -1;
2838
0
        }
2839
2
        return 0;
2840
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
2761
45
    auto loop_done = [&, this]() -> int {
2762
45
        bool finished = true;
2763
45
        auto tablet_keys = sync_executor.when_all(&finished);
2764
45
        if (!finished) {
2765
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
2766
1
            return -1;
2767
1
        }
2768
44
        if (tablet_keys.empty() && tablet_idx_keys.empty()) return 0;
2769
44
        if (!tablet_keys.empty() &&
2770
44
            std::ranges::all_of(tablet_keys, [](const auto& k) { return k.first.empty(); })) {
2771
0
            return -1;
2772
0
        }
2773
        // sort the vector using key's order
2774
44
        std::sort(tablet_keys.begin(), tablet_keys.end(),
2775
44
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
2776
44
        bool use_range_remove = true;
2777
236
        for (auto& [_, remove] : tablet_keys) {
2778
236
            if (!remove) {
2779
0
                use_range_remove = remove;
2780
0
                break;
2781
0
            }
2782
236
        }
2783
44
        DORIS_CLOUD_DEFER {
2784
44
            tablet_idx_keys.clear();
2785
44
            restore_job_keys.clear();
2786
44
            init_rs_keys.clear();
2787
44
            tablet_compact_stats_keys.clear();
2788
44
            tablet_load_stats_keys.clear();
2789
44
            versioned_meta_tablet_keys.clear();
2790
44
        };
2791
44
        std::unique_ptr<Transaction> txn;
2792
44
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2793
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
2794
0
            return -1;
2795
0
        }
2796
44
        std::string tablet_key_end;
2797
44
        if (!tablet_keys.empty()) {
2798
42
            if (use_range_remove) {
2799
42
                tablet_key_end = std::string(tablet_keys.back().first) + '\x00';
2800
42
                txn->remove(tablet_keys.front().first, tablet_key_end);
2801
42
            } else {
2802
0
                for (auto& [k, _] : tablet_keys) {
2803
0
                    txn->remove(k);
2804
0
                }
2805
0
            }
2806
42
        }
2807
44
        if (is_multi_version) {
2808
6
            for (auto& k : tablet_compact_stats_keys) {
2809
                // Remove all versions of tablet compact stats for recycled tablet
2810
6
                LOG_INFO("remove versioned tablet compact stats key")
2811
6
                        .tag("compact_stats_key", hex(k));
2812
6
                versioned_remove_all(txn.get(), k);
2813
6
            }
2814
6
            for (auto& k : tablet_load_stats_keys) {
2815
                // Remove all versions of tablet load stats for recycled tablet
2816
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
2817
6
                versioned_remove_all(txn.get(), k);
2818
6
            }
2819
6
            for (auto& k : versioned_meta_tablet_keys) {
2820
                // Remove all versions of meta tablet for recycled tablet
2821
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
2822
6
                versioned_remove_all(txn.get(), k);
2823
6
            }
2824
5
        }
2825
239
        for (auto& k : tablet_idx_keys) {
2826
239
            txn->remove(k);
2827
239
        }
2828
239
        for (auto& k : restore_job_keys) {
2829
239
            txn->remove(k);
2830
239
        }
2831
44
        for (auto& k : init_rs_keys) {
2832
0
            txn->remove(k);
2833
0
        }
2834
44
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
2835
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
2836
0
                         << ", err=" << err;
2837
0
            return -1;
2838
0
        }
2839
44
        return 0;
2840
44
    };
2841
2842
49
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
2843
49
                               std::move(loop_done));
2844
49
    if (ret != 0) {
2845
3
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
2846
3
        return ret;
2847
3
    }
2848
2849
    // directly remove tablet stats and tablet jobs of these dropped index or partition
2850
46
    std::unique_ptr<Transaction> txn;
2851
46
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2852
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
2853
0
        return -1;
2854
0
    }
2855
46
    txn->remove(stats_key_begin, stats_key_end);
2856
46
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
2857
46
                 << " end=" << hex(stats_key_end);
2858
46
    txn->remove(job_key_begin, job_key_end);
2859
46
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
2860
46
    std::string schema_key_begin, schema_key_end;
2861
46
    std::string schema_dict_key;
2862
46
    std::string versioned_schema_key_begin, versioned_schema_key_end;
2863
46
    if (partition_id <= 0) {
2864
        // Delete schema kv of this index
2865
14
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
2866
14
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
2867
14
        txn->remove(schema_key_begin, schema_key_end);
2868
14
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
2869
14
                     << " end=" << hex(schema_key_end);
2870
14
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
2871
14
        txn->remove(schema_dict_key);
2872
14
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
2873
14
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
2874
14
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
2875
14
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
2876
14
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
2877
14
                     << " end=" << hex(versioned_schema_key_end);
2878
14
    }
2879
2880
46
    TxnErrorCode err = txn->commit();
2881
46
    if (err != TxnErrorCode::TXN_OK) {
2882
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
2883
0
                     << " err=" << err;
2884
0
        return -1;
2885
0
    }
2886
2887
46
    return ret;
2888
46
}
2889
2890
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
2891
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
2892
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
2893
5.61k
    if (num_segments <= 0) return 0;
2894
2895
5.61k
    std::vector<std::string> file_paths;
2896
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
2897
0
        return -1;
2898
0
    }
2899
2900
    // Process inverted indexes
2901
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
2902
    // default format as v1.
2903
5.61k
    InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
2904
5.61k
    bool delete_rowset_data_by_prefix = false;
2905
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
2906
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
2907
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
2908
0
        delete_rowset_data_by_prefix = true;
2909
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
2910
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
2911
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
2912
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
2913
10.0k
            }
2914
10.0k
        }
2915
4.80k
        if (rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
2916
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
2917
2.00k
        }
2918
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
2919
        // schema version and index id are not found, delete rowset data by prefix directly.
2920
0
        delete_rowset_data_by_prefix = true;
2921
809
    } else {
2922
        // otherwise, try to get schema kv
2923
809
        InvertedIndexInfo index_info;
2924
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
2925
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
2926
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
2927
809
                                 &inverted_index_get_ret);
2928
809
        if (inverted_index_get_ret == 0) {
2929
809
            index_format = index_info.first;
2930
809
            index_ids = index_info.second;
2931
809
        } else if (inverted_index_get_ret == 1) {
2932
            // 1. Schema kv not found means tablet has been recycled
2933
            // Maybe some tablet recycle failed by some bugs
2934
            // We need to delete again to double check
2935
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
2936
            // because we are uncertain about the inverted index information.
2937
            // If there are inverted indexes, some data might not be deleted,
2938
            // but this is acceptable as we have made our best effort to delete the data.
2939
0
            LOG_INFO(
2940
0
                    "delete rowset data schema kv not found, need to delete again to double "
2941
0
                    "check")
2942
0
                    .tag("instance_id", instance_id_)
2943
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
2944
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
2945
            // Currently index_ids is guaranteed to be empty,
2946
            // but we clear it again here as a safeguard against future code changes
2947
            // that might cause index_ids to no longer be empty
2948
0
            index_format = InvertedIndexStorageFormatPB::V2;
2949
0
            index_ids.clear();
2950
0
        } else {
2951
            // failed to get schema kv, delete rowset data by prefix directly.
2952
0
            delete_rowset_data_by_prefix = true;
2953
0
        }
2954
809
    }
2955
2956
5.61k
    if (delete_rowset_data_by_prefix) {
2957
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
2958
0
                                  rs_meta_pb.rowset_id_v2());
2959
0
    }
2960
2961
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
2962
5.61k
    if (it == accessor_map_.end()) {
2963
1.59k
        LOG_WARNING("instance has no such resource id")
2964
1.59k
                .tag("instance_id", instance_id_)
2965
1.59k
                .tag("resource_id", rs_meta_pb.resource_id());
2966
1.59k
        return -1;
2967
1.59k
    }
2968
4.01k
    auto& accessor = it->second;
2969
2970
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
2971
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
2972
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
2973
20.0k
        file_paths.push_back(segment_path(tablet_id, rowset_id, i));
2974
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
2975
40.0k
            for (const auto& index_id : index_ids) {
2976
40.0k
                file_paths.push_back(inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
2977
40.0k
                                                            index_id.second));
2978
40.0k
            }
2979
20.0k
        } else if (!index_ids.empty()) {
2980
0
            file_paths.push_back(inverted_index_path_v2(tablet_id, rowset_id, i));
2981
0
        }
2982
20.0k
    }
2983
2984
    // Process delete bitmap - check if it's stored in packed file
2985
4.01k
    bool delete_bitmap_is_packed = false;
2986
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
2987
4.01k
                                                       &delete_bitmap_is_packed) != 0) {
2988
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
2989
0
                .tag("instance_id", instance_id_)
2990
0
                .tag("tablet_id", tablet_id)
2991
0
                .tag("rowset_id", rowset_id);
2992
0
        return -1;
2993
0
    }
2994
    // Only delete standalone delete bitmap file if not stored in packed file
2995
4.01k
    if (!delete_bitmap_is_packed) {
2996
4.01k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
2997
4.01k
    }
2998
    // TODO(AlexYue): seems could do do batch
2999
4.01k
    return accessor->delete_files(file_paths);
3000
4.01k
}
3001
3002
62.3k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3003
62.3k
    LOG_INFO("begin process_packed_file_location_index")
3004
62.3k
            .tag("instance_id", instance_id_)
3005
62.3k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3006
62.3k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3007
62.3k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3008
62.3k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3009
62.3k
    if (index_map.empty()) {
3010
62.3k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3011
62.3k
                .tag("instance_id", instance_id_)
3012
62.3k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3013
62.3k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3014
62.3k
        return 0;
3015
62.3k
    }
3016
3017
14
    struct PackedSmallFileInfo {
3018
14
        std::string small_file_path;
3019
14
    };
3020
14
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3021
14
    packed_file_updates.reserve(index_map.size());
3022
27
    for (const auto& [small_path, index_pb] : index_map) {
3023
27
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3024
0
            continue;
3025
0
        }
3026
27
        packed_file_updates[index_pb.packed_file_path()].push_back(
3027
27
                PackedSmallFileInfo {small_path});
3028
27
    }
3029
14
    if (packed_file_updates.empty()) {
3030
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3031
0
                .tag("instance_id", instance_id_)
3032
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3033
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3034
0
                .tag("index_map_size", index_map.size());
3035
0
        return 0;
3036
0
    }
3037
3038
14
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3039
14
    int ret = 0;
3040
24
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3041
24
        if (small_files.empty()) {
3042
0
            continue;
3043
0
        }
3044
3045
24
        bool success = false;
3046
24
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3047
24
            std::unique_ptr<Transaction> txn;
3048
24
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3049
24
            if (err != TxnErrorCode::TXN_OK) {
3050
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3051
0
                        .tag("instance_id", instance_id_)
3052
0
                        .tag("packed_file_path", packed_file_path)
3053
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3054
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3055
0
                        .tag("err", err);
3056
0
                ret = -1;
3057
0
                break;
3058
0
            }
3059
3060
24
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3061
24
            std::string packed_val;
3062
24
            err = txn->get(packed_key, &packed_val);
3063
24
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3064
0
                LOG_WARNING("packed file info not found when recycling rowset")
3065
0
                        .tag("instance_id", instance_id_)
3066
0
                        .tag("packed_file_path", packed_file_path)
3067
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3068
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3069
0
                        .tag("key", hex(packed_key))
3070
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3071
                // Skip this packed file entry and continue with others
3072
0
                success = true;
3073
0
                break;
3074
0
            }
3075
24
            if (err != TxnErrorCode::TXN_OK) {
3076
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
3077
0
                        .tag("instance_id", instance_id_)
3078
0
                        .tag("packed_file_path", packed_file_path)
3079
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3080
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3081
0
                        .tag("err", err);
3082
0
                ret = -1;
3083
0
                break;
3084
0
            }
3085
3086
24
            cloud::PackedFileInfoPB packed_info;
3087
24
            if (!packed_info.ParseFromString(packed_val)) {
3088
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
3089
0
                        .tag("instance_id", instance_id_)
3090
0
                        .tag("packed_file_path", packed_file_path)
3091
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3092
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3093
0
                ret = -1;
3094
0
                break;
3095
0
            }
3096
3097
24
            LOG_INFO("packed file update check")
3098
24
                    .tag("instance_id", instance_id_)
3099
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3100
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3101
24
                    .tag("merged_file_path", packed_file_path)
3102
24
                    .tag("requested_small_files", small_files.size())
3103
24
                    .tag("merge_entries", packed_info.slices_size());
3104
3105
24
            auto* small_file_entries = packed_info.mutable_slices();
3106
24
            int64_t changed_files = 0;
3107
24
            int64_t missing_entries = 0;
3108
24
            int64_t already_deleted = 0;
3109
27
            for (const auto& small_file_info : small_files) {
3110
27
                bool found = false;
3111
87
                for (auto& small_file_entry : *small_file_entries) {
3112
87
                    if (small_file_entry.path() == small_file_info.small_file_path) {
3113
27
                        if (!small_file_entry.deleted()) {
3114
27
                            small_file_entry.set_deleted(true);
3115
27
                            if (!small_file_entry.corrected()) {
3116
27
                                small_file_entry.set_corrected(true);
3117
27
                            }
3118
27
                            ++changed_files;
3119
27
                        } else {
3120
0
                            ++already_deleted;
3121
0
                        }
3122
27
                        found = true;
3123
27
                        break;
3124
27
                    }
3125
87
                }
3126
27
                if (!found) {
3127
0
                    ++missing_entries;
3128
0
                    LOG_WARNING("packed file info missing small file entry")
3129
0
                            .tag("instance_id", instance_id_)
3130
0
                            .tag("packed_file_path", packed_file_path)
3131
0
                            .tag("small_file_path", small_file_info.small_file_path)
3132
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3133
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
3134
0
                }
3135
27
            }
3136
3137
24
            if (changed_files == 0) {
3138
0
                LOG_INFO("skip merge file update: no merge entries changed")
3139
0
                        .tag("instance_id", instance_id_)
3140
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3141
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3142
0
                        .tag("merged_file_path", packed_file_path)
3143
0
                        .tag("missing_entries", missing_entries)
3144
0
                        .tag("already_deleted", already_deleted)
3145
0
                        .tag("requested_small_files", small_files.size())
3146
0
                        .tag("merge_entries", packed_info.slices_size());
3147
0
                success = true;
3148
0
                break;
3149
0
            }
3150
3151
            // Calculate remaining files
3152
24
            int64_t left_file_count = 0;
3153
24
            int64_t left_file_bytes = 0;
3154
141
            for (const auto& small_file_entry : packed_info.slices()) {
3155
141
                if (!small_file_entry.deleted()) {
3156
57
                    ++left_file_count;
3157
57
                    left_file_bytes += small_file_entry.size();
3158
57
                }
3159
141
            }
3160
24
            packed_info.set_remaining_slice_bytes(left_file_bytes);
3161
24
            packed_info.set_ref_cnt(left_file_count);
3162
24
            LOG_INFO("updated packed file reference info")
3163
24
                    .tag("instance_id", instance_id_)
3164
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3165
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3166
24
                    .tag("packed_file_path", packed_file_path)
3167
24
                    .tag("ref_cnt", left_file_count)
3168
24
                    .tag("left_file_bytes", left_file_bytes);
3169
3170
24
            if (left_file_count == 0) {
3171
7
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3172
7
            }
3173
3174
24
            std::string updated_val;
3175
24
            if (!packed_info.SerializeToString(&updated_val)) {
3176
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
3177
0
                        .tag("instance_id", instance_id_)
3178
0
                        .tag("packed_file_path", packed_file_path)
3179
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3180
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3181
0
                ret = -1;
3182
0
                break;
3183
0
            }
3184
3185
24
            txn->put(packed_key, updated_val);
3186
24
            err = txn->commit();
3187
24
            if (err == TxnErrorCode::TXN_OK) {
3188
24
                success = true;
3189
24
                if (left_file_count == 0) {
3190
7
                    LOG_INFO("packed file ready to delete, deleting immediately")
3191
7
                            .tag("instance_id", instance_id_)
3192
7
                            .tag("packed_file_path", packed_file_path);
3193
7
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3194
0
                        ret = -1;
3195
0
                    }
3196
7
                }
3197
24
                break;
3198
24
            }
3199
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
3200
0
                if (attempt >= max_retry_times) {
3201
0
                    LOG_WARNING("packed file info update conflict after max retry")
3202
0
                            .tag("instance_id", instance_id_)
3203
0
                            .tag("packed_file_path", packed_file_path)
3204
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3205
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
3206
0
                            .tag("changed_files", changed_files)
3207
0
                            .tag("attempt", attempt);
3208
0
                    ret = -1;
3209
0
                    break;
3210
0
                }
3211
0
                LOG_WARNING("packed file info update conflict, retrying")
3212
0
                        .tag("instance_id", instance_id_)
3213
0
                        .tag("packed_file_path", packed_file_path)
3214
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3215
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3216
0
                        .tag("changed_files", changed_files)
3217
0
                        .tag("attempt", attempt);
3218
0
                sleep_for_packed_file_retry();
3219
0
                continue;
3220
0
            }
3221
3222
0
            LOG_WARNING("failed to commit packed file info update")
3223
0
                    .tag("instance_id", instance_id_)
3224
0
                    .tag("packed_file_path", packed_file_path)
3225
0
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3226
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3227
0
                    .tag("err", err)
3228
0
                    .tag("changed_files", changed_files);
3229
0
            ret = -1;
3230
0
            break;
3231
0
        }
3232
3233
24
        if (!success) {
3234
0
            ret = -1;
3235
0
        }
3236
24
    }
3237
3238
14
    return ret;
3239
14
}
3240
3241
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(int64_t tablet_id,
3242
                                                                     const std::string& rowset_id,
3243
58.2k
                                                                     bool* out_is_packed) {
3244
58.2k
    if (out_is_packed) {
3245
58.2k
        *out_is_packed = false;
3246
58.2k
    }
3247
3248
    // Get delete bitmap storage info from FDB
3249
58.2k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
3250
58.2k
    std::unique_ptr<Transaction> txn;
3251
58.2k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
3252
58.2k
    if (err != TxnErrorCode::TXN_OK) {
3253
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
3254
0
                .tag("instance_id", instance_id_)
3255
0
                .tag("tablet_id", tablet_id)
3256
0
                .tag("rowset_id", rowset_id)
3257
0
                .tag("err", err);
3258
0
        return -1;
3259
0
    }
3260
3261
58.2k
    std::string dbm_val;
3262
58.2k
    err = txn->get(dbm_key, &dbm_val);
3263
58.2k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3264
        // No delete bitmap for this rowset, nothing to do
3265
4.63k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
3266
4.63k
                .tag("instance_id", instance_id_)
3267
4.63k
                .tag("tablet_id", tablet_id)
3268
4.63k
                .tag("rowset_id", rowset_id);
3269
4.63k
        return 0;
3270
4.63k
    }
3271
53.5k
    if (err != TxnErrorCode::TXN_OK) {
3272
0
        LOG_WARNING("failed to get delete bitmap storage")
3273
0
                .tag("instance_id", instance_id_)
3274
0
                .tag("tablet_id", tablet_id)
3275
0
                .tag("rowset_id", rowset_id)
3276
0
                .tag("err", err);
3277
0
        return -1;
3278
0
    }
3279
3280
53.5k
    DeleteBitmapStoragePB storage;
3281
53.5k
    if (!storage.ParseFromString(dbm_val)) {
3282
0
        LOG_WARNING("failed to parse delete bitmap storage")
3283
0
                .tag("instance_id", instance_id_)
3284
0
                .tag("tablet_id", tablet_id)
3285
0
                .tag("rowset_id", rowset_id);
3286
0
        return -1;
3287
0
    }
3288
3289
    // Check if delete bitmap is stored in packed file
3290
53.5k
    if (!storage.has_packed_slice_location() ||
3291
53.5k
        storage.packed_slice_location().packed_file_path().empty()) {
3292
        // Not stored in packed file, nothing to do
3293
53.5k
        return 0;
3294
53.5k
    }
3295
3296
0
    if (out_is_packed) {
3297
0
        *out_is_packed = true;
3298
0
    }
3299
3300
0
    const auto& packed_loc = storage.packed_slice_location();
3301
0
    const std::string& packed_file_path = packed_loc.packed_file_path();
3302
3303
0
    LOG_INFO("decrementing delete bitmap packed file ref count")
3304
0
            .tag("instance_id", instance_id_)
3305
0
            .tag("tablet_id", tablet_id)
3306
0
            .tag("rowset_id", rowset_id)
3307
0
            .tag("packed_file_path", packed_file_path);
3308
3309
0
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3310
0
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3311
0
        std::unique_ptr<Transaction> update_txn;
3312
0
        err = txn_kv_->create_txn(&update_txn);
3313
0
        if (err != TxnErrorCode::TXN_OK) {
3314
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
3315
0
                    .tag("instance_id", instance_id_)
3316
0
                    .tag("tablet_id", tablet_id)
3317
0
                    .tag("rowset_id", rowset_id)
3318
0
                    .tag("err", err);
3319
0
            return -1;
3320
0
        }
3321
3322
0
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3323
0
        std::string packed_val;
3324
0
        err = update_txn->get(packed_key, &packed_val);
3325
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3326
0
            LOG_WARNING("packed file info not found for delete bitmap")
3327
0
                    .tag("instance_id", instance_id_)
3328
0
                    .tag("tablet_id", tablet_id)
3329
0
                    .tag("rowset_id", rowset_id)
3330
0
                    .tag("packed_file_path", packed_file_path);
3331
0
            return 0;
3332
0
        }
3333
0
        if (err != TxnErrorCode::TXN_OK) {
3334
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
3335
0
                    .tag("instance_id", instance_id_)
3336
0
                    .tag("tablet_id", tablet_id)
3337
0
                    .tag("rowset_id", rowset_id)
3338
0
                    .tag("packed_file_path", packed_file_path)
3339
0
                    .tag("err", err);
3340
0
            return -1;
3341
0
        }
3342
3343
0
        cloud::PackedFileInfoPB packed_info;
3344
0
        if (!packed_info.ParseFromString(packed_val)) {
3345
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
3346
0
                    .tag("instance_id", instance_id_)
3347
0
                    .tag("tablet_id", tablet_id)
3348
0
                    .tag("rowset_id", rowset_id)
3349
0
                    .tag("packed_file_path", packed_file_path);
3350
0
            return -1;
3351
0
        }
3352
3353
        // Find and mark the small file entry as deleted
3354
        // Use tablet_id and rowset_id to match entry instead of path,
3355
        // because path format may vary with path_version (with or without shard prefix)
3356
0
        auto* entries = packed_info.mutable_slices();
3357
0
        bool found = false;
3358
0
        bool already_deleted = false;
3359
0
        for (auto& entry : *entries) {
3360
0
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
3361
0
                if (!entry.deleted()) {
3362
0
                    entry.set_deleted(true);
3363
0
                    if (!entry.corrected()) {
3364
0
                        entry.set_corrected(true);
3365
0
                    }
3366
0
                } else {
3367
0
                    already_deleted = true;
3368
0
                }
3369
0
                found = true;
3370
0
                break;
3371
0
            }
3372
0
        }
3373
3374
0
        if (!found) {
3375
0
            LOG_WARNING("delete bitmap entry not found in packed file")
3376
0
                    .tag("instance_id", instance_id_)
3377
0
                    .tag("tablet_id", tablet_id)
3378
0
                    .tag("rowset_id", rowset_id)
3379
0
                    .tag("packed_file_path", packed_file_path);
3380
0
            return 0;
3381
0
        }
3382
3383
0
        if (already_deleted) {
3384
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
3385
0
                    .tag("instance_id", instance_id_)
3386
0
                    .tag("tablet_id", tablet_id)
3387
0
                    .tag("rowset_id", rowset_id)
3388
0
                    .tag("packed_file_path", packed_file_path);
3389
0
            return 0;
3390
0
        }
3391
3392
        // Calculate remaining files
3393
0
        int64_t left_file_count = 0;
3394
0
        int64_t left_file_bytes = 0;
3395
0
        for (const auto& entry : packed_info.slices()) {
3396
0
            if (!entry.deleted()) {
3397
0
                ++left_file_count;
3398
0
                left_file_bytes += entry.size();
3399
0
            }
3400
0
        }
3401
0
        packed_info.set_remaining_slice_bytes(left_file_bytes);
3402
0
        packed_info.set_ref_cnt(left_file_count);
3403
3404
0
        if (left_file_count == 0) {
3405
0
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3406
0
        }
3407
3408
0
        std::string updated_val;
3409
0
        if (!packed_info.SerializeToString(&updated_val)) {
3410
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
3411
0
                    .tag("instance_id", instance_id_)
3412
0
                    .tag("tablet_id", tablet_id)
3413
0
                    .tag("rowset_id", rowset_id)
3414
0
                    .tag("packed_file_path", packed_file_path);
3415
0
            return -1;
3416
0
        }
3417
3418
0
        update_txn->put(packed_key, updated_val);
3419
0
        err = update_txn->commit();
3420
0
        if (err == TxnErrorCode::TXN_OK) {
3421
0
            LOG_INFO("delete bitmap packed file ref count decremented")
3422
0
                    .tag("instance_id", instance_id_)
3423
0
                    .tag("tablet_id", tablet_id)
3424
0
                    .tag("rowset_id", rowset_id)
3425
0
                    .tag("packed_file_path", packed_file_path)
3426
0
                    .tag("left_file_count", left_file_count);
3427
0
            if (left_file_count == 0) {
3428
0
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3429
0
                    return -1;
3430
0
                }
3431
0
            }
3432
0
            return 0;
3433
0
        }
3434
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
3435
0
            if (attempt >= max_retry_times) {
3436
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
3437
0
                        .tag("instance_id", instance_id_)
3438
0
                        .tag("tablet_id", tablet_id)
3439
0
                        .tag("rowset_id", rowset_id)
3440
0
                        .tag("packed_file_path", packed_file_path)
3441
0
                        .tag("attempt", attempt);
3442
0
                return -1;
3443
0
            }
3444
0
            sleep_for_packed_file_retry();
3445
0
            continue;
3446
0
        }
3447
3448
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
3449
0
                .tag("instance_id", instance_id_)
3450
0
                .tag("tablet_id", tablet_id)
3451
0
                .tag("rowset_id", rowset_id)
3452
0
                .tag("packed_file_path", packed_file_path)
3453
0
                .tag("err", err);
3454
0
        return -1;
3455
0
    }
3456
3457
0
    return -1;
3458
0
}
3459
3460
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
3461
                                                const std::string& packed_key,
3462
7
                                                const cloud::PackedFileInfoPB& packed_info) {
3463
7
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
3464
0
        LOG_WARNING("packed file missing resource id when recycling")
3465
0
                .tag("instance_id", instance_id_)
3466
0
                .tag("packed_file_path", packed_file_path);
3467
0
        return -1;
3468
0
    }
3469
3470
7
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
3471
7
    if (!accessor) {
3472
0
        LOG_WARNING("no accessor available to delete packed file")
3473
0
                .tag("instance_id", instance_id_)
3474
0
                .tag("packed_file_path", packed_file_path)
3475
0
                .tag("resource_id", packed_info.resource_id());
3476
0
        return -1;
3477
0
    }
3478
3479
7
    int del_ret = accessor->delete_file(packed_file_path);
3480
7
    if (del_ret != 0 && del_ret != 1) {
3481
0
        LOG_WARNING("failed to delete packed file")
3482
0
                .tag("instance_id", instance_id_)
3483
0
                .tag("packed_file_path", packed_file_path)
3484
0
                .tag("resource_id", resource_id)
3485
0
                .tag("ret", del_ret);
3486
0
        return -1;
3487
0
    }
3488
7
    if (del_ret == 1) {
3489
0
        LOG_INFO("packed file already removed")
3490
0
                .tag("instance_id", instance_id_)
3491
0
                .tag("packed_file_path", packed_file_path)
3492
0
                .tag("resource_id", resource_id);
3493
7
    } else {
3494
7
        LOG_INFO("deleted packed file")
3495
7
                .tag("instance_id", instance_id_)
3496
7
                .tag("packed_file_path", packed_file_path)
3497
7
                .tag("resource_id", resource_id);
3498
7
    }
3499
3500
7
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
3501
7
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3502
7
        std::unique_ptr<Transaction> del_txn;
3503
7
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
3504
7
        if (err != TxnErrorCode::TXN_OK) {
3505
0
            LOG_WARNING("failed to create txn when removing packed file kv")
3506
0
                    .tag("instance_id", instance_id_)
3507
0
                    .tag("packed_file_path", packed_file_path)
3508
0
                    .tag("attempt", attempt)
3509
0
                    .tag("err", err);
3510
0
            return -1;
3511
0
        }
3512
3513
7
        std::string latest_val;
3514
7
        err = del_txn->get(packed_key, &latest_val);
3515
7
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3516
0
            return 0;
3517
0
        }
3518
7
        if (err != TxnErrorCode::TXN_OK) {
3519
0
            LOG_WARNING("failed to re-read packed file kv before removal")
3520
0
                    .tag("instance_id", instance_id_)
3521
0
                    .tag("packed_file_path", packed_file_path)
3522
0
                    .tag("attempt", attempt)
3523
0
                    .tag("err", err);
3524
0
            return -1;
3525
0
        }
3526
3527
7
        cloud::PackedFileInfoPB latest_info;
3528
7
        if (!latest_info.ParseFromString(latest_val)) {
3529
0
            LOG_WARNING("failed to parse packed file info before removal")
3530
0
                    .tag("instance_id", instance_id_)
3531
0
                    .tag("packed_file_path", packed_file_path)
3532
0
                    .tag("attempt", attempt);
3533
0
            return -1;
3534
0
        }
3535
3536
7
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
3537
7
              latest_info.ref_cnt() == 0)) {
3538
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
3539
0
                    .tag("instance_id", instance_id_)
3540
0
                    .tag("packed_file_path", packed_file_path)
3541
0
                    .tag("attempt", attempt);
3542
0
            return 0;
3543
0
        }
3544
3545
7
        del_txn->remove(packed_key);
3546
7
        err = del_txn->commit();
3547
7
        if (err == TxnErrorCode::TXN_OK) {
3548
7
            LOG_INFO("removed packed file metadata")
3549
7
                    .tag("instance_id", instance_id_)
3550
7
                    .tag("packed_file_path", packed_file_path);
3551
7
            return 0;
3552
7
        }
3553
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
3554
0
            if (attempt >= max_retry_times) {
3555
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
3556
0
                        .tag("instance_id", instance_id_)
3557
0
                        .tag("packed_file_path", packed_file_path)
3558
0
                        .tag("attempt", attempt);
3559
0
                return -1;
3560
0
            }
3561
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
3562
0
                    .tag("instance_id", instance_id_)
3563
0
                    .tag("packed_file_path", packed_file_path)
3564
0
                    .tag("attempt", attempt);
3565
0
            sleep_for_packed_file_retry();
3566
0
            continue;
3567
0
        }
3568
0
        LOG_WARNING("failed to remove packed file kv")
3569
0
                .tag("instance_id", instance_id_)
3570
0
                .tag("packed_file_path", packed_file_path)
3571
0
                .tag("attempt", attempt)
3572
0
                .tag("err", err);
3573
0
        return -1;
3574
0
    }
3575
0
    return -1;
3576
7
}
3577
3578
int InstanceRecycler::delete_rowset_data(
3579
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
3580
92
        RecyclerMetricsContext& metrics_context) {
3581
92
    int ret = 0;
3582
    // resource_id -> file_paths
3583
92
    std::map<std::string, std::vector<std::string>> resource_file_paths;
3584
    // (resource_id, tablet_id, rowset_id)
3585
92
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
3586
92
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
3587
3588
54.1k
    for (const auto& [_, rs] : rowsets) {
3589
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
3590
        // due to aborted schema change.
3591
54.1k
        if (is_formal_rowset) {
3592
3.16k
            std::lock_guard lock(recycled_tablets_mtx_);
3593
3.16k
            if (recycled_tablets_.count(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
3594
                // Tablet has been recycled and this rowset has no packed slices, so file data
3595
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
3596
                // slice info must still run to decrement packed file ref counts.
3597
0
                continue;
3598
0
            }
3599
3.16k
        }
3600
3601
54.1k
        auto it = accessor_map_.find(rs.resource_id());
3602
        // possible if the accessor is not initilized correctly
3603
54.1k
        if (it == accessor_map_.end()) [[unlikely]] {
3604
1
            LOG_WARNING("instance has no such resource id")
3605
1
                    .tag("instance_id", instance_id_)
3606
1
                    .tag("resource_id", rs.resource_id());
3607
1
            ret = -1;
3608
1
            continue;
3609
1
        }
3610
3611
54.1k
        auto& file_paths = resource_file_paths[rs.resource_id()];
3612
54.1k
        const auto& rowset_id = rs.rowset_id_v2();
3613
54.1k
        int64_t tablet_id = rs.tablet_id();
3614
54.1k
        LOG_INFO("recycle rowset merge index size")
3615
54.1k
                .tag("instance_id", instance_id_)
3616
54.1k
                .tag("tablet_id", tablet_id)
3617
54.1k
                .tag("rowset_id", rowset_id)
3618
54.1k
                .tag("merge_index_size", rs.packed_slice_locations_size());
3619
54.1k
        if (decrement_packed_file_ref_counts(rs) != 0) {
3620
0
            ret = -1;
3621
0
            continue;
3622
0
        }
3623
54.1k
        int64_t num_segments = rs.num_segments();
3624
54.1k
        if (num_segments <= 0) {
3625
0
            metrics_context.total_recycled_num++;
3626
0
            metrics_context.total_recycled_data_size += rs.total_disk_size();
3627
0
            continue;
3628
0
        }
3629
3630
        // Process delete bitmap - check if it's stored in packed file
3631
54.1k
        bool delete_bitmap_is_packed = false;
3632
54.1k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3633
54.1k
                                                           &delete_bitmap_is_packed) != 0) {
3634
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3635
0
                    .tag("instance_id", instance_id_)
3636
0
                    .tag("tablet_id", tablet_id)
3637
0
                    .tag("rowset_id", rowset_id);
3638
0
            ret = -1;
3639
0
            continue;
3640
0
        }
3641
        // Only delete standalone delete bitmap file if not stored in packed file
3642
54.2k
        if (!delete_bitmap_is_packed) {
3643
54.2k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3644
54.2k
        }
3645
3646
        // Process inverted indexes
3647
54.1k
        std::vector<std::pair<int64_t, std::string>> index_ids;
3648
        // default format as v1.
3649
54.1k
        InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
3650
54.1k
        int inverted_index_get_ret = 0;
3651
54.1k
        if (rs.has_tablet_schema()) {
3652
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
3653
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3654
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3655
53.5k
                }
3656
53.5k
            }
3657
26.6k
            if (rs.tablet_schema().has_inverted_index_storage_format()) {
3658
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
3659
26.5k
            }
3660
27.5k
        } else {
3661
27.5k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
3662
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
3663
0
                                "instance_id="
3664
0
                             << instance_id_ << " tablet_id=" << tablet_id
3665
0
                             << " rowset_id=" << rowset_id;
3666
0
                ret = -1;
3667
0
                continue;
3668
0
            }
3669
27.5k
            InvertedIndexInfo index_info;
3670
27.5k
            inverted_index_get_ret =
3671
27.5k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
3672
27.5k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3673
27.5k
                                     &inverted_index_get_ret);
3674
27.5k
            if (inverted_index_get_ret == 0) {
3675
27.0k
                index_format = index_info.first;
3676
27.0k
                index_ids = index_info.second;
3677
27.0k
            } else if (inverted_index_get_ret == 1) {
3678
                // 1. Schema kv not found means tablet has been recycled
3679
                // Maybe some tablet recycle failed by some bugs
3680
                // We need to delete again to double check
3681
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3682
                // because we are uncertain about the inverted index information.
3683
                // If there are inverted indexes, some data might not be deleted,
3684
                // but this is acceptable as we have made our best effort to delete the data.
3685
507
                LOG_INFO(
3686
507
                        "delete rowset data schema kv not found, need to delete again to "
3687
507
                        "double "
3688
507
                        "check")
3689
507
                        .tag("instance_id", instance_id_)
3690
507
                        .tag("tablet_id", tablet_id)
3691
507
                        .tag("rowset", rs.ShortDebugString());
3692
                // Currently index_ids is guaranteed to be empty,
3693
                // but we clear it again here as a safeguard against future code changes
3694
                // that might cause index_ids to no longer be empty
3695
507
                index_format = InvertedIndexStorageFormatPB::V2;
3696
507
                index_ids.clear();
3697
18.4E
            } else {
3698
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
3699
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
3700
18.4E
                ret = -1;
3701
18.4E
                continue;
3702
18.4E
            }
3703
27.5k
        }
3704
54.2k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3705
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3706
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3707
5
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
3708
5
            continue;
3709
5
        }
3710
323k
        for (int64_t i = 0; i < num_segments; ++i) {
3711
269k
            file_paths.push_back(segment_path(tablet_id, rowset_id, i));
3712
269k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
3713
535k
                for (const auto& index_id : index_ids) {
3714
535k
                    file_paths.push_back(inverted_index_path_v1(tablet_id, rowset_id, i,
3715
535k
                                                                index_id.first, index_id.second));
3716
535k
                }
3717
267k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
3718
                // try to recycle inverted index v2 when get_ret == 1
3719
                // we treat schema not found as if it has a v2 format inverted index
3720
                // to reduce chance of data leakage
3721
2.50k
                if (inverted_index_get_ret == 1) {
3722
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
3723
2.50k
                            .tag("instance_id", instance_id_)
3724
2.50k
                            .tag("inverted index v2 path",
3725
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, i));
3726
2.50k
                }
3727
2.50k
                file_paths.push_back(inverted_index_path_v2(tablet_id, rowset_id, i));
3728
2.50k
            }
3729
269k
        }
3730
54.1k
    }
3731
3732
92
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
3733
92
                                                 "delete_rowset_data",
3734
92
                                                 [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clERKi
Line
Count
Source
3734
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
3734
50
                                                 [](const int& ret) { return ret != 0; });
3735
92
    for (auto& [resource_id, file_paths] : resource_file_paths) {
3736
50
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
3737
50
            DCHECK(accessor_map_.count(*rid))
3738
0
                    << "uninitilized accessor, instance_id=" << instance_id_
3739
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
3740
50
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
3741
50
                                     &accessor_map_);
3742
50
            if (!accessor_map_.contains(*rid)) {
3743
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
3744
0
                        .tag("resource_id", resource_id)
3745
0
                        .tag("instance_id", instance_id_);
3746
0
                return -1;
3747
0
            }
3748
50
            auto& accessor = accessor_map_[*rid];
3749
50
            int ret = accessor->delete_files(*paths);
3750
50
            if (!ret) {
3751
                // deduplication of different files with the same rowset id
3752
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
3753
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
3754
50
                std::set<std::string> deleted_rowset_id;
3755
3756
50
                std::for_each(paths->begin(), paths->end(),
3757
50
                              [&metrics_context, &rowsets, &deleted_rowset_id,
3758
861k
                               this](const std::string& path) {
3759
861k
                                  std::vector<std::string> str;
3760
861k
                                  butil::SplitString(path, '/', &str);
3761
861k
                                  std::string rowset_id;
3762
861k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3763
859k
                                      rowset_id = str.back().substr(0, pos);
3764
859k
                                  } else {
3765
2.46k
                                      if (path.find("packed_file/") != std::string::npos) {
3766
0
                                          return; // packed files do not have rowset_id encoded
3767
0
                                      }
3768
2.46k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3769
2.46k
                                      return;
3770
2.46k
                                  }
3771
859k
                                  auto rs_meta = rowsets.find(rowset_id);
3772
859k
                                  if (rs_meta != rowsets.end() &&
3773
862k
                                      !deleted_rowset_id.contains(rowset_id)) {
3774
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
3775
54.1k
                                      metrics_context.total_recycled_data_size +=
3776
54.1k
                                              rs_meta->second.total_disk_size();
3777
54.1k
                                      segment_metrics_context_.total_recycled_num +=
3778
54.1k
                                              rs_meta->second.num_segments();
3779
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
3780
54.1k
                                              rs_meta->second.total_disk_size();
3781
54.1k
                                      metrics_context.total_recycled_num++;
3782
54.1k
                                  }
3783
859k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
3758
14
                               this](const std::string& path) {
3759
14
                                  std::vector<std::string> str;
3760
14
                                  butil::SplitString(path, '/', &str);
3761
14
                                  std::string rowset_id;
3762
14
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3763
14
                                      rowset_id = str.back().substr(0, pos);
3764
14
                                  } else {
3765
0
                                      if (path.find("packed_file/") != std::string::npos) {
3766
0
                                          return; // packed files do not have rowset_id encoded
3767
0
                                      }
3768
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3769
0
                                      return;
3770
0
                                  }
3771
14
                                  auto rs_meta = rowsets.find(rowset_id);
3772
14
                                  if (rs_meta != rowsets.end() &&
3773
14
                                      !deleted_rowset_id.contains(rowset_id)) {
3774
7
                                      deleted_rowset_id.emplace(rowset_id);
3775
7
                                      metrics_context.total_recycled_data_size +=
3776
7
                                              rs_meta->second.total_disk_size();
3777
7
                                      segment_metrics_context_.total_recycled_num +=
3778
7
                                              rs_meta->second.num_segments();
3779
7
                                      segment_metrics_context_.total_recycled_data_size +=
3780
7
                                              rs_meta->second.total_disk_size();
3781
7
                                      metrics_context.total_recycled_num++;
3782
7
                                  }
3783
14
                              });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
3758
861k
                               this](const std::string& path) {
3759
861k
                                  std::vector<std::string> str;
3760
861k
                                  butil::SplitString(path, '/', &str);
3761
861k
                                  std::string rowset_id;
3762
861k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3763
859k
                                      rowset_id = str.back().substr(0, pos);
3764
859k
                                  } else {
3765
2.46k
                                      if (path.find("packed_file/") != std::string::npos) {
3766
0
                                          return; // packed files do not have rowset_id encoded
3767
0
                                      }
3768
2.46k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3769
2.46k
                                      return;
3770
2.46k
                                  }
3771
859k
                                  auto rs_meta = rowsets.find(rowset_id);
3772
859k
                                  if (rs_meta != rowsets.end() &&
3773
862k
                                      !deleted_rowset_id.contains(rowset_id)) {
3774
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
3775
54.1k
                                      metrics_context.total_recycled_data_size +=
3776
54.1k
                                              rs_meta->second.total_disk_size();
3777
54.1k
                                      segment_metrics_context_.total_recycled_num +=
3778
54.1k
                                              rs_meta->second.num_segments();
3779
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
3780
54.1k
                                              rs_meta->second.total_disk_size();
3781
54.1k
                                      metrics_context.total_recycled_num++;
3782
54.1k
                                  }
3783
859k
                              });
3784
50
            }
3785
50
            return ret;
3786
50
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
3736
5
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
3737
5
            DCHECK(accessor_map_.count(*rid))
3738
0
                    << "uninitilized accessor, instance_id=" << instance_id_
3739
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
3740
5
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
3741
5
                                     &accessor_map_);
3742
5
            if (!accessor_map_.contains(*rid)) {
3743
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
3744
0
                        .tag("resource_id", resource_id)
3745
0
                        .tag("instance_id", instance_id_);
3746
0
                return -1;
3747
0
            }
3748
5
            auto& accessor = accessor_map_[*rid];
3749
5
            int ret = accessor->delete_files(*paths);
3750
5
            if (!ret) {
3751
                // deduplication of different files with the same rowset id
3752
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
3753
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
3754
5
                std::set<std::string> deleted_rowset_id;
3755
3756
5
                std::for_each(paths->begin(), paths->end(),
3757
5
                              [&metrics_context, &rowsets, &deleted_rowset_id,
3758
5
                               this](const std::string& path) {
3759
5
                                  std::vector<std::string> str;
3760
5
                                  butil::SplitString(path, '/', &str);
3761
5
                                  std::string rowset_id;
3762
5
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3763
5
                                      rowset_id = str.back().substr(0, pos);
3764
5
                                  } else {
3765
5
                                      if (path.find("packed_file/") != std::string::npos) {
3766
5
                                          return; // packed files do not have rowset_id encoded
3767
5
                                      }
3768
5
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3769
5
                                      return;
3770
5
                                  }
3771
5
                                  auto rs_meta = rowsets.find(rowset_id);
3772
5
                                  if (rs_meta != rowsets.end() &&
3773
5
                                      !deleted_rowset_id.contains(rowset_id)) {
3774
5
                                      deleted_rowset_id.emplace(rowset_id);
3775
5
                                      metrics_context.total_recycled_data_size +=
3776
5
                                              rs_meta->second.total_disk_size();
3777
5
                                      segment_metrics_context_.total_recycled_num +=
3778
5
                                              rs_meta->second.num_segments();
3779
5
                                      segment_metrics_context_.total_recycled_data_size +=
3780
5
                                              rs_meta->second.total_disk_size();
3781
5
                                      metrics_context.total_recycled_num++;
3782
5
                                  }
3783
5
                              });
3784
5
            }
3785
5
            return ret;
3786
5
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
3736
45
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
3737
45
            DCHECK(accessor_map_.count(*rid))
3738
0
                    << "uninitilized accessor, instance_id=" << instance_id_
3739
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
3740
45
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
3741
45
                                     &accessor_map_);
3742
45
            if (!accessor_map_.contains(*rid)) {
3743
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
3744
0
                        .tag("resource_id", resource_id)
3745
0
                        .tag("instance_id", instance_id_);
3746
0
                return -1;
3747
0
            }
3748
45
            auto& accessor = accessor_map_[*rid];
3749
45
            int ret = accessor->delete_files(*paths);
3750
45
            if (!ret) {
3751
                // deduplication of different files with the same rowset id
3752
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
3753
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
3754
45
                std::set<std::string> deleted_rowset_id;
3755
3756
45
                std::for_each(paths->begin(), paths->end(),
3757
45
                              [&metrics_context, &rowsets, &deleted_rowset_id,
3758
45
                               this](const std::string& path) {
3759
45
                                  std::vector<std::string> str;
3760
45
                                  butil::SplitString(path, '/', &str);
3761
45
                                  std::string rowset_id;
3762
45
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3763
45
                                      rowset_id = str.back().substr(0, pos);
3764
45
                                  } else {
3765
45
                                      if (path.find("packed_file/") != std::string::npos) {
3766
45
                                          return; // packed files do not have rowset_id encoded
3767
45
                                      }
3768
45
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3769
45
                                      return;
3770
45
                                  }
3771
45
                                  auto rs_meta = rowsets.find(rowset_id);
3772
45
                                  if (rs_meta != rowsets.end() &&
3773
45
                                      !deleted_rowset_id.contains(rowset_id)) {
3774
45
                                      deleted_rowset_id.emplace(rowset_id);
3775
45
                                      metrics_context.total_recycled_data_size +=
3776
45
                                              rs_meta->second.total_disk_size();
3777
45
                                      segment_metrics_context_.total_recycled_num +=
3778
45
                                              rs_meta->second.num_segments();
3779
45
                                      segment_metrics_context_.total_recycled_data_size +=
3780
45
                                              rs_meta->second.total_disk_size();
3781
45
                                      metrics_context.total_recycled_num++;
3782
45
                                  }
3783
45
                              });
3784
45
            }
3785
45
            return ret;
3786
45
        });
3787
50
    }
3788
92
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
3789
5
        LOG_INFO(
3790
5
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
3791
5
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
3792
5
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
3793
5
        concurrent_delete_executor.add([&]() -> int {
3794
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
3795
5
            if (!ret) {
3796
5
                auto rs = rowsets.at(rowset_id);
3797
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
3798
5
                metrics_context.total_recycled_num++;
3799
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
3800
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
3801
5
            }
3802
5
            return ret;
3803
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
3793
5
        concurrent_delete_executor.add([&]() -> int {
3794
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
3795
5
            if (!ret) {
3796
5
                auto rs = rowsets.at(rowset_id);
3797
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
3798
5
                metrics_context.total_recycled_num++;
3799
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
3800
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
3801
5
            }
3802
5
            return ret;
3803
5
        });
3804
5
    }
3805
3806
92
    bool finished = true;
3807
92
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
3808
92
    for (int r : rets) {
3809
55
        if (r != 0) {
3810
0
            ret = -1;
3811
0
            break;
3812
0
        }
3813
55
    }
3814
92
    ret = finished ? ret : -1;
3815
92
    return ret;
3816
92
}
3817
3818
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
3819
3.30k
                                         const std::string& rowset_id) {
3820
3.30k
    auto it = accessor_map_.find(resource_id);
3821
3.30k
    if (it == accessor_map_.end()) {
3822
400
        LOG_WARNING("instance has no such resource id")
3823
400
                .tag("instance_id", instance_id_)
3824
400
                .tag("resource_id", resource_id)
3825
400
                .tag("tablet_id", tablet_id)
3826
400
                .tag("rowset_id", rowset_id);
3827
400
        return -1;
3828
400
    }
3829
2.90k
    auto& accessor = it->second;
3830
2.90k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
3831
3.30k
}
3832
3833
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
3834
4
    if (key.empty()) {
3835
0
        return false;
3836
0
    }
3837
4
    std::string_view key_view = key;
3838
4
    key_view.remove_prefix(1); // remove keyspace prefix
3839
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
3840
4
    if (decode_key(&key_view, &decoded) != 0) {
3841
0
        return false;
3842
0
    }
3843
4
    if (decoded.size() < 4) {
3844
0
        return false;
3845
0
    }
3846
4
    try {
3847
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
3848
4
    } catch (const std::bad_variant_access&) {
3849
0
        return false;
3850
0
    }
3851
4
    return true;
3852
4
}
3853
3854
14
int InstanceRecycler::recycle_packed_files() {
3855
14
    const std::string task_name = "recycle_packed_files";
3856
14
    auto start_tp = steady_clock::now();
3857
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
3858
14
    int ret = 0;
3859
14
    PackedFileRecycleStats stats;
3860
3861
14
    register_recycle_task(task_name, start_time);
3862
14
    DORIS_CLOUD_DEFER {
3863
14
        unregister_recycle_task(task_name);
3864
14
        int64_t cost =
3865
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3866
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
3867
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
3868
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
3869
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
3870
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
3871
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
3872
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
3873
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
3874
14
                                                             stats.bytes_object_deleted);
3875
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
3876
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
3877
14
                .tag("instance_id", instance_id_)
3878
14
                .tag("num_scanned", stats.num_scanned)
3879
14
                .tag("num_corrected", stats.num_corrected)
3880
14
                .tag("num_deleted", stats.num_deleted)
3881
14
                .tag("num_failed", stats.num_failed)
3882
14
                .tag("num_objects_deleted", stats.num_object_deleted)
3883
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
3884
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
3885
14
                .tag("bytes_deleted", stats.bytes_deleted)
3886
14
                .tag("ret", ret);
3887
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
3862
14
    DORIS_CLOUD_DEFER {
3863
14
        unregister_recycle_task(task_name);
3864
14
        int64_t cost =
3865
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3866
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
3867
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
3868
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
3869
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
3870
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
3871
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
3872
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
3873
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
3874
14
                                                             stats.bytes_object_deleted);
3875
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
3876
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
3877
14
                .tag("instance_id", instance_id_)
3878
14
                .tag("num_scanned", stats.num_scanned)
3879
14
                .tag("num_corrected", stats.num_corrected)
3880
14
                .tag("num_deleted", stats.num_deleted)
3881
14
                .tag("num_failed", stats.num_failed)
3882
14
                .tag("num_objects_deleted", stats.num_object_deleted)
3883
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
3884
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
3885
14
                .tag("bytes_deleted", stats.bytes_deleted)
3886
14
                .tag("ret", ret);
3887
14
    };
3888
3889
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
3890
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
3891
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
3892
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
3889
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
3890
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
3891
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
3892
4
    };
3893
3894
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
3895
3896
14
    std::string begin = packed_file_key({instance_id_, ""});
3897
14
    std::string end = packed_file_key({instance_id_, "\xff"});
3898
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
3899
0
        ret = -1;
3900
0
    }
3901
3902
14
    return ret;
3903
14
}
3904
3905
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
3906
                                                  RecyclerMetricsContext& metrics_context,
3907
0
                                                  int64_t partition_id, bool is_empty_tablet) {
3908
0
    std::string tablet_key_begin, tablet_key_end;
3909
3910
0
    if (partition_id > 0) {
3911
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
3912
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
3913
0
    } else {
3914
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
3915
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
3916
0
    }
3917
    // for calculate the total num or bytes of recyled objects
3918
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
3919
0
                                                          std::string_view v) -> int {
3920
0
        doris::TabletMetaCloudPB tablet_meta_pb;
3921
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3922
0
            return 0;
3923
0
        }
3924
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3925
3926
0
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3927
0
            return 0;
3928
0
        }
3929
3930
0
        if (!is_empty_tablet) {
3931
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
3932
0
                return 0;
3933
0
            }
3934
0
            tablet_metrics_context_.total_need_recycle_num++;
3935
0
        }
3936
0
        return 0;
3937
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_
3938
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
3939
0
    metrics_context.report(true);
3940
0
    tablet_metrics_context_.report(true);
3941
0
    segment_metrics_context_.report(true);
3942
0
    return ret;
3943
0
}
3944
3945
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
3946
0
                                                 RecyclerMetricsContext& metrics_context) {
3947
0
    int ret = 0;
3948
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
3949
0
    std::unique_ptr<Transaction> txn;
3950
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3951
0
        LOG_WARNING("failed to recycle tablet ")
3952
0
                .tag("tablet id", tablet_id)
3953
0
                .tag("instance_id", instance_id_)
3954
0
                .tag("reason", "failed to create txn");
3955
0
        ret = -1;
3956
0
    }
3957
0
    GetRowsetResponse resp;
3958
0
    std::string msg;
3959
0
    MetaServiceCode code = MetaServiceCode::OK;
3960
    // get rowsets in tablet
3961
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
3962
0
                        tablet_id, code, msg, &resp);
3963
0
    if (code != MetaServiceCode::OK) {
3964
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
3965
0
                .tag("tablet id", tablet_id)
3966
0
                .tag("msg", msg)
3967
0
                .tag("code", code)
3968
0
                .tag("instance id", instance_id_);
3969
0
        ret = -1;
3970
0
    }
3971
0
    for (const auto& rs_meta : resp.rowset_meta()) {
3972
        /*
3973
        * For compatibility, we skip the loop for [0-1] here.
3974
        * The purpose of this loop is to delete object files,
3975
        * and since [0-1] only has meta and doesn't have object files,
3976
        * skipping it doesn't affect system correctness.
3977
        *
3978
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
3979
        * would return error -1 directly, causing the recycle operation to fail.
3980
        *
3981
        * [0-1] doesn't have resource id is a bug.
3982
        * In the future, we will fix this problem, after that,
3983
        * we can remove this if statement.
3984
        *
3985
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
3986
        */
3987
3988
0
        if (rs_meta.end_version() == 1) {
3989
            // Assert that [0-1] has no resource_id to make sure
3990
            // this if statement will not be forgetted to remove
3991
            // when the resource id bug is fixed
3992
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
3993
0
            continue;
3994
0
        }
3995
0
        if (!rs_meta.has_resource_id()) {
3996
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
3997
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
3998
0
                    .tag("instance_id", instance_id_)
3999
0
                    .tag("tablet_id", tablet_id);
4000
0
            continue;
4001
0
        }
4002
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4003
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4004
        // possible if the accessor is not initilized correctly
4005
0
        if (it == accessor_map_.end()) [[unlikely]] {
4006
0
            LOG_WARNING(
4007
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4008
0
                    "recycle process")
4009
0
                    .tag("tablet id", tablet_id)
4010
0
                    .tag("instance_id", instance_id_)
4011
0
                    .tag("resource_id", rs_meta.resource_id())
4012
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4013
0
            continue;
4014
0
        }
4015
4016
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
4017
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4018
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4019
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
4020
0
    }
4021
0
    return ret;
4022
0
}
4023
4024
4.25k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
4025
4.25k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
4026
4.25k
            .tag("instance_id", instance_id_)
4027
4.25k
            .tag("tablet_id", tablet_id);
4028
4029
4.25k
    if (should_recycle_versioned_keys()) {
4030
11
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
4031
11
        if (ret != 0) {
4032
0
            return ret;
4033
0
        }
4034
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
4035
        // during the recycle_versioned_tablet process.
4036
        //
4037
        // .. And remove restore job rowsets of this tablet too
4038
11
    }
4039
4040
4.25k
    int ret = 0;
4041
4.25k
    auto start_time = steady_clock::now();
4042
4043
4.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4044
4045
    // collect resource ids
4046
249
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4047
249
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4048
249
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4049
249
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4050
249
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
4051
249
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
4052
4053
249
    std::set<std::string> resource_ids;
4054
249
    int64_t recycle_rowsets_number = 0;
4055
249
    int64_t recycle_segments_number = 0;
4056
249
    int64_t recycle_rowsets_data_size = 0;
4057
249
    int64_t recycle_rowsets_index_size = 0;
4058
249
    int64_t recycle_restore_job_rowsets_number = 0;
4059
249
    int64_t recycle_restore_job_segments_number = 0;
4060
249
    int64_t recycle_restore_job_rowsets_data_size = 0;
4061
249
    int64_t recycle_restore_job_rowsets_index_size = 0;
4062
249
    int64_t max_rowset_version = 0;
4063
249
    int64_t min_rowset_creation_time = INT64_MAX;
4064
249
    int64_t max_rowset_creation_time = 0;
4065
249
    int64_t min_rowset_expiration_time = INT64_MAX;
4066
249
    int64_t max_rowset_expiration_time = 0;
4067
4068
249
    DORIS_CLOUD_DEFER {
4069
248
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4070
248
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4071
248
                .tag("instance_id", instance_id_)
4072
248
                .tag("tablet_id", tablet_id)
4073
248
                .tag("recycle rowsets number", recycle_rowsets_number)
4074
248
                .tag("recycle segments number", recycle_segments_number)
4075
248
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4076
248
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4077
248
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4078
248
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4079
248
                .tag("all restore job rowsets recycle data size",
4080
248
                     recycle_restore_job_rowsets_data_size)
4081
248
                .tag("all restore job rowsets recycle index size",
4082
248
                     recycle_restore_job_rowsets_index_size)
4083
248
                .tag("max rowset version", max_rowset_version)
4084
248
                .tag("min rowset creation time", min_rowset_creation_time)
4085
248
                .tag("max rowset creation time", max_rowset_creation_time)
4086
248
                .tag("min rowset expiration time", min_rowset_expiration_time)
4087
248
                .tag("max rowset expiration time", max_rowset_expiration_time)
4088
248
                .tag("task type", metrics_context.operation_type)
4089
248
                .tag("ret", ret);
4090
248
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4068
248
    DORIS_CLOUD_DEFER {
4069
248
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4070
248
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4071
248
                .tag("instance_id", instance_id_)
4072
248
                .tag("tablet_id", tablet_id)
4073
248
                .tag("recycle rowsets number", recycle_rowsets_number)
4074
248
                .tag("recycle segments number", recycle_segments_number)
4075
248
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4076
248
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4077
248
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4078
248
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4079
248
                .tag("all restore job rowsets recycle data size",
4080
248
                     recycle_restore_job_rowsets_data_size)
4081
248
                .tag("all restore job rowsets recycle index size",
4082
248
                     recycle_restore_job_rowsets_index_size)
4083
248
                .tag("max rowset version", max_rowset_version)
4084
248
                .tag("min rowset creation time", min_rowset_creation_time)
4085
248
                .tag("max rowset creation time", max_rowset_creation_time)
4086
248
                .tag("min rowset expiration time", min_rowset_expiration_time)
4087
248
                .tag("max rowset expiration time", max_rowset_expiration_time)
4088
248
                .tag("task type", metrics_context.operation_type)
4089
248
                .tag("ret", ret);
4090
248
    };
4091
4092
249
    std::unique_ptr<Transaction> txn;
4093
249
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4094
0
        LOG_WARNING("failed to recycle tablet ")
4095
0
                .tag("tablet id", tablet_id)
4096
0
                .tag("instance_id", instance_id_)
4097
0
                .tag("reason", "failed to create txn");
4098
0
        ret = -1;
4099
0
    }
4100
249
    GetRowsetResponse resp;
4101
249
    std::string msg;
4102
249
    MetaServiceCode code = MetaServiceCode::OK;
4103
    // get rowsets in tablet
4104
249
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4105
249
                        tablet_id, code, msg, &resp);
4106
249
    if (code != MetaServiceCode::OK) {
4107
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4108
0
                .tag("tablet id", tablet_id)
4109
0
                .tag("msg", msg)
4110
0
                .tag("code", code)
4111
0
                .tag("instance id", instance_id_);
4112
0
        ret = -1;
4113
0
    }
4114
249
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
4115
4116
2.51k
    for (const auto& rs_meta : resp.rowset_meta()) {
4117
        // The rowset has no resource id and segments when it was generated by compaction
4118
        // with multiple hole rowsets or it's version is [0-1], so we can skip it.
4119
2.51k
        if (!rs_meta.has_resource_id() && rs_meta.num_segments() == 0) {
4120
0
            LOG_INFO("rowset meta does not have a resource id and no segments, skip this rowset")
4121
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4122
0
                    .tag("instance_id", instance_id_)
4123
0
                    .tag("tablet_id", tablet_id);
4124
0
            recycle_rowsets_number += 1;
4125
0
            continue;
4126
0
        }
4127
2.51k
        if (!rs_meta.has_resource_id()) {
4128
1
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4129
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
4130
1
                    .tag("instance_id", instance_id_)
4131
1
                    .tag("tablet_id", tablet_id);
4132
1
            return -1;
4133
1
        }
4134
2.51k
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4135
2.51k
        auto it = accessor_map_.find(rs_meta.resource_id());
4136
        // possible if the accessor is not initilized correctly
4137
2.51k
        if (it == accessor_map_.end()) [[unlikely]] {
4138
1
            LOG_WARNING(
4139
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4140
1
                    "recycle process")
4141
1
                    .tag("tablet id", tablet_id)
4142
1
                    .tag("instance_id", instance_id_)
4143
1
                    .tag("resource_id", rs_meta.resource_id())
4144
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4145
1
            return -1;
4146
1
        }
4147
2.51k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4148
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
4149
0
                    .tag("instance_id", instance_id_)
4150
0
                    .tag("tablet_id", tablet_id)
4151
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4152
0
            return -1;
4153
0
        }
4154
2.51k
        recycle_rowsets_number += 1;
4155
2.51k
        recycle_segments_number += rs_meta.num_segments();
4156
2.51k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4157
2.51k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4158
2.51k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4159
2.51k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4160
2.51k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4161
2.51k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4162
2.51k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4163
2.51k
        resource_ids.emplace(rs_meta.resource_id());
4164
2.51k
    }
4165
4166
    // get restore job rowset in tablet
4167
247
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
4168
247
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
4169
247
    if (code != MetaServiceCode::OK) {
4170
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
4171
0
                .tag("tablet id", tablet_id)
4172
0
                .tag("msg", msg)
4173
0
                .tag("code", code)
4174
0
                .tag("instance id", instance_id_);
4175
0
        return -1;
4176
0
    }
4177
4178
247
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
4179
0
        if (!rs_meta.has_resource_id()) {
4180
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4181
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4182
0
                    .tag("instance_id", instance_id_)
4183
0
                    .tag("tablet_id", tablet_id);
4184
0
            return -1;
4185
0
        }
4186
4187
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4188
        // possible if the accessor is not initilized correctly
4189
0
        if (it == accessor_map_.end()) [[unlikely]] {
4190
0
            LOG_WARNING(
4191
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4192
0
                    "recycle process")
4193
0
                    .tag("tablet id", tablet_id)
4194
0
                    .tag("instance_id", instance_id_)
4195
0
                    .tag("resource_id", rs_meta.resource_id())
4196
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4197
0
            return -1;
4198
0
        }
4199
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4200
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
4201
0
                    .tag("instance_id", instance_id_)
4202
0
                    .tag("tablet_id", tablet_id)
4203
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4204
0
            return -1;
4205
0
        }
4206
0
        recycle_restore_job_rowsets_number += 1;
4207
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
4208
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
4209
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
4210
0
        resource_ids.emplace(rs_meta.resource_id());
4211
0
    }
4212
4213
247
    LOG_INFO("recycle tablet start to delete object")
4214
247
            .tag("instance id", instance_id_)
4215
247
            .tag("tablet id", tablet_id)
4216
247
            .tag("recycle tablet resource ids are",
4217
247
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
4218
247
                                 [](std::string rs_id, const auto& it) {
4219
206
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4220
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
4218
206
                                 [](std::string rs_id, const auto& it) {
4219
206
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4220
206
                                 }));
4221
4222
247
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
4223
247
            _thread_pool_group.s3_producer_pool,
4224
247
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4225
247
            [](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
4225
206
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
4226
4227
    // delete all rowset data in this tablet
4228
    // ATTN: there may be data leak if not all accessor initilized successfully
4229
    //       partial data deleted if the tablet is stored cross-storage vault
4230
    //       vault id is not attached to TabletMeta...
4231
247
    for (const auto& resource_id : resource_ids) {
4232
206
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
4233
206
        concurrent_delete_executor.add(
4234
206
                [&, rs_id = resource_id,
4235
206
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4236
206
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4237
206
                    if (res != 0) {
4238
2
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4239
2
                                     << " path=" << accessor_ptr->uri()
4240
2
                                     << " task type=" << metrics_context.operation_type;
4241
2
                        return std::make_pair(-1, rs_id);
4242
2
                    }
4243
204
                    return std::make_pair(0, rs_id);
4244
206
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
4235
206
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4236
206
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4237
206
                    if (res != 0) {
4238
2
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4239
2
                                     << " path=" << accessor_ptr->uri()
4240
2
                                     << " task type=" << metrics_context.operation_type;
4241
2
                        return std::make_pair(-1, rs_id);
4242
2
                    }
4243
204
                    return std::make_pair(0, rs_id);
4244
206
                });
4245
206
    }
4246
4247
247
    bool finished = true;
4248
247
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
4249
247
    for (auto& r : rets) {
4250
206
        if (r.first != 0) {
4251
2
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
4252
2
            ret = -1;
4253
2
        }
4254
206
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
4255
206
    }
4256
247
    ret = finished ? ret : -1;
4257
4258
247
    if (ret != 0) { // failed recycle tablet data
4259
2
        LOG_WARNING("ret!=0")
4260
2
                .tag("finished", finished)
4261
2
                .tag("ret", ret)
4262
2
                .tag("instance_id", instance_id_)
4263
2
                .tag("tablet_id", tablet_id);
4264
2
        return ret;
4265
2
    }
4266
4267
245
    tablet_metrics_context_.total_recycled_data_size +=
4268
245
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4269
245
    tablet_metrics_context_.total_recycled_num += 1;
4270
245
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
4271
245
    segment_metrics_context_.total_recycled_data_size +=
4272
245
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4273
245
    metrics_context.total_recycled_data_size +=
4274
245
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4275
245
    tablet_metrics_context_.report();
4276
245
    segment_metrics_context_.report();
4277
245
    metrics_context.report();
4278
4279
245
    txn.reset();
4280
245
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4281
0
        LOG_WARNING("failed to recycle tablet ")
4282
0
                .tag("tablet id", tablet_id)
4283
0
                .tag("instance_id", instance_id_)
4284
0
                .tag("reason", "failed to create txn");
4285
0
        ret = -1;
4286
0
    }
4287
    // delete all rowset kv in this tablet
4288
245
    txn->remove(rs_key0, rs_key1);
4289
245
    txn->remove(recyc_rs_key0, recyc_rs_key1);
4290
245
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
4291
4292
    // remove delete bitmap for MoW table
4293
245
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
4294
245
    txn->remove(pending_key);
4295
245
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
4296
245
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
4297
245
    txn->remove(delete_bitmap_start, delete_bitmap_end);
4298
4299
245
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
4300
245
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
4301
245
    txn->remove(dbm_start_key, dbm_end_key);
4302
245
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
4303
245
              << " end=" << hex(dbm_end_key);
4304
4305
245
    TxnErrorCode err = txn->commit();
4306
245
    if (err != TxnErrorCode::TXN_OK) {
4307
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
4308
0
        ret = -1;
4309
0
    }
4310
4311
245
    if (ret == 0) {
4312
        // All object files under tablet have been deleted
4313
244
        std::lock_guard lock(recycled_tablets_mtx_);
4314
244
        recycled_tablets_.insert(tablet_id);
4315
244
    }
4316
4317
245
    return ret;
4318
247
}
4319
4320
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
4321
11
                                               RecyclerMetricsContext& metrics_context) {
4322
11
    int ret = 0;
4323
11
    auto start_time = steady_clock::now();
4324
4325
11
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4326
4327
    // collect resource ids
4328
11
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4329
11
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4330
11
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4331
11
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4332
4333
11
    int64_t recycle_rowsets_number = 0;
4334
11
    int64_t recycle_segments_number = 0;
4335
11
    int64_t recycle_rowsets_data_size = 0;
4336
11
    int64_t recycle_rowsets_index_size = 0;
4337
11
    int64_t max_rowset_version = 0;
4338
11
    int64_t min_rowset_creation_time = INT64_MAX;
4339
11
    int64_t max_rowset_creation_time = 0;
4340
11
    int64_t min_rowset_expiration_time = INT64_MAX;
4341
11
    int64_t max_rowset_expiration_time = 0;
4342
4343
11
    DORIS_CLOUD_DEFER {
4344
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4345
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4346
11
                .tag("instance_id", instance_id_)
4347
11
                .tag("tablet_id", tablet_id)
4348
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4349
11
                .tag("recycle segments number", recycle_segments_number)
4350
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4351
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4352
11
                .tag("max rowset version", max_rowset_version)
4353
11
                .tag("min rowset creation time", min_rowset_creation_time)
4354
11
                .tag("max rowset creation time", max_rowset_creation_time)
4355
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4356
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4357
11
                .tag("ret", ret);
4358
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4343
11
    DORIS_CLOUD_DEFER {
4344
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4345
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4346
11
                .tag("instance_id", instance_id_)
4347
11
                .tag("tablet_id", tablet_id)
4348
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4349
11
                .tag("recycle segments number", recycle_segments_number)
4350
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4351
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4352
11
                .tag("max rowset version", max_rowset_version)
4353
11
                .tag("min rowset creation time", min_rowset_creation_time)
4354
11
                .tag("max rowset creation time", max_rowset_creation_time)
4355
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4356
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4357
11
                .tag("ret", ret);
4358
11
    };
4359
4360
11
    std::unique_ptr<Transaction> txn;
4361
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4362
0
        LOG_WARNING("failed to recycle tablet ")
4363
0
                .tag("tablet id", tablet_id)
4364
0
                .tag("instance_id", instance_id_)
4365
0
                .tag("reason", "failed to create txn");
4366
0
        ret = -1;
4367
0
    }
4368
4369
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
4370
    // by the related operation logs.
4371
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
4372
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
4373
11
    MetaReader meta_reader(instance_id_);
4374
11
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
4375
11
    if (err == TxnErrorCode::TXN_OK) {
4376
11
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
4377
11
    }
4378
11
    if (err != TxnErrorCode::TXN_OK) {
4379
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4380
0
                .tag("tablet id", tablet_id)
4381
0
                .tag("err", err)
4382
0
                .tag("instance id", instance_id_);
4383
0
        ret = -1;
4384
0
    }
4385
4386
11
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
4387
11
             load_rowset_metas.size(), compact_rowset_metas.size())
4388
11
            .tag("instance_id", instance_id_)
4389
11
            .tag("tablet_id", tablet_id);
4390
4391
11
    SyncExecutor<int> concurrent_delete_executor(
4392
11
            _thread_pool_group.s3_producer_pool,
4393
11
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4394
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
4395
4396
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
4397
60
        recycle_rowsets_number += 1;
4398
60
        recycle_segments_number += rs_meta.num_segments();
4399
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4400
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4401
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4402
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4403
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4404
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4405
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4406
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
4396
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
4397
60
        recycle_rowsets_number += 1;
4398
60
        recycle_segments_number += rs_meta.num_segments();
4399
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4400
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4401
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4402
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4403
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4404
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4405
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4406
60
    };
4407
4408
11
    std::vector<RowsetDeleteTask> all_tasks;
4409
4410
11
    auto create_delete_task = [this](const RowsetMetaCloudPB& rs_meta, std::string_view recycle_key,
4411
11
                                     std::string_view non_versioned_rowset_key =
4412
60
                                             "") -> RowsetDeleteTask {
4413
60
        RowsetDeleteTask task;
4414
60
        task.rowset_meta = rs_meta;
4415
60
        task.recycle_rowset_key = std::string(recycle_key);
4416
60
        task.non_versioned_rowset_key = std::string(non_versioned_rowset_key);
4417
60
        task.versioned_rowset_key = versioned::meta_rowset_key(
4418
60
                {instance_id_, rs_meta.tablet_id(), rs_meta.rowset_id_v2()});
4419
60
        return task;
4420
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clERKNS_17RowsetMetaCloudPBESt17basic_string_viewIcSt11char_traitsIcEESB_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clERKNS_17RowsetMetaCloudPBESt17basic_string_viewIcSt11char_traitsIcEESB_
Line
Count
Source
4412
60
                                             "") -> RowsetDeleteTask {
4413
60
        RowsetDeleteTask task;
4414
60
        task.rowset_meta = rs_meta;
4415
60
        task.recycle_rowset_key = std::string(recycle_key);
4416
60
        task.non_versioned_rowset_key = std::string(non_versioned_rowset_key);
4417
60
        task.versioned_rowset_key = versioned::meta_rowset_key(
4418
60
                {instance_id_, rs_meta.tablet_id(), rs_meta.rowset_id_v2()});
4419
60
        return task;
4420
60
    };
4421
4422
60
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
4423
60
        update_rowset_stats(rs_meta);
4424
        // Version 0-1 rowset has no resource_id and no actual data files,
4425
        // but still needs ref_count key cleanup, so we add it to all_tasks.
4426
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
4427
60
        std::string rowset_load_key =
4428
60
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
4429
60
        std::string rowset_key = meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
4430
60
        RowsetDeleteTask task = create_delete_task(
4431
60
                rs_meta, encode_versioned_key(rowset_load_key, versionstamp), rowset_key);
4432
60
        all_tasks.push_back(std::move(task));
4433
60
    }
4434
4435
11
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
4436
0
        update_rowset_stats(rs_meta);
4437
        // Version 0-1 rowset has no resource_id and no actual data files,
4438
        // but still needs ref_count key cleanup, so we add it to all_tasks.
4439
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
4440
0
        std::string rowset_compact_key = versioned::meta_rowset_compact_key(
4441
0
                {instance_id_, tablet_id, rs_meta.end_version()});
4442
0
        std::string rowset_key = meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
4443
0
        RowsetDeleteTask task = create_delete_task(
4444
0
                rs_meta, encode_versioned_key(rowset_compact_key, versionstamp), rowset_key);
4445
0
        all_tasks.push_back(std::move(task));
4446
0
    }
4447
4448
11
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
4449
0
        RecycleRowsetPB recycle_rowset;
4450
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
4451
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4452
0
            return -1;
4453
0
        }
4454
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
4455
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
4456
                // in old version, keep this key-value pair and it needs to be checked manually
4457
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4458
0
                return -1;
4459
0
            }
4460
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
4461
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
4462
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
4463
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
4464
0
                return -1;
4465
0
            }
4466
            // decode rowset_id
4467
0
            auto k1 = k;
4468
0
            k1.remove_prefix(1);
4469
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
4470
0
            decode_key(&k1, &out);
4471
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
4472
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
4473
0
            LOG_INFO("delete old-version rowset data")
4474
0
                    .tag("instance_id", instance_id_)
4475
0
                    .tag("tablet_id", tablet_id)
4476
0
                    .tag("rowset_id", rowset_id);
4477
4478
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
4479
            // so we must use prefix deletion directly instead of batch delete.
4480
0
            concurrent_delete_executor.add(
4481
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
4482
                        // delete by prefix, the recycle rowset key will be deleted by range later.
4483
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
4484
0
                    });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Unexecuted instantiation: recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
4485
0
        } else {
4486
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
4487
            // Version 0-1 rowset has no resource_id and no actual data files,
4488
            // but still needs ref_count key cleanup, so we add it to all_tasks.
4489
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
4490
0
            RowsetDeleteTask task = create_delete_task(rowset_meta, k);
4491
0
            all_tasks.push_back(std::move(task));
4492
0
        }
4493
0
        return 0;
4494
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clESt17basic_string_viewIcSt11char_traitsIcEES8_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clESt17basic_string_viewIcSt11char_traitsIcEES8_
4495
4496
11
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
4497
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
4498
0
                .tag("tablet id", tablet_id)
4499
0
                .tag("instance_id", instance_id_)
4500
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
4501
0
        ret = -1;
4502
0
    }
4503
4504
    // Phase 1: Classify tasks by ref_count
4505
11
    std::vector<RowsetDeleteTask> batch_delete_tasks;
4506
60
    for (auto& task : all_tasks) {
4507
60
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
4508
60
        if (classify_ret < 0) {
4509
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
4510
0
                    .tag("instance_id", instance_id_)
4511
0
                    .tag("tablet_id", tablet_id)
4512
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
4513
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
4514
0
                return recycle_rowset_meta_and_data(t.recycle_rowset_key, t.rowset_meta,
4515
0
                                                    t.non_versioned_rowset_key);
4516
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_5clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_5clEv
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
805
                    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
805
                    std::vector<std::string> keys;
4751
805
                    {
4752
805
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4753
805
                        async_recycled_rowset_keys.push_back(std::move(key));
4754
805
                        if (async_recycled_rowset_keys.size() > 100) {
4755
7
                            keys.swap(async_recycled_rowset_keys);
4756
7
                        }
4757
805
                    }
4758
805
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4759
805
                    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
803
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4746
803
                    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
803
                    std::vector<std::string> keys;
4751
803
                    {
4752
803
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4753
803
                        async_recycled_rowset_keys.push_back(std::move(key));
4754
803
                        if (async_recycled_rowset_keys.size() > 100) {
4755
7
                            keys.swap(async_recycled_rowset_keys);
4756
7
                        }
4757
803
                    }
4758
803
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4759
803
                    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
97
        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
97
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
4777
0
            return -1;
4778
0
        }
4779
97
        rowset_keys.push_back(std::move(key));
4780
97
        return 0;
4781
97
    };
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
97
        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
97
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
4777
0
            return -1;
4778
0
        }
4779
97
        rowset_keys.push_back(std::move(key));
4780
97
        return 0;
4781
97
    };
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
9
int InstanceRecycler::recycle_versioned_rowsets() {
5160
9
    const std::string task_name = "recycle_rowsets";
5161
9
    int64_t num_scanned = 0;
5162
9
    int64_t num_expired = 0;
5163
9
    int64_t num_prepare = 0;
5164
9
    int64_t num_compacted = 0;
5165
9
    int64_t num_empty_rowset = 0;
5166
9
    size_t total_rowset_key_size = 0;
5167
9
    size_t total_rowset_value_size = 0;
5168
9
    size_t expired_rowset_size = 0;
5169
9
    std::atomic_long num_recycled = 0;
5170
9
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5171
5172
9
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5173
9
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5174
9
    std::string recyc_rs_key0;
5175
9
    std::string recyc_rs_key1;
5176
9
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5177
9
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5178
5179
9
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5180
5181
9
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5182
9
    register_recycle_task(task_name, start_time);
5183
5184
9
    DORIS_CLOUD_DEFER {
5185
9
        unregister_recycle_task(task_name);
5186
9
        int64_t cost =
5187
9
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5188
9
        metrics_context.finish_report();
5189
9
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5190
9
                .tag("instance_id", instance_id_)
5191
9
                .tag("num_scanned", num_scanned)
5192
9
                .tag("num_expired", num_expired)
5193
9
                .tag("num_recycled", num_recycled)
5194
9
                .tag("num_recycled.prepare", num_prepare)
5195
9
                .tag("num_recycled.compacted", num_compacted)
5196
9
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5197
9
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5198
9
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5199
9
                .tag("expired_rowset_meta_size", expired_rowset_size);
5200
9
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
5184
9
    DORIS_CLOUD_DEFER {
5185
9
        unregister_recycle_task(task_name);
5186
9
        int64_t cost =
5187
9
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5188
9
        metrics_context.finish_report();
5189
9
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5190
9
                .tag("instance_id", instance_id_)
5191
9
                .tag("num_scanned", num_scanned)
5192
9
                .tag("num_expired", num_expired)
5193
9
                .tag("num_recycled", num_recycled)
5194
9
                .tag("num_recycled.prepare", num_prepare)
5195
9
                .tag("num_recycled.compacted", num_compacted)
5196
9
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5197
9
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5198
9
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5199
9
                .tag("expired_rowset_meta_size", expired_rowset_size);
5200
9
    };
5201
5202
9
    std::vector<std::string> orphan_rowset_keys;
5203
5204
    // Store keys of rowset recycled by background workers
5205
9
    std::mutex async_recycled_rowset_keys_mutex;
5206
9
    std::vector<std::string> async_recycled_rowset_keys;
5207
9
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5208
9
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5209
9
    worker_pool->start();
5210
9
    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
9
    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
1.61k
                        if (recycle_rowset_meta_and_data(k, rowset_meta) != 0) {
5333
1.60k
                            return;
5334
1.60k
                        }
5335
13
                        num_compacted += is_compacted;
5336
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5337
13
                        if (rowset_meta.num_segments() == 0) {
5338
0
                            ++num_empty_rowset;
5339
0
                        }
5340
13
                    });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlvE_clEv
Line
Count
Source
5331
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5332
1.61k
                        if (recycle_rowset_meta_and_data(k, rowset_meta) != 0) {
5333
1.60k
                            return;
5334
1.60k
                        }
5335
13
                        num_compacted += is_compacted;
5336
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5337
13
                        if (rowset_meta.num_segments() == 0) {
5338
0
                            ++num_empty_rowset;
5339
0
                        }
5340
13
                    });
5341
1.61k
        }
5342
2.01k
        return 0;
5343
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
1.61k
                        if (recycle_rowset_meta_and_data(k, rowset_meta) != 0) {
5333
1.61k
                            return;
5334
1.61k
                        }
5335
1.61k
                        num_compacted += is_compacted;
5336
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5337
1.61k
                        if (rowset_meta.num_segments() == 0) {
5338
1.61k
                            ++num_empty_rowset;
5339
1.61k
                        }
5340
1.61k
                    });
5341
1.61k
        }
5342
2.01k
        return 0;
5343
2.01k
    };
5344
5345
9
    if (config::enable_recycler_stats_metrics) {
5346
0
        scan_and_statistics_rowsets();
5347
0
    }
5348
5349
9
    auto loop_done = [&]() -> int {
5350
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
5351
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5352
0
        }
5353
6
        orphan_rowset_keys.clear();
5354
6
        return 0;
5355
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
Line
Count
Source
5349
6
    auto loop_done = [&]() -> int {
5350
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
5351
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5352
0
        }
5353
6
        orphan_rowset_keys.clear();
5354
6
        return 0;
5355
6
    };
5356
5357
    // recycle_func and loop_done for scan and recycle
5358
9
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
5359
9
                               std::move(loop_done));
5360
5361
9
    worker_pool->stop();
5362
5363
9
    if (!async_recycled_rowset_keys.empty()) {
5364
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5365
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5366
0
            return -1;
5367
0
        } else {
5368
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5369
0
        }
5370
0
    }
5371
5372
    // Report final metrics after all concurrent tasks completed
5373
9
    segment_metrics_context_.report();
5374
9
    metrics_context.report();
5375
5376
9
    return ret;
5377
9
}
5378
5379
int InstanceRecycler::recycle_rowset_meta_and_data(std::string_view recycle_rowset_key,
5380
                                                   const RowsetMetaCloudPB& rowset_meta,
5381
1.61k
                                                   std::string_view non_versioned_rowset_key) {
5382
1.61k
    constexpr int MAX_RETRY = 10;
5383
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
5384
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
5385
1.61k
    std::string_view reference_instance_id = instance_id_;
5386
1.61k
    if (rowset_meta.has_reference_instance_id()) {
5387
8
        reference_instance_id = rowset_meta.reference_instance_id();
5388
8
    }
5389
5390
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
5391
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
5392
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(recycle_rowset_key));
5393
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
5394
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
5395
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
5396
1.61k
        std::unique_ptr<Transaction> txn;
5397
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5398
1.61k
        if (err != TxnErrorCode::TXN_OK) {
5399
0
            LOG_WARNING("failed to create txn").tag("err", err);
5400
0
            return -1;
5401
0
        }
5402
5403
1.61k
        std::string rowset_ref_count_key =
5404
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
5405
1.61k
        int64_t ref_count = 0;
5406
1.61k
        {
5407
1.61k
            std::string value;
5408
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
5409
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
5410
                // This is the old version rowset, we could recycle it directly.
5411
1.60k
                ref_count = 1;
5412
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
5413
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
5414
0
                return -1;
5415
11
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
5416
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
5417
0
                return -1;
5418
0
            }
5419
1.61k
        }
5420
5421
1.61k
        if (ref_count == 1) {
5422
            // It would not be added since it is recycling.
5423
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
5424
1.60k
                LOG_WARNING("failed to delete rowset data");
5425
1.60k
                return -1;
5426
1.60k
            }
5427
5428
            // Reset the transaction to avoid timeout.
5429
10
            err = txn_kv_->create_txn(&txn);
5430
10
            if (err != TxnErrorCode::TXN_OK) {
5431
0
                LOG_WARNING("failed to create txn").tag("err", err);
5432
0
                return -1;
5433
0
            }
5434
10
            txn->remove(rowset_ref_count_key);
5435
10
            LOG_INFO("delete rowset data ref count key")
5436
10
                    .tag("txn_id", rowset_meta.txn_id())
5437
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
5438
5439
10
            std::string dbm_start_key =
5440
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
5441
10
            std::string dbm_end_key = meta_delete_bitmap_key(
5442
10
                    {reference_instance_id, tablet_id, rowset_id,
5443
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
5444
10
            txn->remove(dbm_start_key, dbm_end_key);
5445
10
            LOG_INFO("remove delete bitmap kv")
5446
10
                    .tag("begin", hex(dbm_start_key))
5447
10
                    .tag("end", hex(dbm_end_key));
5448
5449
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
5450
10
                    {reference_instance_id, tablet_id, rowset_id});
5451
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
5452
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
5453
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
5454
10
            LOG_INFO("remove versioned delete bitmap kv")
5455
10
                    .tag("begin", hex(versioned_dbm_start_key))
5456
10
                    .tag("end", hex(versioned_dbm_end_key));
5457
5458
10
            std::string meta_rowset_key_begin =
5459
10
                    versioned::meta_rowset_key({reference_instance_id, tablet_id, rowset_id});
5460
10
            std::string meta_rowset_key_end = meta_rowset_key_begin;
5461
10
            encode_int64(INT64_MAX, &meta_rowset_key_end);
5462
10
            txn->remove(meta_rowset_key_begin, meta_rowset_key_end);
5463
10
            LOG_INFO("remove meta rowset key").tag("key", hex(meta_rowset_key_begin));
5464
10
        } else {
5465
            // Decrease the rowset ref count.
5466
            //
5467
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
5468
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
5469
3
            txn->atomic_add(rowset_ref_count_key, -1);
5470
3
            LOG_INFO("decrease rowset data ref count")
5471
3
                    .tag("txn_id", rowset_meta.txn_id())
5472
3
                    .tag("ref_count", ref_count - 1)
5473
3
                    .tag("ref_count_key", hex(rowset_ref_count_key));
5474
3
        }
5475
5476
13
        if (!recycle_rowset_key.empty()) { // empty when recycle ref rowsets for deleted instance
5477
13
            txn->remove(recycle_rowset_key);
5478
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(recycle_rowset_key));
5479
13
        }
5480
13
        if (!non_versioned_rowset_key.empty()) {
5481
0
            txn->remove(non_versioned_rowset_key);
5482
0
            LOG_INFO("remove non versioned rowset key").tag("key", hex(non_versioned_rowset_key));
5483
0
        }
5484
5485
13
        err = txn->commit();
5486
13
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
5487
            // The rowset ref count key has been changed, we need to retry.
5488
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
5489
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
5490
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
5491
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
5492
0
            continue;
5493
13
        } else if (err != TxnErrorCode::TXN_OK) {
5494
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
5495
0
            return -1;
5496
0
        }
5497
13
        LOG_INFO("recycle rowset meta and data success");
5498
13
        return 0;
5499
13
    }
5500
0
    LOG_WARNING("failed to recycle rowset meta and data after retry")
5501
0
            .tag("tablet_id", tablet_id)
5502
0
            .tag("rowset_id", rowset_id)
5503
0
            .tag("retry", MAX_RETRY);
5504
0
    return -1;
5505
1.61k
}
5506
5507
29
int InstanceRecycler::recycle_tmp_rowsets() {
5508
29
    const std::string task_name = "recycle_tmp_rowsets";
5509
29
    int64_t num_scanned = 0;
5510
29
    int64_t num_expired = 0;
5511
29
    std::atomic_long num_recycled = 0;
5512
29
    size_t expired_rowset_size = 0;
5513
29
    size_t total_rowset_key_size = 0;
5514
29
    size_t total_rowset_value_size = 0;
5515
29
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5516
5517
29
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
5518
29
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
5519
29
    std::string tmp_rs_key0;
5520
29
    std::string tmp_rs_key1;
5521
29
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
5522
29
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
5523
5524
29
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
5525
5526
29
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5527
29
    register_recycle_task(task_name, start_time);
5528
5529
29
    DORIS_CLOUD_DEFER {
5530
29
        unregister_recycle_task(task_name);
5531
29
        int64_t cost =
5532
29
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5533
29
        metrics_context.finish_report();
5534
29
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5535
29
                .tag("instance_id", instance_id_)
5536
29
                .tag("num_scanned", num_scanned)
5537
29
                .tag("num_expired", num_expired)
5538
29
                .tag("num_recycled", num_recycled)
5539
29
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5540
29
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5541
29
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5542
29
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
5529
12
    DORIS_CLOUD_DEFER {
5530
12
        unregister_recycle_task(task_name);
5531
12
        int64_t cost =
5532
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5533
12
        metrics_context.finish_report();
5534
12
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5535
12
                .tag("instance_id", instance_id_)
5536
12
                .tag("num_scanned", num_scanned)
5537
12
                .tag("num_expired", num_expired)
5538
12
                .tag("num_recycled", num_recycled)
5539
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5540
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5541
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5542
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
5529
17
    DORIS_CLOUD_DEFER {
5530
17
        unregister_recycle_task(task_name);
5531
17
        int64_t cost =
5532
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5533
17
        metrics_context.finish_report();
5534
17
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5535
17
                .tag("instance_id", instance_id_)
5536
17
                .tag("num_scanned", num_scanned)
5537
17
                .tag("num_expired", num_expired)
5538
17
                .tag("num_recycled", num_recycled)
5539
17
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5540
17
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5541
17
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5542
17
    };
5543
5544
    // Elements in `tmp_rowset_keys` has the same lifetime as `it`
5545
5546
29
    std::vector<std::string> tmp_rowset_keys;
5547
29
    std::vector<std::string> tmp_rowset_ref_count_keys;
5548
5549
    // rowset_id -> rowset_meta
5550
    // store tmp_rowset id and meta for statistics rs size when delete
5551
29
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
5552
29
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5553
29
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
5554
29
    worker_pool->start();
5555
5556
29
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5557
5558
29
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &tmp_rowsets,
5559
29
                             &expired_rowset_size, &total_rowset_key_size, &total_rowset_value_size,
5560
29
                             &earlest_ts, &tmp_rowset_ref_count_keys, this,
5561
102k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5562
102k
        ++num_scanned;
5563
102k
        total_rowset_key_size += k.size();
5564
102k
        total_rowset_value_size += v.size();
5565
102k
        doris::RowsetMetaCloudPB rowset;
5566
102k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5567
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5568
0
            return -1;
5569
0
        }
5570
102k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5571
102k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5572
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5573
0
                   << " txn_expiration=" << rowset.txn_expiration()
5574
0
                   << " rowset_creation_time=" << rowset.creation_time();
5575
102k
        int64_t current_time = ::time(nullptr);
5576
102k
        if (current_time < expiration) { // not expired
5577
0
            return 0;
5578
0
        }
5579
5580
102k
        if (config::enable_mark_delete_rowset_before_recycle) {
5581
102k
            int mark_ret = mark_rowset_as_recycled(txn_kv_.get(), instance_id_, k, rowset);
5582
102k
            if (mark_ret == -1) {
5583
0
                LOG(WARNING) << "failed to mark rowset as recycled, instance_id=" << instance_id_
5584
0
                             << " tablet_id=" << rowset.tablet_id() << " version=["
5585
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5586
0
                return -1;
5587
102k
            } else if (mark_ret == 1) {
5588
51.0k
                LOG(INFO)
5589
51.0k
                        << "rowset already marked as recycled, recycler will delete data and kv at "
5590
51.0k
                           "next turn, instance_id="
5591
51.0k
                        << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5592
51.0k
                        << rowset.start_version() << '-' << rowset.end_version() << "]";
5593
51.0k
                return 0;
5594
51.0k
            }
5595
102k
        }
5596
5597
51.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
5598
51.0k
            LOG(INFO) << "begin to abort txn or job for related rowset, instance_id="
5599
51.0k
                      << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5600
51.0k
                      << rowset.start_version() << '-' << rowset.end_version() << "]";
5601
5602
51.0k
            int ret = abort_txn_or_job_for_recycle(rowset);
5603
51.0k
            if (ret != 0) {
5604
0
                LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
5605
0
                             << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5606
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5607
0
                return ret;
5608
0
            }
5609
51.0k
        }
5610
5611
51.0k
        ++num_expired;
5612
51.0k
        expired_rowset_size += v.size();
5613
51.0k
        if (!rowset.has_resource_id()) {
5614
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
5615
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
5616
0
                return -1;
5617
0
            }
5618
            // might be a delete pred rowset
5619
0
            tmp_rowset_keys.emplace_back(k);
5620
0
            return 0;
5621
0
        }
5622
        // TODO(plat1ko): check rowset not referenced
5623
51.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5624
51.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
5625
51.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
5626
51.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
5627
51.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
5628
51.0k
                  << " num_expired=" << num_expired
5629
51.0k
                  << " task_type=" << metrics_context.operation_type;
5630
5631
51.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
5632
        // Remove the rowset ref count key directly since it has not been used.
5633
51.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
5634
51.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
5635
51.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
5636
51.0k
                  << "key=" << hex(rowset_ref_count_key);
5637
51.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
5638
5639
51.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
5640
51.0k
        return 0;
5641
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5561
16
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5562
16
        ++num_scanned;
5563
16
        total_rowset_key_size += k.size();
5564
16
        total_rowset_value_size += v.size();
5565
16
        doris::RowsetMetaCloudPB rowset;
5566
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5567
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5568
0
            return -1;
5569
0
        }
5570
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5571
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5572
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5573
0
                   << " txn_expiration=" << rowset.txn_expiration()
5574
0
                   << " rowset_creation_time=" << rowset.creation_time();
5575
16
        int64_t current_time = ::time(nullptr);
5576
16
        if (current_time < expiration) { // not expired
5577
0
            return 0;
5578
0
        }
5579
5580
16
        if (config::enable_mark_delete_rowset_before_recycle) {
5581
16
            int mark_ret = mark_rowset_as_recycled(txn_kv_.get(), instance_id_, k, rowset);
5582
16
            if (mark_ret == -1) {
5583
0
                LOG(WARNING) << "failed to mark rowset as recycled, instance_id=" << instance_id_
5584
0
                             << " tablet_id=" << rowset.tablet_id() << " version=["
5585
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5586
0
                return -1;
5587
16
            } else if (mark_ret == 1) {
5588
9
                LOG(INFO)
5589
9
                        << "rowset already marked as recycled, recycler will delete data and kv at "
5590
9
                           "next turn, instance_id="
5591
9
                        << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5592
9
                        << rowset.start_version() << '-' << rowset.end_version() << "]";
5593
9
                return 0;
5594
9
            }
5595
16
        }
5596
5597
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
5598
7
            LOG(INFO) << "begin to abort txn or job for related rowset, instance_id="
5599
7
                      << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5600
7
                      << rowset.start_version() << '-' << rowset.end_version() << "]";
5601
5602
7
            int ret = abort_txn_or_job_for_recycle(rowset);
5603
7
            if (ret != 0) {
5604
0
                LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
5605
0
                             << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5606
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5607
0
                return ret;
5608
0
            }
5609
7
        }
5610
5611
7
        ++num_expired;
5612
7
        expired_rowset_size += v.size();
5613
7
        if (!rowset.has_resource_id()) {
5614
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
5615
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
5616
0
                return -1;
5617
0
            }
5618
            // might be a delete pred rowset
5619
0
            tmp_rowset_keys.emplace_back(k);
5620
0
            return 0;
5621
0
        }
5622
        // TODO(plat1ko): check rowset not referenced
5623
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5624
7
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
5625
7
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
5626
7
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
5627
7
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
5628
7
                  << " num_expired=" << num_expired
5629
7
                  << " task_type=" << metrics_context.operation_type;
5630
5631
7
        tmp_rowset_keys.emplace_back(k.data(), k.size());
5632
        // Remove the rowset ref count key directly since it has not been used.
5633
7
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
5634
7
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
5635
7
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
5636
7
                  << "key=" << hex(rowset_ref_count_key);
5637
7
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
5638
5639
7
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
5640
7
        return 0;
5641
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5561
102k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5562
102k
        ++num_scanned;
5563
102k
        total_rowset_key_size += k.size();
5564
102k
        total_rowset_value_size += v.size();
5565
102k
        doris::RowsetMetaCloudPB rowset;
5566
102k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5567
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5568
0
            return -1;
5569
0
        }
5570
102k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5571
102k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5572
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5573
0
                   << " txn_expiration=" << rowset.txn_expiration()
5574
0
                   << " rowset_creation_time=" << rowset.creation_time();
5575
102k
        int64_t current_time = ::time(nullptr);
5576
102k
        if (current_time < expiration) { // not expired
5577
0
            return 0;
5578
0
        }
5579
5580
102k
        if (config::enable_mark_delete_rowset_before_recycle) {
5581
102k
            int mark_ret = mark_rowset_as_recycled(txn_kv_.get(), instance_id_, k, rowset);
5582
102k
            if (mark_ret == -1) {
5583
0
                LOG(WARNING) << "failed to mark rowset as recycled, instance_id=" << instance_id_
5584
0
                             << " tablet_id=" << rowset.tablet_id() << " version=["
5585
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5586
0
                return -1;
5587
102k
            } else if (mark_ret == 1) {
5588
51.0k
                LOG(INFO)
5589
51.0k
                        << "rowset already marked as recycled, recycler will delete data and kv at "
5590
51.0k
                           "next turn, instance_id="
5591
51.0k
                        << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5592
51.0k
                        << rowset.start_version() << '-' << rowset.end_version() << "]";
5593
51.0k
                return 0;
5594
51.0k
            }
5595
102k
        }
5596
5597
51.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
5598
51.0k
            LOG(INFO) << "begin to abort txn or job for related rowset, instance_id="
5599
51.0k
                      << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5600
51.0k
                      << rowset.start_version() << '-' << rowset.end_version() << "]";
5601
5602
51.0k
            int ret = abort_txn_or_job_for_recycle(rowset);
5603
51.0k
            if (ret != 0) {
5604
0
                LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
5605
0
                             << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5606
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5607
0
                return ret;
5608
0
            }
5609
51.0k
        }
5610
5611
51.0k
        ++num_expired;
5612
51.0k
        expired_rowset_size += v.size();
5613
51.0k
        if (!rowset.has_resource_id()) {
5614
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
5615
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
5616
0
                return -1;
5617
0
            }
5618
            // might be a delete pred rowset
5619
0
            tmp_rowset_keys.emplace_back(k);
5620
0
            return 0;
5621
0
        }
5622
        // TODO(plat1ko): check rowset not referenced
5623
51.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5624
51.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
5625
51.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
5626
51.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
5627
51.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
5628
51.0k
                  << " num_expired=" << num_expired
5629
51.0k
                  << " task_type=" << metrics_context.operation_type;
5630
5631
51.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
5632
        // Remove the rowset ref count key directly since it has not been used.
5633
51.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
5634
51.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
5635
51.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
5636
51.0k
                  << "key=" << hex(rowset_ref_count_key);
5637
51.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
5638
5639
51.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
5640
51.0k
        return 0;
5641
51.0k
    };
5642
5643
    // TODO bacth delete
5644
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5645
51.0k
        std::string dbm_start_key =
5646
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5647
51.0k
        std::string dbm_end_key = dbm_start_key;
5648
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
5649
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5650
51.0k
        if (ret != 0) {
5651
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5652
0
                         << instance_id_ << ", tablet_id=" << tablet_id
5653
0
                         << ", rowset_id=" << rowset_id;
5654
0
        }
5655
51.0k
        return ret;
5656
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5644
7
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5645
7
        std::string dbm_start_key =
5646
7
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5647
7
        std::string dbm_end_key = dbm_start_key;
5648
7
        encode_int64(INT64_MAX, &dbm_end_key);
5649
7
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5650
7
        if (ret != 0) {
5651
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5652
0
                         << instance_id_ << ", tablet_id=" << tablet_id
5653
0
                         << ", rowset_id=" << rowset_id;
5654
0
        }
5655
7
        return ret;
5656
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5644
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5645
51.0k
        std::string dbm_start_key =
5646
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5647
51.0k
        std::string dbm_end_key = dbm_start_key;
5648
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
5649
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5650
51.0k
        if (ret != 0) {
5651
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5652
0
                         << instance_id_ << ", tablet_id=" << tablet_id
5653
0
                         << ", rowset_id=" << rowset_id;
5654
0
        }
5655
51.0k
        return ret;
5656
51.0k
    };
5657
5658
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5659
51.0k
        auto delete_bitmap_start =
5660
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
5661
51.0k
        auto delete_bitmap_end =
5662
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
5663
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
5664
51.0k
        if (ret != 0) {
5665
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
5666
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
5667
0
        }
5668
51.0k
        return ret;
5669
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5658
7
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5659
7
        auto delete_bitmap_start =
5660
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
5661
7
        auto delete_bitmap_end =
5662
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
5663
7
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
5664
7
        if (ret != 0) {
5665
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
5666
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
5667
0
        }
5668
7
        return ret;
5669
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5658
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5659
51.0k
        auto delete_bitmap_start =
5660
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
5661
51.0k
        auto delete_bitmap_end =
5662
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
5663
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
5664
51.0k
        if (ret != 0) {
5665
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
5666
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
5667
0
        }
5668
51.0k
        return ret;
5669
51.0k
    };
5670
5671
29
    auto loop_done = [&]() -> int {
5672
26
        DORIS_CLOUD_DEFER {
5673
26
            tmp_rowset_keys.clear();
5674
26
            tmp_rowsets.clear();
5675
26
            tmp_rowset_ref_count_keys.clear();
5676
26
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5672
12
        DORIS_CLOUD_DEFER {
5673
12
            tmp_rowset_keys.clear();
5674
12
            tmp_rowsets.clear();
5675
12
            tmp_rowset_ref_count_keys.clear();
5676
12
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5672
14
        DORIS_CLOUD_DEFER {
5673
14
            tmp_rowset_keys.clear();
5674
14
            tmp_rowsets.clear();
5675
14
            tmp_rowset_ref_count_keys.clear();
5676
14
        };
5677
26
        worker_pool->submit([&, tmp_rowset_keys_to_delete = tmp_rowset_keys,
5678
26
                             tmp_rowsets_to_delete = tmp_rowsets,
5679
26
                             tmp_rowset_ref_count_keys_to_delete = tmp_rowset_ref_count_keys]() {
5680
26
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5681
26
                                   metrics_context) != 0) {
5682
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5683
0
                return;
5684
0
            }
5685
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5686
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5687
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5688
0
                                 << rs.ShortDebugString();
5689
0
                    return;
5690
0
                }
5691
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5692
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5693
0
                                 << rs.ShortDebugString();
5694
0
                    return;
5695
0
                }
5696
51.0k
            }
5697
26
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5698
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5699
0
                return;
5700
0
            }
5701
26
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5702
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5703
0
                return;
5704
0
            }
5705
26
            num_recycled += tmp_rowset_keys.size();
5706
26
            return;
5707
26
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
5679
12
                             tmp_rowset_ref_count_keys_to_delete = tmp_rowset_ref_count_keys]() {
5680
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5681
12
                                   metrics_context) != 0) {
5682
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5683
0
                return;
5684
0
            }
5685
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5686
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5687
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5688
0
                                 << rs.ShortDebugString();
5689
0
                    return;
5690
0
                }
5691
7
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5692
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5693
0
                                 << rs.ShortDebugString();
5694
0
                    return;
5695
0
                }
5696
7
            }
5697
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5698
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5699
0
                return;
5700
0
            }
5701
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5702
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5703
0
                return;
5704
0
            }
5705
12
            num_recycled += tmp_rowset_keys.size();
5706
12
            return;
5707
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
5679
14
                             tmp_rowset_ref_count_keys_to_delete = tmp_rowset_ref_count_keys]() {
5680
14
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5681
14
                                   metrics_context) != 0) {
5682
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5683
0
                return;
5684
0
            }
5685
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5686
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5687
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5688
0
                                 << rs.ShortDebugString();
5689
0
                    return;
5690
0
                }
5691
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5692
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5693
0
                                 << rs.ShortDebugString();
5694
0
                    return;
5695
0
                }
5696
51.0k
            }
5697
14
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5698
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5699
0
                return;
5700
0
            }
5701
14
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5702
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5703
0
                return;
5704
0
            }
5705
14
            num_recycled += tmp_rowset_keys.size();
5706
14
            return;
5707
14
        });
5708
26
        return 0;
5709
26
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
5671
12
    auto loop_done = [&]() -> int {
5672
12
        DORIS_CLOUD_DEFER {
5673
12
            tmp_rowset_keys.clear();
5674
12
            tmp_rowsets.clear();
5675
12
            tmp_rowset_ref_count_keys.clear();
5676
12
        };
5677
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = tmp_rowset_keys,
5678
12
                             tmp_rowsets_to_delete = tmp_rowsets,
5679
12
                             tmp_rowset_ref_count_keys_to_delete = tmp_rowset_ref_count_keys]() {
5680
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5681
12
                                   metrics_context) != 0) {
5682
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5683
12
                return;
5684
12
            }
5685
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5686
12
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5687
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5688
12
                                 << rs.ShortDebugString();
5689
12
                    return;
5690
12
                }
5691
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5692
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5693
12
                                 << rs.ShortDebugString();
5694
12
                    return;
5695
12
                }
5696
12
            }
5697
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5698
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5699
12
                return;
5700
12
            }
5701
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5702
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5703
12
                return;
5704
12
            }
5705
12
            num_recycled += tmp_rowset_keys.size();
5706
12
            return;
5707
12
        });
5708
12
        return 0;
5709
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
5671
14
    auto loop_done = [&]() -> int {
5672
14
        DORIS_CLOUD_DEFER {
5673
14
            tmp_rowset_keys.clear();
5674
14
            tmp_rowsets.clear();
5675
14
            tmp_rowset_ref_count_keys.clear();
5676
14
        };
5677
14
        worker_pool->submit([&, tmp_rowset_keys_to_delete = tmp_rowset_keys,
5678
14
                             tmp_rowsets_to_delete = tmp_rowsets,
5679
14
                             tmp_rowset_ref_count_keys_to_delete = tmp_rowset_ref_count_keys]() {
5680
14
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5681
14
                                   metrics_context) != 0) {
5682
14
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5683
14
                return;
5684
14
            }
5685
14
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5686
14
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5687
14
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5688
14
                                 << rs.ShortDebugString();
5689
14
                    return;
5690
14
                }
5691
14
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5692
14
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5693
14
                                 << rs.ShortDebugString();
5694
14
                    return;
5695
14
                }
5696
14
            }
5697
14
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5698
14
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5699
14
                return;
5700
14
            }
5701
14
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5702
14
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5703
14
                return;
5704
14
            }
5705
14
            num_recycled += tmp_rowset_keys.size();
5706
14
            return;
5707
14
        });
5708
14
        return 0;
5709
14
    };
5710
5711
29
    if (config::enable_recycler_stats_metrics) {
5712
0
        scan_and_statistics_tmp_rowsets();
5713
0
    }
5714
    // recycle_func and loop_done for scan and recycle
5715
29
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
5716
29
                               std::move(loop_done));
5717
5718
29
    worker_pool->stop();
5719
5720
    // Report final metrics after all concurrent tasks completed
5721
29
    segment_metrics_context_.report();
5722
29
    metrics_context.report();
5723
5724
29
    return ret;
5725
29
}
5726
5727
int InstanceRecycler::scan_and_recycle(
5728
        std::string begin, std::string_view end,
5729
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
5730
256
        std::function<int()> loop_done) {
5731
256
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
5732
256
    int ret = 0;
5733
256
    int64_t cnt = 0;
5734
256
    int get_range_retried = 0;
5735
256
    std::string err;
5736
256
    DORIS_CLOUD_DEFER_COPY(begin, end) {
5737
256
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
5738
256
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
5739
256
                  << " ret=" << ret << " err=" << err;
5740
256
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
5736
31
    DORIS_CLOUD_DEFER_COPY(begin, end) {
5737
31
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
5738
31
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
5739
31
                  << " ret=" << ret << " err=" << err;
5740
31
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
5736
225
    DORIS_CLOUD_DEFER_COPY(begin, end) {
5737
225
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
5738
225
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
5739
225
                  << " ret=" << ret << " err=" << err;
5740
225
    };
5741
5742
256
    std::unique_ptr<RangeGetIterator> it;
5743
309
    do {
5744
309
        if (get_range_retried > 1000) {
5745
0
            err = "txn_get exceeds max retry, may not scan all keys";
5746
0
            ret = -1;
5747
0
            return -1;
5748
0
        }
5749
309
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
5750
309
        if (get_ret != 0) { // txn kv may complain "Request for future version"
5751
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
5752
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
5753
0
                         << " get_range_retried=" << get_range_retried;
5754
0
            ++get_range_retried;
5755
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
5756
0
            continue; // try again
5757
0
        }
5758
309
        if (!it->has_next()) {
5759
134
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
5760
134
            break; // scan finished
5761
134
        }
5762
150k
        while (it->has_next()) {
5763
150k
            ++cnt;
5764
            // recycle corresponding resources
5765
150k
            auto [k, v] = it->next();
5766
150k
            if (!it->has_next()) {
5767
175
                begin = k;
5768
175
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
5769
175
            }
5770
            // if we want to continue scanning, the recycle_func should not return non-zero
5771
150k
            if (recycle_func(k, v) != 0) {
5772
4.00k
                err = "recycle_func error";
5773
4.00k
                ret = -1;
5774
4.00k
            }
5775
150k
        }
5776
175
        begin.push_back('\x00'); // Update to next smallest key for iteration
5777
        // if we want to continue scanning, the recycle_func should not return non-zero
5778
175
        if (loop_done && loop_done() != 0) {
5779
4
            err = "loop_done error";
5780
4
            ret = -1;
5781
4
        }
5782
175
    } while (it->more() && !stopped());
5783
256
    return ret;
5784
256
}
5785
5786
19
int InstanceRecycler::abort_timeout_txn() {
5787
19
    const std::string task_name = "abort_timeout_txn";
5788
19
    int64_t num_scanned = 0;
5789
19
    int64_t num_timeout = 0;
5790
19
    int64_t num_abort = 0;
5791
19
    int64_t num_advance = 0;
5792
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5793
5794
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
5795
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
5796
19
    std::string begin_txn_running_key;
5797
19
    std::string end_txn_running_key;
5798
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
5799
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
5800
5801
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
5802
5803
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5804
19
    register_recycle_task(task_name, start_time);
5805
5806
19
    DORIS_CLOUD_DEFER {
5807
19
        unregister_recycle_task(task_name);
5808
19
        int64_t cost =
5809
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5810
19
        metrics_context.finish_report();
5811
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
5812
19
                .tag("instance_id", instance_id_)
5813
19
                .tag("num_scanned", num_scanned)
5814
19
                .tag("num_timeout", num_timeout)
5815
19
                .tag("num_abort", num_abort)
5816
19
                .tag("num_advance", num_advance);
5817
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
5806
3
    DORIS_CLOUD_DEFER {
5807
3
        unregister_recycle_task(task_name);
5808
3
        int64_t cost =
5809
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5810
3
        metrics_context.finish_report();
5811
3
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
5812
3
                .tag("instance_id", instance_id_)
5813
3
                .tag("num_scanned", num_scanned)
5814
3
                .tag("num_timeout", num_timeout)
5815
3
                .tag("num_abort", num_abort)
5816
3
                .tag("num_advance", num_advance);
5817
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
5806
16
    DORIS_CLOUD_DEFER {
5807
16
        unregister_recycle_task(task_name);
5808
16
        int64_t cost =
5809
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5810
16
        metrics_context.finish_report();
5811
16
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
5812
16
                .tag("instance_id", instance_id_)
5813
16
                .tag("num_scanned", num_scanned)
5814
16
                .tag("num_timeout", num_timeout)
5815
16
                .tag("num_abort", num_abort)
5816
16
                .tag("num_advance", num_advance);
5817
16
    };
5818
5819
19
    int64_t current_time =
5820
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
5821
5822
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
5823
19
                                  &current_time, &metrics_context,
5824
19
                                  this](std::string_view k, std::string_view v) -> int {
5825
9
        ++num_scanned;
5826
5827
9
        std::unique_ptr<Transaction> txn;
5828
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5829
9
        if (err != TxnErrorCode::TXN_OK) {
5830
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
5831
0
            return -1;
5832
0
        }
5833
9
        std::string_view k1 = k;
5834
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
5835
9
        k1.remove_prefix(1); // Remove key space
5836
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5837
9
        if (decode_key(&k1, &out) != 0) {
5838
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
5839
0
            return -1;
5840
0
        }
5841
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
5842
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
5843
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
5844
        // Update txn_info
5845
9
        std::string txn_inf_key, txn_inf_val;
5846
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
5847
9
        err = txn->get(txn_inf_key, &txn_inf_val);
5848
9
        if (err != TxnErrorCode::TXN_OK) {
5849
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
5850
0
            return -1;
5851
0
        }
5852
9
        TxnInfoPB txn_info;
5853
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
5854
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
5855
0
            return -1;
5856
0
        }
5857
5858
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
5859
3
            txn.reset();
5860
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
5861
3
            std::shared_ptr<TxnLazyCommitTask> task =
5862
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
5863
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
5864
3
            if (ret.first != MetaServiceCode::OK) {
5865
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
5866
0
                             << "msg=" << ret.second;
5867
0
                return -1;
5868
0
            }
5869
3
            ++num_advance;
5870
3
            return 0;
5871
6
        } else {
5872
6
            TxnRunningPB txn_running_pb;
5873
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
5874
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
5875
0
                return -1;
5876
0
            }
5877
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
5878
4
                return 0;
5879
4
            }
5880
2
            ++num_timeout;
5881
5882
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
5883
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
5884
2
            txn_info.set_finish_time(current_time);
5885
2
            txn_info.set_reason("timeout");
5886
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
5887
2
            txn_inf_val.clear();
5888
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
5889
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
5890
0
                return -1;
5891
0
            }
5892
2
            txn->put(txn_inf_key, txn_inf_val);
5893
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
5894
            // Put recycle txn key
5895
2
            std::string recyc_txn_key, recyc_txn_val;
5896
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
5897
2
            RecycleTxnPB recycle_txn_pb;
5898
2
            recycle_txn_pb.set_creation_time(current_time);
5899
2
            recycle_txn_pb.set_label(txn_info.label());
5900
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
5901
0
                LOG_WARNING("failed to serialize txn recycle info")
5902
0
                        .tag("key", hex(k))
5903
0
                        .tag("db_id", db_id)
5904
0
                        .tag("txn_id", txn_id);
5905
0
                return -1;
5906
0
            }
5907
2
            txn->put(recyc_txn_key, recyc_txn_val);
5908
            // Remove txn running key
5909
2
            txn->remove(k);
5910
2
            err = txn->commit();
5911
2
            if (err != TxnErrorCode::TXN_OK) {
5912
0
                LOG_WARNING("failed to commit txn err={}", err)
5913
0
                        .tag("key", hex(k))
5914
0
                        .tag("db_id", db_id)
5915
0
                        .tag("txn_id", txn_id);
5916
0
                return -1;
5917
0
            }
5918
2
            metrics_context.total_recycled_num = ++num_abort;
5919
2
            metrics_context.report();
5920
2
        }
5921
5922
2
        return 0;
5923
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5824
3
                                  this](std::string_view k, std::string_view v) -> int {
5825
3
        ++num_scanned;
5826
5827
3
        std::unique_ptr<Transaction> txn;
5828
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5829
3
        if (err != TxnErrorCode::TXN_OK) {
5830
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
5831
0
            return -1;
5832
0
        }
5833
3
        std::string_view k1 = k;
5834
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
5835
3
        k1.remove_prefix(1); // Remove key space
5836
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5837
3
        if (decode_key(&k1, &out) != 0) {
5838
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
5839
0
            return -1;
5840
0
        }
5841
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
5842
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
5843
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
5844
        // Update txn_info
5845
3
        std::string txn_inf_key, txn_inf_val;
5846
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
5847
3
        err = txn->get(txn_inf_key, &txn_inf_val);
5848
3
        if (err != TxnErrorCode::TXN_OK) {
5849
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
5850
0
            return -1;
5851
0
        }
5852
3
        TxnInfoPB txn_info;
5853
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
5854
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
5855
0
            return -1;
5856
0
        }
5857
5858
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
5859
3
            txn.reset();
5860
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
5861
3
            std::shared_ptr<TxnLazyCommitTask> task =
5862
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
5863
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
5864
3
            if (ret.first != MetaServiceCode::OK) {
5865
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
5866
0
                             << "msg=" << ret.second;
5867
0
                return -1;
5868
0
            }
5869
3
            ++num_advance;
5870
3
            return 0;
5871
3
        } else {
5872
0
            TxnRunningPB txn_running_pb;
5873
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
5874
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
5875
0
                return -1;
5876
0
            }
5877
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
5878
0
                return 0;
5879
0
            }
5880
0
            ++num_timeout;
5881
5882
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
5883
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
5884
0
            txn_info.set_finish_time(current_time);
5885
0
            txn_info.set_reason("timeout");
5886
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
5887
0
            txn_inf_val.clear();
5888
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
5889
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
5890
0
                return -1;
5891
0
            }
5892
0
            txn->put(txn_inf_key, txn_inf_val);
5893
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
5894
            // Put recycle txn key
5895
0
            std::string recyc_txn_key, recyc_txn_val;
5896
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
5897
0
            RecycleTxnPB recycle_txn_pb;
5898
0
            recycle_txn_pb.set_creation_time(current_time);
5899
0
            recycle_txn_pb.set_label(txn_info.label());
5900
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
5901
0
                LOG_WARNING("failed to serialize txn recycle info")
5902
0
                        .tag("key", hex(k))
5903
0
                        .tag("db_id", db_id)
5904
0
                        .tag("txn_id", txn_id);
5905
0
                return -1;
5906
0
            }
5907
0
            txn->put(recyc_txn_key, recyc_txn_val);
5908
            // Remove txn running key
5909
0
            txn->remove(k);
5910
0
            err = txn->commit();
5911
0
            if (err != TxnErrorCode::TXN_OK) {
5912
0
                LOG_WARNING("failed to commit txn err={}", err)
5913
0
                        .tag("key", hex(k))
5914
0
                        .tag("db_id", db_id)
5915
0
                        .tag("txn_id", txn_id);
5916
0
                return -1;
5917
0
            }
5918
0
            metrics_context.total_recycled_num = ++num_abort;
5919
0
            metrics_context.report();
5920
0
        }
5921
5922
0
        return 0;
5923
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5824
6
                                  this](std::string_view k, std::string_view v) -> int {
5825
6
        ++num_scanned;
5826
5827
6
        std::unique_ptr<Transaction> txn;
5828
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5829
6
        if (err != TxnErrorCode::TXN_OK) {
5830
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
5831
0
            return -1;
5832
0
        }
5833
6
        std::string_view k1 = k;
5834
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
5835
6
        k1.remove_prefix(1); // Remove key space
5836
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5837
6
        if (decode_key(&k1, &out) != 0) {
5838
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
5839
0
            return -1;
5840
0
        }
5841
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
5842
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
5843
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
5844
        // Update txn_info
5845
6
        std::string txn_inf_key, txn_inf_val;
5846
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
5847
6
        err = txn->get(txn_inf_key, &txn_inf_val);
5848
6
        if (err != TxnErrorCode::TXN_OK) {
5849
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
5850
0
            return -1;
5851
0
        }
5852
6
        TxnInfoPB txn_info;
5853
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
5854
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
5855
0
            return -1;
5856
0
        }
5857
5858
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
5859
0
            txn.reset();
5860
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
5861
0
            std::shared_ptr<TxnLazyCommitTask> task =
5862
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
5863
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
5864
0
            if (ret.first != MetaServiceCode::OK) {
5865
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
5866
0
                             << "msg=" << ret.second;
5867
0
                return -1;
5868
0
            }
5869
0
            ++num_advance;
5870
0
            return 0;
5871
6
        } else {
5872
6
            TxnRunningPB txn_running_pb;
5873
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
5874
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
5875
0
                return -1;
5876
0
            }
5877
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
5878
4
                return 0;
5879
4
            }
5880
2
            ++num_timeout;
5881
5882
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
5883
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
5884
2
            txn_info.set_finish_time(current_time);
5885
2
            txn_info.set_reason("timeout");
5886
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
5887
2
            txn_inf_val.clear();
5888
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
5889
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
5890
0
                return -1;
5891
0
            }
5892
2
            txn->put(txn_inf_key, txn_inf_val);
5893
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
5894
            // Put recycle txn key
5895
2
            std::string recyc_txn_key, recyc_txn_val;
5896
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
5897
2
            RecycleTxnPB recycle_txn_pb;
5898
2
            recycle_txn_pb.set_creation_time(current_time);
5899
2
            recycle_txn_pb.set_label(txn_info.label());
5900
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
5901
0
                LOG_WARNING("failed to serialize txn recycle info")
5902
0
                        .tag("key", hex(k))
5903
0
                        .tag("db_id", db_id)
5904
0
                        .tag("txn_id", txn_id);
5905
0
                return -1;
5906
0
            }
5907
2
            txn->put(recyc_txn_key, recyc_txn_val);
5908
            // Remove txn running key
5909
2
            txn->remove(k);
5910
2
            err = txn->commit();
5911
2
            if (err != TxnErrorCode::TXN_OK) {
5912
0
                LOG_WARNING("failed to commit txn err={}", err)
5913
0
                        .tag("key", hex(k))
5914
0
                        .tag("db_id", db_id)
5915
0
                        .tag("txn_id", txn_id);
5916
0
                return -1;
5917
0
            }
5918
2
            metrics_context.total_recycled_num = ++num_abort;
5919
2
            metrics_context.report();
5920
2
        }
5921
5922
2
        return 0;
5923
6
    };
5924
5925
19
    if (config::enable_recycler_stats_metrics) {
5926
0
        scan_and_statistics_abort_timeout_txn();
5927
0
    }
5928
    // recycle_func and loop_done for scan and recycle
5929
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
5930
19
                            std::move(handle_txn_running_kv));
5931
19
}
5932
5933
19
int InstanceRecycler::recycle_expired_txn_label() {
5934
19
    const std::string task_name = "recycle_expired_txn_label";
5935
19
    int64_t num_scanned = 0;
5936
19
    int64_t num_expired = 0;
5937
19
    std::atomic_long num_recycled = 0;
5938
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5939
19
    int ret = 0;
5940
5941
19
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
5942
19
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
5943
19
    std::string begin_recycle_txn_key;
5944
19
    std::string end_recycle_txn_key;
5945
19
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
5946
19
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
5947
19
    std::vector<std::string> recycle_txn_info_keys;
5948
5949
19
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
5950
5951
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5952
19
    register_recycle_task(task_name, start_time);
5953
19
    DORIS_CLOUD_DEFER {
5954
19
        unregister_recycle_task(task_name);
5955
19
        int64_t cost =
5956
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5957
19
        metrics_context.finish_report();
5958
19
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
5959
19
                .tag("instance_id", instance_id_)
5960
19
                .tag("num_scanned", num_scanned)
5961
19
                .tag("num_expired", num_expired)
5962
19
                .tag("num_recycled", num_recycled);
5963
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
5953
1
    DORIS_CLOUD_DEFER {
5954
1
        unregister_recycle_task(task_name);
5955
1
        int64_t cost =
5956
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5957
1
        metrics_context.finish_report();
5958
1
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
5959
1
                .tag("instance_id", instance_id_)
5960
1
                .tag("num_scanned", num_scanned)
5961
1
                .tag("num_expired", num_expired)
5962
1
                .tag("num_recycled", num_recycled);
5963
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
5953
18
    DORIS_CLOUD_DEFER {
5954
18
        unregister_recycle_task(task_name);
5955
18
        int64_t cost =
5956
18
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5957
18
        metrics_context.finish_report();
5958
18
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
5959
18
                .tag("instance_id", instance_id_)
5960
18
                .tag("num_scanned", num_scanned)
5961
18
                .tag("num_expired", num_expired)
5962
18
                .tag("num_recycled", num_recycled);
5963
18
    };
5964
5965
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5966
5967
19
    SyncExecutor<int> concurrent_delete_executor(
5968
19
            _thread_pool_group.s3_producer_pool,
5969
19
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
5970
23.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
5970
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
5970
23.0k
            [](const int& ret) { return ret != 0; });
5971
5972
19
    int64_t current_time_ms =
5973
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
5974
5975
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
5976
30.0k
        ++num_scanned;
5977
30.0k
        RecycleTxnPB recycle_txn_pb;
5978
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
5979
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
5980
0
            return -1;
5981
0
        }
5982
30.0k
        if ((config::force_immediate_recycle) ||
5983
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
5984
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
5985
30.0k
             current_time_ms)) {
5986
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
5987
23.0k
            num_expired++;
5988
23.0k
            recycle_txn_info_keys.emplace_back(k);
5989
23.0k
        }
5990
30.0k
        return 0;
5991
30.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5975
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
5976
1
        ++num_scanned;
5977
1
        RecycleTxnPB recycle_txn_pb;
5978
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
5979
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
5980
0
            return -1;
5981
0
        }
5982
1
        if ((config::force_immediate_recycle) ||
5983
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
5984
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
5985
1
             current_time_ms)) {
5986
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
5987
1
            num_expired++;
5988
1
            recycle_txn_info_keys.emplace_back(k);
5989
1
        }
5990
1
        return 0;
5991
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5975
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
5976
30.0k
        ++num_scanned;
5977
30.0k
        RecycleTxnPB recycle_txn_pb;
5978
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
5979
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
5980
0
            return -1;
5981
0
        }
5982
30.0k
        if ((config::force_immediate_recycle) ||
5983
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
5984
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
5985
30.0k
             current_time_ms)) {
5986
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
5987
23.0k
            num_expired++;
5988
23.0k
            recycle_txn_info_keys.emplace_back(k);
5989
23.0k
        }
5990
30.0k
        return 0;
5991
30.0k
    };
5992
5993
    // int 0 for success, 1 for conflict, -1 for error
5994
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
5995
23.0k
        std::string_view k1 = k;
5996
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
5997
23.0k
        k1.remove_prefix(1); // Remove key space
5998
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5999
23.0k
        int ret = decode_key(&k1, &out);
6000
23.0k
        if (ret != 0) {
6001
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6002
0
            return -1;
6003
0
        }
6004
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6005
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6006
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6007
23.0k
        std::unique_ptr<Transaction> txn;
6008
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6009
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6010
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6011
0
            return -1;
6012
0
        }
6013
        // Remove txn index kv
6014
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6015
23.0k
        txn->remove(index_key);
6016
        // Remove txn info kv
6017
23.0k
        std::string info_key, info_val;
6018
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6019
23.0k
        err = txn->get(info_key, &info_val);
6020
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6021
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6022
0
            return -1;
6023
0
        }
6024
23.0k
        TxnInfoPB txn_info;
6025
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6026
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6027
0
            return -1;
6028
0
        }
6029
23.0k
        txn->remove(info_key);
6030
        // Remove sub txn index kvs
6031
23.0k
        std::vector<std::string> sub_txn_index_keys;
6032
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6033
23.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6034
23.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6035
23.0k
        }
6036
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6037
22.9k
            txn->remove(sub_txn_index_key);
6038
22.9k
        }
6039
        // Update txn label
6040
23.0k
        std::string label_key, label_val;
6041
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6042
23.0k
        err = txn->get(label_key, &label_val);
6043
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6044
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6045
0
                         << " err=" << err;
6046
0
            return -1;
6047
0
        }
6048
23.0k
        TxnLabelPB txn_label;
6049
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6050
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6051
0
            return -1;
6052
0
        }
6053
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6054
23.0k
        if (it != txn_label.txn_ids().end()) {
6055
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6056
23.0k
        }
6057
23.0k
        if (txn_label.txn_ids().empty()) {
6058
23.0k
            txn->remove(label_key);
6059
23.0k
            TEST_SYNC_POINT_CALLBACK(
6060
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6061
23.0k
        } else {
6062
73
            if (!txn_label.SerializeToString(&label_val)) {
6063
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6064
0
                return -1;
6065
0
            }
6066
73
            TEST_SYNC_POINT_CALLBACK(
6067
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6068
73
            txn->atomic_set_ver_value(label_key, label_val);
6069
73
            TEST_SYNC_POINT_CALLBACK(
6070
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6071
73
        }
6072
        // Remove recycle txn kv
6073
23.0k
        txn->remove(k);
6074
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6075
23.0k
        err = txn->commit();
6076
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6077
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6078
62
                TEST_SYNC_POINT_CALLBACK(
6079
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6080
                // log the txn_id and label
6081
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6082
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6083
62
                             << " txn_label=" << txn_info.label();
6084
62
                return 1;
6085
62
            }
6086
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6087
0
            return -1;
6088
62
        }
6089
23.0k
        ++num_recycled;
6090
6091
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6092
23.0k
        return 0;
6093
23.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5994
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
5995
1
        std::string_view k1 = k;
5996
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
5997
1
        k1.remove_prefix(1); // Remove key space
5998
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5999
1
        int ret = decode_key(&k1, &out);
6000
1
        if (ret != 0) {
6001
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6002
0
            return -1;
6003
0
        }
6004
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6005
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6006
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6007
1
        std::unique_ptr<Transaction> txn;
6008
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6009
1
        if (err != TxnErrorCode::TXN_OK) {
6010
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6011
0
            return -1;
6012
0
        }
6013
        // Remove txn index kv
6014
1
        auto index_key = txn_index_key({instance_id_, txn_id});
6015
1
        txn->remove(index_key);
6016
        // Remove txn info kv
6017
1
        std::string info_key, info_val;
6018
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6019
1
        err = txn->get(info_key, &info_val);
6020
1
        if (err != TxnErrorCode::TXN_OK) {
6021
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6022
0
            return -1;
6023
0
        }
6024
1
        TxnInfoPB txn_info;
6025
1
        if (!txn_info.ParseFromString(info_val)) {
6026
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6027
0
            return -1;
6028
0
        }
6029
1
        txn->remove(info_key);
6030
        // Remove sub txn index kvs
6031
1
        std::vector<std::string> sub_txn_index_keys;
6032
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6033
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6034
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
6035
0
        }
6036
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6037
0
            txn->remove(sub_txn_index_key);
6038
0
        }
6039
        // Update txn label
6040
1
        std::string label_key, label_val;
6041
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6042
1
        err = txn->get(label_key, &label_val);
6043
1
        if (err != TxnErrorCode::TXN_OK) {
6044
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6045
0
                         << " err=" << err;
6046
0
            return -1;
6047
0
        }
6048
1
        TxnLabelPB txn_label;
6049
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6050
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6051
0
            return -1;
6052
0
        }
6053
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6054
1
        if (it != txn_label.txn_ids().end()) {
6055
1
            txn_label.mutable_txn_ids()->erase(it);
6056
1
        }
6057
1
        if (txn_label.txn_ids().empty()) {
6058
1
            txn->remove(label_key);
6059
1
            TEST_SYNC_POINT_CALLBACK(
6060
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6061
1
        } else {
6062
0
            if (!txn_label.SerializeToString(&label_val)) {
6063
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6064
0
                return -1;
6065
0
            }
6066
0
            TEST_SYNC_POINT_CALLBACK(
6067
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6068
0
            txn->atomic_set_ver_value(label_key, label_val);
6069
0
            TEST_SYNC_POINT_CALLBACK(
6070
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6071
0
        }
6072
        // Remove recycle txn kv
6073
1
        txn->remove(k);
6074
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6075
1
        err = txn->commit();
6076
1
        if (err != TxnErrorCode::TXN_OK) {
6077
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
6078
0
                TEST_SYNC_POINT_CALLBACK(
6079
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6080
                // log the txn_id and label
6081
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6082
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6083
0
                             << " txn_label=" << txn_info.label();
6084
0
                return 1;
6085
0
            }
6086
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6087
0
            return -1;
6088
0
        }
6089
1
        ++num_recycled;
6090
6091
1
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6092
1
        return 0;
6093
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5994
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
5995
23.0k
        std::string_view k1 = k;
5996
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
5997
23.0k
        k1.remove_prefix(1); // Remove key space
5998
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5999
23.0k
        int ret = decode_key(&k1, &out);
6000
23.0k
        if (ret != 0) {
6001
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6002
0
            return -1;
6003
0
        }
6004
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6005
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6006
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6007
23.0k
        std::unique_ptr<Transaction> txn;
6008
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6009
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6010
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6011
0
            return -1;
6012
0
        }
6013
        // Remove txn index kv
6014
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6015
23.0k
        txn->remove(index_key);
6016
        // Remove txn info kv
6017
23.0k
        std::string info_key, info_val;
6018
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6019
23.0k
        err = txn->get(info_key, &info_val);
6020
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6021
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6022
0
            return -1;
6023
0
        }
6024
23.0k
        TxnInfoPB txn_info;
6025
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6026
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6027
0
            return -1;
6028
0
        }
6029
23.0k
        txn->remove(info_key);
6030
        // Remove sub txn index kvs
6031
23.0k
        std::vector<std::string> sub_txn_index_keys;
6032
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6033
23.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6034
23.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6035
23.0k
        }
6036
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6037
22.9k
            txn->remove(sub_txn_index_key);
6038
22.9k
        }
6039
        // Update txn label
6040
23.0k
        std::string label_key, label_val;
6041
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6042
23.0k
        err = txn->get(label_key, &label_val);
6043
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6044
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6045
0
                         << " err=" << err;
6046
0
            return -1;
6047
0
        }
6048
23.0k
        TxnLabelPB txn_label;
6049
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6050
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6051
0
            return -1;
6052
0
        }
6053
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6054
23.0k
        if (it != txn_label.txn_ids().end()) {
6055
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6056
23.0k
        }
6057
23.0k
        if (txn_label.txn_ids().empty()) {
6058
23.0k
            txn->remove(label_key);
6059
23.0k
            TEST_SYNC_POINT_CALLBACK(
6060
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6061
23.0k
        } else {
6062
73
            if (!txn_label.SerializeToString(&label_val)) {
6063
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6064
0
                return -1;
6065
0
            }
6066
73
            TEST_SYNC_POINT_CALLBACK(
6067
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6068
73
            txn->atomic_set_ver_value(label_key, label_val);
6069
73
            TEST_SYNC_POINT_CALLBACK(
6070
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6071
73
        }
6072
        // Remove recycle txn kv
6073
23.0k
        txn->remove(k);
6074
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6075
23.0k
        err = txn->commit();
6076
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6077
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6078
62
                TEST_SYNC_POINT_CALLBACK(
6079
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6080
                // log the txn_id and label
6081
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6082
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6083
62
                             << " txn_label=" << txn_info.label();
6084
62
                return 1;
6085
62
            }
6086
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6087
0
            return -1;
6088
62
        }
6089
23.0k
        ++num_recycled;
6090
6091
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6092
23.0k
        return 0;
6093
23.0k
    };
6094
6095
19
    auto loop_done = [&]() -> int {
6096
10
        DORIS_CLOUD_DEFER {
6097
10
            recycle_txn_info_keys.clear();
6098
10
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6096
1
        DORIS_CLOUD_DEFER {
6097
1
            recycle_txn_info_keys.clear();
6098
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6096
9
        DORIS_CLOUD_DEFER {
6097
9
            recycle_txn_info_keys.clear();
6098
9
        };
6099
10
        TEST_SYNC_POINT_CALLBACK(
6100
10
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6101
10
                &recycle_txn_info_keys);
6102
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6103
23.0k
            concurrent_delete_executor.add([&]() {
6104
23.0k
                int ret = delete_recycle_txn_kv(k);
6105
23.0k
                if (ret == 1) {
6106
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6107
54
                    for (int i = 1; i <= max_retry; ++i) {
6108
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6109
54
                        ret = delete_recycle_txn_kv(k);
6110
                        // clang-format off
6111
54
                        TEST_SYNC_POINT_CALLBACK(
6112
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6113
                        // clang-format off
6114
54
                        if (ret != 1) {
6115
18
                            break;
6116
18
                        }
6117
                        // random sleep 0-100 ms to retry
6118
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6119
36
                    }
6120
18
                }
6121
23.0k
                if (ret != 0) {
6122
9
                    LOG_WARNING("failed to delete recycle txn kv")
6123
9
                            .tag("instance id", instance_id_)
6124
9
                            .tag("key", hex(k));
6125
9
                    return -1;
6126
9
                }
6127
23.0k
                return 0;
6128
23.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6103
1
            concurrent_delete_executor.add([&]() {
6104
1
                int ret = delete_recycle_txn_kv(k);
6105
1
                if (ret == 1) {
6106
0
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6107
0
                    for (int i = 1; i <= max_retry; ++i) {
6108
0
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6109
0
                        ret = delete_recycle_txn_kv(k);
6110
                        // clang-format off
6111
0
                        TEST_SYNC_POINT_CALLBACK(
6112
0
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6113
                        // clang-format off
6114
0
                        if (ret != 1) {
6115
0
                            break;
6116
0
                        }
6117
                        // random sleep 0-100 ms to retry
6118
0
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6119
0
                    }
6120
0
                }
6121
1
                if (ret != 0) {
6122
0
                    LOG_WARNING("failed to delete recycle txn kv")
6123
0
                            .tag("instance id", instance_id_)
6124
0
                            .tag("key", hex(k));
6125
0
                    return -1;
6126
0
                }
6127
1
                return 0;
6128
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6103
23.0k
            concurrent_delete_executor.add([&]() {
6104
23.0k
                int ret = delete_recycle_txn_kv(k);
6105
23.0k
                if (ret == 1) {
6106
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6107
54
                    for (int i = 1; i <= max_retry; ++i) {
6108
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6109
54
                        ret = delete_recycle_txn_kv(k);
6110
                        // clang-format off
6111
54
                        TEST_SYNC_POINT_CALLBACK(
6112
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6113
                        // clang-format off
6114
54
                        if (ret != 1) {
6115
18
                            break;
6116
18
                        }
6117
                        // random sleep 0-100 ms to retry
6118
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6119
36
                    }
6120
18
                }
6121
23.0k
                if (ret != 0) {
6122
9
                    LOG_WARNING("failed to delete recycle txn kv")
6123
9
                            .tag("instance id", instance_id_)
6124
9
                            .tag("key", hex(k));
6125
9
                    return -1;
6126
9
                }
6127
23.0k
                return 0;
6128
23.0k
            });
6129
23.0k
        }
6130
10
        bool finished = true;
6131
10
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6132
23.0k
        for (int r : rets) {
6133
23.0k
            if (r != 0) {
6134
9
                ret = -1;
6135
9
            }
6136
23.0k
        }
6137
6138
10
        ret = finished ? ret : -1;
6139
6140
        // Update metrics after all concurrent tasks completed
6141
10
        metrics_context.total_recycled_num = num_recycled.load();
6142
10
        metrics_context.report();
6143
6144
10
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6145
6146
10
        if (ret != 0) {
6147
3
            LOG_WARNING("recycle txn kv ret!=0")
6148
3
                    .tag("finished", finished)
6149
3
                    .tag("ret", ret)
6150
3
                    .tag("instance_id", instance_id_);
6151
3
            return ret;
6152
3
        }
6153
7
        return ret;
6154
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6095
1
    auto loop_done = [&]() -> int {
6096
1
        DORIS_CLOUD_DEFER {
6097
1
            recycle_txn_info_keys.clear();
6098
1
        };
6099
1
        TEST_SYNC_POINT_CALLBACK(
6100
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6101
1
                &recycle_txn_info_keys);
6102
1
        for (const auto& k : recycle_txn_info_keys) {
6103
1
            concurrent_delete_executor.add([&]() {
6104
1
                int ret = delete_recycle_txn_kv(k);
6105
1
                if (ret == 1) {
6106
1
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6107
1
                    for (int i = 1; i <= max_retry; ++i) {
6108
1
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6109
1
                        ret = delete_recycle_txn_kv(k);
6110
                        // clang-format off
6111
1
                        TEST_SYNC_POINT_CALLBACK(
6112
1
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6113
                        // clang-format off
6114
1
                        if (ret != 1) {
6115
1
                            break;
6116
1
                        }
6117
                        // random sleep 0-100 ms to retry
6118
1
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6119
1
                    }
6120
1
                }
6121
1
                if (ret != 0) {
6122
1
                    LOG_WARNING("failed to delete recycle txn kv")
6123
1
                            .tag("instance id", instance_id_)
6124
1
                            .tag("key", hex(k));
6125
1
                    return -1;
6126
1
                }
6127
1
                return 0;
6128
1
            });
6129
1
        }
6130
1
        bool finished = true;
6131
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6132
1
        for (int r : rets) {
6133
1
            if (r != 0) {
6134
0
                ret = -1;
6135
0
            }
6136
1
        }
6137
6138
1
        ret = finished ? ret : -1;
6139
6140
        // Update metrics after all concurrent tasks completed
6141
1
        metrics_context.total_recycled_num = num_recycled.load();
6142
1
        metrics_context.report();
6143
6144
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6145
6146
1
        if (ret != 0) {
6147
0
            LOG_WARNING("recycle txn kv ret!=0")
6148
0
                    .tag("finished", finished)
6149
0
                    .tag("ret", ret)
6150
0
                    .tag("instance_id", instance_id_);
6151
0
            return ret;
6152
0
        }
6153
1
        return ret;
6154
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6095
9
    auto loop_done = [&]() -> int {
6096
9
        DORIS_CLOUD_DEFER {
6097
9
            recycle_txn_info_keys.clear();
6098
9
        };
6099
9
        TEST_SYNC_POINT_CALLBACK(
6100
9
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6101
9
                &recycle_txn_info_keys);
6102
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6103
23.0k
            concurrent_delete_executor.add([&]() {
6104
23.0k
                int ret = delete_recycle_txn_kv(k);
6105
23.0k
                if (ret == 1) {
6106
23.0k
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6107
23.0k
                    for (int i = 1; i <= max_retry; ++i) {
6108
23.0k
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6109
23.0k
                        ret = delete_recycle_txn_kv(k);
6110
                        // clang-format off
6111
23.0k
                        TEST_SYNC_POINT_CALLBACK(
6112
23.0k
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6113
                        // clang-format off
6114
23.0k
                        if (ret != 1) {
6115
23.0k
                            break;
6116
23.0k
                        }
6117
                        // random sleep 0-100 ms to retry
6118
23.0k
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6119
23.0k
                    }
6120
23.0k
                }
6121
23.0k
                if (ret != 0) {
6122
23.0k
                    LOG_WARNING("failed to delete recycle txn kv")
6123
23.0k
                            .tag("instance id", instance_id_)
6124
23.0k
                            .tag("key", hex(k));
6125
23.0k
                    return -1;
6126
23.0k
                }
6127
23.0k
                return 0;
6128
23.0k
            });
6129
23.0k
        }
6130
9
        bool finished = true;
6131
9
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6132
23.0k
        for (int r : rets) {
6133
23.0k
            if (r != 0) {
6134
9
                ret = -1;
6135
9
            }
6136
23.0k
        }
6137
6138
9
        ret = finished ? ret : -1;
6139
6140
        // Update metrics after all concurrent tasks completed
6141
9
        metrics_context.total_recycled_num = num_recycled.load();
6142
9
        metrics_context.report();
6143
6144
9
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6145
6146
9
        if (ret != 0) {
6147
3
            LOG_WARNING("recycle txn kv ret!=0")
6148
3
                    .tag("finished", finished)
6149
3
                    .tag("ret", ret)
6150
3
                    .tag("instance_id", instance_id_);
6151
3
            return ret;
6152
3
        }
6153
6
        return ret;
6154
9
    };
6155
6156
19
    if (config::enable_recycler_stats_metrics) {
6157
0
        scan_and_statistics_expired_txn_label();
6158
0
    }
6159
    // recycle_func and loop_done for scan and recycle
6160
19
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
6161
19
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
6162
19
}
6163
6164
struct CopyJobIdTuple {
6165
    std::string instance_id;
6166
    std::string stage_id;
6167
    long table_id;
6168
    std::string copy_id;
6169
    std::string stage_path;
6170
};
6171
struct BatchObjStoreAccessor {
6172
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
6173
                          TxnKv* txn_kv)
6174
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
6175
3
    ~BatchObjStoreAccessor() {
6176
3
        if (!paths_.empty()) {
6177
3
            consume();
6178
3
        }
6179
3
    }
6180
6181
    /**
6182
    * To implicitely do batch work and submit the batch delete task to s3
6183
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
6184
    *
6185
    * @param copy_job The protubuf struct consists of the copy job files.
6186
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
6187
    *            it would last until we finish the delete task, here we need pass one string value
6188
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
6189
    */
6190
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
6191
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
6192
5
        auto& file_keys = copy_file_keys_[key];
6193
5
        file_keys.log_trace =
6194
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
6195
5
                            instance_id, stage_id, table_id, copy_id, path);
6196
5
        std::string_view log_trace = file_keys.log_trace;
6197
2.03k
        for (const auto& file : copy_job.object_files()) {
6198
2.03k
            auto relative_path = file.relative_path();
6199
2.03k
            paths_.push_back(relative_path);
6200
2.03k
            file_keys.keys.push_back(copy_file_key(
6201
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
6202
2.03k
            LOG_INFO(log_trace)
6203
2.03k
                    .tag("relative_path", relative_path)
6204
2.03k
                    .tag("batch_count", batch_count_);
6205
2.03k
        }
6206
5
        LOG_INFO(log_trace)
6207
5
                .tag("objects_num", copy_job.object_files().size())
6208
5
                .tag("batch_count", batch_count_);
6209
        // 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
6210
        // recommend using delete objects when objects num is less than 10)
6211
5
        if (paths_.size() < 1000) {
6212
3
            return;
6213
3
        }
6214
2
        consume();
6215
2
    }
6216
6217
private:
6218
5
    void consume() {
6219
5
        DORIS_CLOUD_DEFER {
6220
5
            paths_.clear();
6221
5
            copy_file_keys_.clear();
6222
5
            batch_count_++;
6223
6224
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
6225
5
                        batch_count_);
6226
5
        };
6227
6228
5
        StopWatch sw;
6229
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
6230
5
        if (0 != accessor_->delete_files(paths_)) {
6231
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
6232
2
                        paths_.size(), batch_count_, sw.elapsed_us());
6233
2
            return;
6234
2
        }
6235
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
6236
3
                    paths_.size(), batch_count_, sw.elapsed_us());
6237
        // delete fdb's keys
6238
3
        for (auto& file_keys : copy_file_keys_) {
6239
3
            auto& [log_trace, keys] = file_keys.second;
6240
3
            std::unique_ptr<Transaction> txn;
6241
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
6242
0
                LOG(WARNING) << "failed to create txn";
6243
0
                continue;
6244
0
            }
6245
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6246
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6247
            // limited, should not cause the txn commit failed.
6248
1.02k
            for (const auto& key : keys) {
6249
1.02k
                txn->remove(key);
6250
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
6251
1.02k
            }
6252
3
            txn->remove(file_keys.first);
6253
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
6254
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
6255
0
                continue;
6256
0
            }
6257
3
        }
6258
3
    }
6259
    std::shared_ptr<StorageVaultAccessor> accessor_;
6260
    // the path of the s3 files to be deleted
6261
    std::vector<std::string> paths_;
6262
    struct CopyFiles {
6263
        std::string log_trace;
6264
        std::vector<std::string> keys;
6265
    };
6266
    // pair<std::string, std::vector<std::string>>
6267
    // first: instance_id_ stage_id table_id query_id
6268
    // second: keys to be deleted
6269
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
6270
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
6271
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
6272
    // which can together uniquely identifies different tasks for tracing log
6273
    uint64_t& batch_count_;
6274
    TxnKv* txn_kv_;
6275
};
6276
6277
13
int InstanceRecycler::recycle_copy_jobs() {
6278
13
    int64_t num_scanned = 0;
6279
13
    int64_t num_finished = 0;
6280
13
    int64_t num_expired = 0;
6281
13
    int64_t num_recycled = 0;
6282
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
6283
13
    uint64_t batch_count = 0;
6284
13
    const std::string task_name = "recycle_copy_jobs";
6285
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6286
6287
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
6288
6289
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6290
13
    register_recycle_task(task_name, start_time);
6291
6292
13
    DORIS_CLOUD_DEFER {
6293
13
        unregister_recycle_task(task_name);
6294
13
        int64_t cost =
6295
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6296
13
        metrics_context.finish_report();
6297
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
6298
13
                .tag("instance_id", instance_id_)
6299
13
                .tag("num_scanned", num_scanned)
6300
13
                .tag("num_finished", num_finished)
6301
13
                .tag("num_expired", num_expired)
6302
13
                .tag("num_recycled", num_recycled);
6303
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
6292
13
    DORIS_CLOUD_DEFER {
6293
13
        unregister_recycle_task(task_name);
6294
13
        int64_t cost =
6295
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6296
13
        metrics_context.finish_report();
6297
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
6298
13
                .tag("instance_id", instance_id_)
6299
13
                .tag("num_scanned", num_scanned)
6300
13
                .tag("num_finished", num_finished)
6301
13
                .tag("num_expired", num_expired)
6302
13
                .tag("num_recycled", num_recycled);
6303
13
    };
6304
6305
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
6306
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
6307
13
    std::string key0;
6308
13
    std::string key1;
6309
13
    copy_job_key(key_info0, &key0);
6310
13
    copy_job_key(key_info1, &key1);
6311
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
6312
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
6313
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
6314
16
                         this](std::string_view k, std::string_view v) -> int {
6315
16
        ++num_scanned;
6316
16
        CopyJobPB copy_job;
6317
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
6318
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
6319
0
            return -1;
6320
0
        }
6321
6322
        // decode copy job key
6323
16
        auto k1 = k;
6324
16
        k1.remove_prefix(1);
6325
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6326
16
        decode_key(&k1, &out);
6327
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
6328
        // -> CopyJobPB
6329
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
6330
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
6331
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
6332
6333
16
        bool check_storage = true;
6334
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
6335
12
            ++num_finished;
6336
6337
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
6338
7
                auto it = stage_accessor_map.find(stage_id);
6339
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
6340
7
                std::string_view path;
6341
7
                if (it != stage_accessor_map.end()) {
6342
2
                    accessor = it->second;
6343
5
                } else {
6344
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
6345
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
6346
5
                                                      &inner_accessor);
6347
5
                    if (ret < 0) { // error
6348
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
6349
0
                        return -1;
6350
5
                    } else if (ret == 0) {
6351
3
                        path = inner_accessor->uri();
6352
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
6353
3
                                inner_accessor, batch_count, txn_kv_.get());
6354
3
                        stage_accessor_map.emplace(stage_id, accessor);
6355
3
                    } else { // stage not found, skip check storage
6356
2
                        check_storage = false;
6357
2
                    }
6358
5
                }
6359
7
                if (check_storage) {
6360
                    // TODO delete objects with key and etag is not supported
6361
5
                    accessor->add(std::move(copy_job), std::string(k),
6362
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
6363
5
                    return 0;
6364
5
                }
6365
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
6366
5
                int64_t current_time =
6367
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6368
5
                if (copy_job.finish_time_ms() > 0) {
6369
2
                    if (!config::force_immediate_recycle &&
6370
2
                        current_time < copy_job.finish_time_ms() +
6371
2
                                               config::copy_job_max_retention_second * 1000) {
6372
1
                        return 0;
6373
1
                    }
6374
3
                } else {
6375
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
6376
3
                    if (!config::force_immediate_recycle &&
6377
3
                        current_time < copy_job.start_time_ms() +
6378
3
                                               config::copy_job_max_retention_second * 1000) {
6379
1
                        return 0;
6380
1
                    }
6381
3
                }
6382
5
            }
6383
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
6384
4
            int64_t current_time =
6385
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6386
            // if copy job is timeout: delete all copy file kvs and copy job kv
6387
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
6388
2
                return 0;
6389
2
            }
6390
2
            ++num_expired;
6391
2
        }
6392
6393
        // delete all copy files
6394
7
        std::vector<std::string> copy_file_keys;
6395
70
        for (auto& file : copy_job.object_files()) {
6396
70
            copy_file_keys.push_back(copy_file_key(
6397
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
6398
70
        }
6399
7
        std::unique_ptr<Transaction> txn;
6400
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
6401
0
            LOG(WARNING) << "failed to create txn";
6402
0
            return -1;
6403
0
        }
6404
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6405
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6406
        // limited, should not cause the txn commit failed.
6407
70
        for (const auto& key : copy_file_keys) {
6408
70
            txn->remove(key);
6409
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
6410
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
6411
70
                      << ", query_id=" << copy_id;
6412
70
        }
6413
7
        txn->remove(k);
6414
7
        TxnErrorCode err = txn->commit();
6415
7
        if (err != TxnErrorCode::TXN_OK) {
6416
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
6417
0
            return -1;
6418
0
        }
6419
6420
7
        metrics_context.total_recycled_num = ++num_recycled;
6421
7
        metrics_context.report();
6422
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6423
7
        return 0;
6424
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
6314
16
                         this](std::string_view k, std::string_view v) -> int {
6315
16
        ++num_scanned;
6316
16
        CopyJobPB copy_job;
6317
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
6318
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
6319
0
            return -1;
6320
0
        }
6321
6322
        // decode copy job key
6323
16
        auto k1 = k;
6324
16
        k1.remove_prefix(1);
6325
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6326
16
        decode_key(&k1, &out);
6327
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
6328
        // -> CopyJobPB
6329
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
6330
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
6331
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
6332
6333
16
        bool check_storage = true;
6334
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
6335
12
            ++num_finished;
6336
6337
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
6338
7
                auto it = stage_accessor_map.find(stage_id);
6339
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
6340
7
                std::string_view path;
6341
7
                if (it != stage_accessor_map.end()) {
6342
2
                    accessor = it->second;
6343
5
                } else {
6344
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
6345
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
6346
5
                                                      &inner_accessor);
6347
5
                    if (ret < 0) { // error
6348
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
6349
0
                        return -1;
6350
5
                    } else if (ret == 0) {
6351
3
                        path = inner_accessor->uri();
6352
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
6353
3
                                inner_accessor, batch_count, txn_kv_.get());
6354
3
                        stage_accessor_map.emplace(stage_id, accessor);
6355
3
                    } else { // stage not found, skip check storage
6356
2
                        check_storage = false;
6357
2
                    }
6358
5
                }
6359
7
                if (check_storage) {
6360
                    // TODO delete objects with key and etag is not supported
6361
5
                    accessor->add(std::move(copy_job), std::string(k),
6362
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
6363
5
                    return 0;
6364
5
                }
6365
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
6366
5
                int64_t current_time =
6367
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6368
5
                if (copy_job.finish_time_ms() > 0) {
6369
2
                    if (!config::force_immediate_recycle &&
6370
2
                        current_time < copy_job.finish_time_ms() +
6371
2
                                               config::copy_job_max_retention_second * 1000) {
6372
1
                        return 0;
6373
1
                    }
6374
3
                } else {
6375
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
6376
3
                    if (!config::force_immediate_recycle &&
6377
3
                        current_time < copy_job.start_time_ms() +
6378
3
                                               config::copy_job_max_retention_second * 1000) {
6379
1
                        return 0;
6380
1
                    }
6381
3
                }
6382
5
            }
6383
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
6384
4
            int64_t current_time =
6385
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6386
            // if copy job is timeout: delete all copy file kvs and copy job kv
6387
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
6388
2
                return 0;
6389
2
            }
6390
2
            ++num_expired;
6391
2
        }
6392
6393
        // delete all copy files
6394
7
        std::vector<std::string> copy_file_keys;
6395
70
        for (auto& file : copy_job.object_files()) {
6396
70
            copy_file_keys.push_back(copy_file_key(
6397
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
6398
70
        }
6399
7
        std::unique_ptr<Transaction> txn;
6400
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
6401
0
            LOG(WARNING) << "failed to create txn";
6402
0
            return -1;
6403
0
        }
6404
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6405
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6406
        // limited, should not cause the txn commit failed.
6407
70
        for (const auto& key : copy_file_keys) {
6408
70
            txn->remove(key);
6409
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
6410
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
6411
70
                      << ", query_id=" << copy_id;
6412
70
        }
6413
7
        txn->remove(k);
6414
7
        TxnErrorCode err = txn->commit();
6415
7
        if (err != TxnErrorCode::TXN_OK) {
6416
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
6417
0
            return -1;
6418
0
        }
6419
6420
7
        metrics_context.total_recycled_num = ++num_recycled;
6421
7
        metrics_context.report();
6422
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6423
7
        return 0;
6424
7
    };
6425
6426
13
    if (config::enable_recycler_stats_metrics) {
6427
0
        scan_and_statistics_copy_jobs();
6428
0
    }
6429
    // recycle_func and loop_done for scan and recycle
6430
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
6431
13
}
6432
6433
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
6434
                                             const StagePB::StageType& stage_type,
6435
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
6436
5
#ifdef UNIT_TEST
6437
    // In unit test, external use the same accessor as the internal stage
6438
5
    auto it = accessor_map_.find(stage_id);
6439
5
    if (it != accessor_map_.end()) {
6440
3
        *accessor = it->second;
6441
3
    } else {
6442
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
6443
2
        return 1;
6444
2
    }
6445
#else
6446
    // init s3 accessor and add to accessor map
6447
    auto stage_it =
6448
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
6449
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
6450
6451
    if (stage_it == instance_info_.stages().end()) {
6452
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
6453
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
6454
        return 1;
6455
    }
6456
6457
    const auto& object_store_info = stage_it->obj_info();
6458
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
6459
6460
    S3Conf s3_conf;
6461
    if (stage_type == StagePB::EXTERNAL) {
6462
        if (stage_access_type == StagePB::AKSK) {
6463
            auto conf = S3Conf::from_obj_store_info(object_store_info);
6464
            if (!conf) {
6465
                return -1;
6466
            }
6467
6468
            s3_conf = std::move(*conf);
6469
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
6470
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
6471
            if (!conf) {
6472
                return -1;
6473
            }
6474
6475
            s3_conf = std::move(*conf);
6476
            if (instance_info_.ram_user().has_encryption_info()) {
6477
                AkSkPair plain_ak_sk_pair;
6478
                int ret = decrypt_ak_sk_helper(
6479
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
6480
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
6481
                if (ret != 0) {
6482
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
6483
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
6484
                    return -1;
6485
                }
6486
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
6487
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
6488
            } else {
6489
                s3_conf.ak = instance_info_.ram_user().ak();
6490
                s3_conf.sk = instance_info_.ram_user().sk();
6491
            }
6492
        } else {
6493
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
6494
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
6495
            return -1;
6496
        }
6497
    } else if (stage_type == StagePB::INTERNAL) {
6498
        int idx = stoi(object_store_info.id());
6499
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6500
            LOG(WARNING) << "invalid idx: " << idx;
6501
            return -1;
6502
        }
6503
6504
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
6505
        auto conf = S3Conf::from_obj_store_info(old_obj);
6506
        if (!conf) {
6507
            return -1;
6508
        }
6509
6510
        s3_conf = std::move(*conf);
6511
        s3_conf.prefix = object_store_info.prefix();
6512
    } else {
6513
        LOG(WARNING) << "unknown stage type " << stage_type;
6514
        return -1;
6515
    }
6516
6517
    std::shared_ptr<S3Accessor> s3_accessor;
6518
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
6519
    if (ret != 0) {
6520
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
6521
        return -1;
6522
    }
6523
6524
    *accessor = std::move(s3_accessor);
6525
#endif
6526
3
    return 0;
6527
5
}
6528
6529
11
int InstanceRecycler::recycle_stage() {
6530
11
    int64_t num_scanned = 0;
6531
11
    int64_t num_recycled = 0;
6532
11
    const std::string task_name = "recycle_stage";
6533
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6534
6535
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
6536
6537
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6538
11
    register_recycle_task(task_name, start_time);
6539
6540
11
    DORIS_CLOUD_DEFER {
6541
11
        unregister_recycle_task(task_name);
6542
11
        int64_t cost =
6543
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6544
11
        metrics_context.finish_report();
6545
11
        LOG_WARNING("recycle stage, cost={}s", cost)
6546
11
                .tag("instance_id", instance_id_)
6547
11
                .tag("num_scanned", num_scanned)
6548
11
                .tag("num_recycled", num_recycled);
6549
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
6540
11
    DORIS_CLOUD_DEFER {
6541
11
        unregister_recycle_task(task_name);
6542
11
        int64_t cost =
6543
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6544
11
        metrics_context.finish_report();
6545
11
        LOG_WARNING("recycle stage, cost={}s", cost)
6546
11
                .tag("instance_id", instance_id_)
6547
11
                .tag("num_scanned", num_scanned)
6548
11
                .tag("num_recycled", num_recycled);
6549
11
    };
6550
6551
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
6552
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
6553
11
    std::string key0 = recycle_stage_key(key_info0);
6554
11
    std::string key1 = recycle_stage_key(key_info1);
6555
6556
11
    std::vector<std::string_view> stage_keys;
6557
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
6558
11
                         this](std::string_view k, std::string_view v) -> int {
6559
1
        ++num_scanned;
6560
1
        RecycleStagePB recycle_stage;
6561
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
6562
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
6563
0
            return -1;
6564
0
        }
6565
6566
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
6567
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6568
0
            LOG(WARNING) << "invalid idx: " << idx;
6569
0
            return -1;
6570
0
        }
6571
6572
1
        std::shared_ptr<StorageVaultAccessor> accessor;
6573
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
6574
1
                [&] {
6575
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
6576
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
6577
1
                    if (!s3_conf) {
6578
1
                        return -1;
6579
1
                    }
6580
6581
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
6582
1
                    std::shared_ptr<S3Accessor> s3_accessor;
6583
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
6584
1
                    if (ret != 0) {
6585
1
                        return -1;
6586
1
                    }
6587
6588
1
                    accessor = std::move(s3_accessor);
6589
1
                    return 0;
6590
1
                }(),
6591
1
                "recycle_stage:get_accessor", &accessor);
6592
6593
1
        if (ret != 0) {
6594
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
6595
0
            return ret;
6596
0
        }
6597
6598
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
6599
1
                .tag("instance_id", instance_id_)
6600
1
                .tag("stage_id", recycle_stage.stage().stage_id())
6601
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
6602
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
6603
1
                .tag("obj_info_id", idx)
6604
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
6605
1
        ret = accessor->delete_all();
6606
1
        if (ret != 0) {
6607
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
6608
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
6609
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
6610
0
                         << ", ret=" << ret;
6611
0
            return -1;
6612
0
        }
6613
1
        metrics_context.total_recycled_num = ++num_recycled;
6614
1
        metrics_context.report();
6615
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
6616
1
        stage_keys.push_back(k);
6617
1
        return 0;
6618
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6558
1
                         this](std::string_view k, std::string_view v) -> int {
6559
1
        ++num_scanned;
6560
1
        RecycleStagePB recycle_stage;
6561
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
6562
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
6563
0
            return -1;
6564
0
        }
6565
6566
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
6567
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6568
0
            LOG(WARNING) << "invalid idx: " << idx;
6569
0
            return -1;
6570
0
        }
6571
6572
1
        std::shared_ptr<StorageVaultAccessor> accessor;
6573
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
6574
1
                [&] {
6575
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
6576
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
6577
1
                    if (!s3_conf) {
6578
1
                        return -1;
6579
1
                    }
6580
6581
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
6582
1
                    std::shared_ptr<S3Accessor> s3_accessor;
6583
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
6584
1
                    if (ret != 0) {
6585
1
                        return -1;
6586
1
                    }
6587
6588
1
                    accessor = std::move(s3_accessor);
6589
1
                    return 0;
6590
1
                }(),
6591
1
                "recycle_stage:get_accessor", &accessor);
6592
6593
1
        if (ret != 0) {
6594
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
6595
0
            return ret;
6596
0
        }
6597
6598
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
6599
1
                .tag("instance_id", instance_id_)
6600
1
                .tag("stage_id", recycle_stage.stage().stage_id())
6601
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
6602
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
6603
1
                .tag("obj_info_id", idx)
6604
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
6605
1
        ret = accessor->delete_all();
6606
1
        if (ret != 0) {
6607
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
6608
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
6609
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
6610
0
                         << ", ret=" << ret;
6611
0
            return -1;
6612
0
        }
6613
1
        metrics_context.total_recycled_num = ++num_recycled;
6614
1
        metrics_context.report();
6615
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
6616
1
        stage_keys.push_back(k);
6617
1
        return 0;
6618
1
    };
6619
6620
11
    auto loop_done = [&stage_keys, this]() -> int {
6621
1
        if (stage_keys.empty()) return 0;
6622
1
        DORIS_CLOUD_DEFER {
6623
1
            stage_keys.clear();
6624
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6622
1
        DORIS_CLOUD_DEFER {
6623
1
            stage_keys.clear();
6624
1
        };
6625
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
6626
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
6627
0
            return -1;
6628
0
        }
6629
1
        return 0;
6630
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
6620
1
    auto loop_done = [&stage_keys, this]() -> int {
6621
1
        if (stage_keys.empty()) return 0;
6622
1
        DORIS_CLOUD_DEFER {
6623
1
            stage_keys.clear();
6624
1
        };
6625
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
6626
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
6627
0
            return -1;
6628
0
        }
6629
1
        return 0;
6630
1
    };
6631
11
    if (config::enable_recycler_stats_metrics) {
6632
0
        scan_and_statistics_stage();
6633
0
    }
6634
    // recycle_func and loop_done for scan and recycle
6635
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
6636
11
}
6637
6638
10
int InstanceRecycler::recycle_expired_stage_objects() {
6639
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
6640
6641
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6642
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
6643
6644
10
    DORIS_CLOUD_DEFER {
6645
10
        int64_t cost =
6646
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6647
10
        metrics_context.finish_report();
6648
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
6649
10
                .tag("instance_id", instance_id_);
6650
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
6644
10
    DORIS_CLOUD_DEFER {
6645
10
        int64_t cost =
6646
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6647
10
        metrics_context.finish_report();
6648
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
6649
10
                .tag("instance_id", instance_id_);
6650
10
    };
6651
6652
10
    int ret = 0;
6653
6654
10
    if (config::enable_recycler_stats_metrics) {
6655
0
        scan_and_statistics_expired_stage_objects();
6656
0
    }
6657
6658
10
    for (const auto& stage : instance_info_.stages()) {
6659
0
        std::stringstream ss;
6660
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
6661
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
6662
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
6663
0
           << ", prefix=" << stage.obj_info().prefix();
6664
6665
0
        if (stopped()) {
6666
0
            break;
6667
0
        }
6668
0
        if (stage.type() == StagePB::EXTERNAL) {
6669
0
            continue;
6670
0
        }
6671
0
        int idx = stoi(stage.obj_info().id());
6672
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6673
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
6674
0
            continue;
6675
0
        }
6676
6677
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
6678
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
6679
0
        if (!s3_conf) {
6680
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
6681
0
            continue;
6682
0
        }
6683
6684
0
        s3_conf->prefix = stage.obj_info().prefix();
6685
0
        std::shared_ptr<S3Accessor> accessor;
6686
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
6687
0
        if (ret1 != 0) {
6688
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
6689
0
            ret = -1;
6690
0
            continue;
6691
0
        }
6692
6693
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
6694
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
6695
0
            ret = -1;
6696
0
            continue;
6697
0
        }
6698
6699
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
6700
0
        int64_t expiration_time =
6701
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
6702
0
                config::internal_stage_objects_expire_time_second;
6703
0
        if (config::force_immediate_recycle) {
6704
0
            expiration_time = INT64_MAX;
6705
0
        }
6706
0
        ret1 = accessor->delete_all(expiration_time);
6707
0
        if (ret1 != 0) {
6708
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
6709
0
                         << ss.str();
6710
0
            ret = -1;
6711
0
            continue;
6712
0
        }
6713
0
        metrics_context.total_recycled_num++;
6714
0
        metrics_context.report();
6715
0
    }
6716
10
    return ret;
6717
10
}
6718
6719
181
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
6720
181
    std::lock_guard lock(recycle_tasks_mutex);
6721
181
    running_recycle_tasks[task_name] = start_time;
6722
181
}
6723
6724
181
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
6725
181
    std::lock_guard lock(recycle_tasks_mutex);
6726
181
    DCHECK(running_recycle_tasks[task_name] > 0);
6727
181
    running_recycle_tasks.erase(task_name);
6728
181
}
6729
6730
21
bool InstanceRecycler::check_recycle_tasks() {
6731
21
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
6732
21
    {
6733
21
        std::lock_guard lock(recycle_tasks_mutex);
6734
21
        tmp_running_recycle_tasks = running_recycle_tasks;
6735
21
    }
6736
6737
21
    bool found = false;
6738
21
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6739
21
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
6740
20
        int64_t cost = now - start_time;
6741
20
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
6742
20
            LOG_INFO("recycle task cost too much time cost={}s", cost)
6743
20
                    .tag("instance_id", instance_id_)
6744
20
                    .tag("task", task_name);
6745
20
            found = true;
6746
20
        }
6747
20
    }
6748
6749
21
    return found;
6750
21
}
6751
6752
// Scan and statistics indexes that need to be recycled
6753
0
int InstanceRecycler::scan_and_statistics_indexes() {
6754
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
6755
6756
0
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
6757
0
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
6758
0
    std::string index_key0;
6759
0
    std::string index_key1;
6760
0
    recycle_index_key(index_key_info0, &index_key0);
6761
0
    recycle_index_key(index_key_info1, &index_key1);
6762
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6763
6764
0
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
6765
0
        RecycleIndexPB index_pb;
6766
0
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
6767
0
            return 0;
6768
0
        }
6769
0
        int64_t current_time = ::time(nullptr);
6770
0
        if (current_time <
6771
0
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
6772
0
            return 0;
6773
0
        }
6774
        // decode index_id
6775
0
        auto k1 = k;
6776
0
        k1.remove_prefix(1);
6777
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6778
0
        decode_key(&k1, &out);
6779
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
6780
0
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
6781
0
        std::unique_ptr<Transaction> txn;
6782
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6783
0
        if (err != TxnErrorCode::TXN_OK) {
6784
0
            return 0;
6785
0
        }
6786
0
        std::string val;
6787
0
        err = txn->get(k, &val);
6788
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6789
0
            return 0;
6790
0
        }
6791
0
        if (err != TxnErrorCode::TXN_OK) {
6792
0
            return 0;
6793
0
        }
6794
0
        index_pb.Clear();
6795
0
        if (!index_pb.ParseFromString(val)) {
6796
0
            return 0;
6797
0
        }
6798
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
6799
0
            return 0;
6800
0
        }
6801
0
        metrics_context.total_need_recycle_num++;
6802
0
        return 0;
6803
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_
6804
6805
0
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
6806
0
    metrics_context.report(true);
6807
0
    segment_metrics_context_.report(true);
6808
0
    tablet_metrics_context_.report(true);
6809
0
    return ret;
6810
0
}
6811
6812
// Scan and statistics partitions that need to be recycled
6813
0
int InstanceRecycler::scan_and_statistics_partitions() {
6814
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
6815
6816
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
6817
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
6818
0
    std::string part_key0;
6819
0
    std::string part_key1;
6820
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6821
6822
0
    recycle_partition_key(part_key_info0, &part_key0);
6823
0
    recycle_partition_key(part_key_info1, &part_key1);
6824
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
6825
0
        RecyclePartitionPB part_pb;
6826
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
6827
0
            return 0;
6828
0
        }
6829
0
        int64_t current_time = ::time(nullptr);
6830
0
        if (current_time <
6831
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
6832
0
            return 0;
6833
0
        }
6834
        // decode partition_id
6835
0
        auto k1 = k;
6836
0
        k1.remove_prefix(1);
6837
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6838
0
        decode_key(&k1, &out);
6839
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
6840
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
6841
        // Change state to RECYCLING
6842
0
        std::unique_ptr<Transaction> txn;
6843
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6844
0
        if (err != TxnErrorCode::TXN_OK) {
6845
0
            return 0;
6846
0
        }
6847
0
        std::string val;
6848
0
        err = txn->get(k, &val);
6849
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6850
0
            return 0;
6851
0
        }
6852
0
        if (err != TxnErrorCode::TXN_OK) {
6853
0
            return 0;
6854
0
        }
6855
0
        part_pb.Clear();
6856
0
        if (!part_pb.ParseFromString(val)) {
6857
0
            return 0;
6858
0
        }
6859
        // Partitions with PREPARED state MUST have no data
6860
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
6861
0
        int ret = 0;
6862
0
        for (int64_t index_id : part_pb.index_id()) {
6863
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
6864
0
                                            partition_id, is_empty_tablet) != 0) {
6865
0
                ret = 0;
6866
0
            }
6867
0
        }
6868
0
        metrics_context.total_need_recycle_num++;
6869
0
        return ret;
6870
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_
6871
6872
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
6873
0
    metrics_context.report(true);
6874
0
    segment_metrics_context_.report(true);
6875
0
    tablet_metrics_context_.report(true);
6876
0
    return ret;
6877
0
}
6878
6879
// Scan and statistics rowsets that need to be recycled
6880
0
int InstanceRecycler::scan_and_statistics_rowsets() {
6881
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
6882
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
6883
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
6884
0
    std::string recyc_rs_key0;
6885
0
    std::string recyc_rs_key1;
6886
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
6887
0
                recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
6888
0
       int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6889
6890
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6891
0
        RecycleRowsetPB rowset;
6892
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6893
0
            return 0;
6894
0
        }
6895
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
6896
0
        int64_t current_time = ::time(nullptr);
6897
0
        if (current_time <
6898
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
6899
0
            return 0;
6900
0
        }
6901
6902
0
        if (!rowset.has_type()) {
6903
0
            if (!rowset.has_resource_id()) [[unlikely]] {
6904
0
                return 0;
6905
0
            }
6906
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6907
0
                return 0;
6908
0
            }
6909
0
            metrics_context.total_need_recycle_num++;
6910
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
6911
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
6912
0
            segment_metrics_context_.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
6913
0
            return 0;
6914
0
        }
6915
6916
0
        if(!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled()) {
6917
0
            return 0;
6918
0
        }
6919
6920
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
6921
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
6922
0
                return 0;
6923
0
            }
6924
0
        }
6925
0
        metrics_context.total_need_recycle_num++;
6926
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
6927
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
6928
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
6929
0
        return 0;
6930
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_
6931
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
6932
0
    metrics_context.report(true);
6933
0
    segment_metrics_context_.report(true);
6934
0
    return ret;
6935
0
}
6936
6937
// Scan and statistics tmp_rowsets that need to be recycled
6938
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
6939
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
6940
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
6941
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
6942
0
    std::string tmp_rs_key0;
6943
0
    std::string tmp_rs_key1;
6944
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
6945
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
6946
6947
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6948
6949
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
6950
0
        doris::RowsetMetaCloudPB rowset;
6951
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6952
0
            return 0;
6953
0
        }
6954
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6955
0
        int64_t current_time = ::time(nullptr);
6956
0
        if (current_time < expiration) {
6957
0
            return 0;
6958
0
        }
6959
6960
0
        DCHECK_GT(rowset.txn_id(), 0)
6961
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
6962
6963
0
        if(!rowset.has_is_recycled() || !rowset.is_recycled()) {
6964
0
            return 0;
6965
0
        }
6966
6967
0
        if (!rowset.has_resource_id()) {
6968
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6969
0
                return 0;
6970
0
            }
6971
0
            return 0;
6972
0
        }
6973
6974
0
        metrics_context.total_need_recycle_num++;
6975
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
6976
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
6977
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
6978
0
        return 0;
6979
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_
6980
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
6981
0
    metrics_context.report(true);
6982
0
    segment_metrics_context_.report(true);
6983
0
    return ret;
6984
0
}
6985
6986
// Scan and statistics abort_timeout_txn that need to be recycled
6987
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
6988
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
6989
6990
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6991
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6992
0
    std::string begin_txn_running_key;
6993
0
    std::string end_txn_running_key;
6994
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6995
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6996
6997
0
    int64_t current_time =
6998
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6999
7000
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
7001
0
                                               std::string_view k, std::string_view v) -> int {
7002
0
        std::unique_ptr<Transaction> txn;
7003
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7004
0
        if (err != TxnErrorCode::TXN_OK) {
7005
0
            return 0;
7006
0
        }
7007
0
        std::string_view k1 = k;
7008
0
        k1.remove_prefix(1);
7009
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7010
0
        if (decode_key(&k1, &out) != 0) {
7011
0
            return 0;
7012
0
        }
7013
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7014
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7015
        // Update txn_info
7016
0
        std::string txn_inf_key, txn_inf_val;
7017
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
7018
0
        err = txn->get(txn_inf_key, &txn_inf_val);
7019
0
        if (err != TxnErrorCode::TXN_OK) {
7020
0
            return 0;
7021
0
        }
7022
0
        TxnInfoPB txn_info;
7023
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
7024
0
            return 0;
7025
0
        }
7026
7027
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
7028
0
            TxnRunningPB txn_running_pb;
7029
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7030
0
                return 0;
7031
0
            }
7032
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7033
0
                return 0;
7034
0
            }
7035
0
            metrics_context.total_need_recycle_num++;
7036
0
        }
7037
0
        return 0;
7038
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_
7039
7040
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key, std::move(handle_abort_timeout_txn_kv));
7041
0
    metrics_context.report(true);
7042
0
    return ret;
7043
0
}
7044
7045
// Scan and statistics expired_txn_label that need to be recycled
7046
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
7047
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
7048
7049
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7050
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7051
0
    std::string begin_recycle_txn_key;
7052
0
    std::string end_recycle_txn_key;
7053
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7054
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7055
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7056
0
    int64_t current_time_ms =
7057
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7058
7059
    // for calculate the total num or bytes of recyled objects
7060
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
7061
0
        RecycleTxnPB recycle_txn_pb;
7062
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7063
0
            return 0;
7064
0
        }
7065
0
        if ((config::force_immediate_recycle) ||
7066
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7067
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7068
0
             current_time_ms)) {
7069
0
            metrics_context.total_need_recycle_num++;
7070
0
        }
7071
0
        return 0;
7072
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_
7073
7074
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key, std::move(handle_expired_txn_label_kv));
7075
0
    metrics_context.report(true);
7076
0
    return ret;
7077
0
}
7078
7079
// Scan and statistics copy_jobs that need to be recycled
7080
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
7081
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
7082
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7083
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7084
0
    std::string key0;
7085
0
    std::string key1;
7086
0
    copy_job_key(key_info0, &key0);
7087
0
    copy_job_key(key_info1, &key1);
7088
7089
    // for calculate the total num or bytes of recyled objects
7090
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
7091
0
        CopyJobPB copy_job;
7092
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7093
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7094
0
            return 0;
7095
0
        }
7096
7097
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7098
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
7099
0
                int64_t current_time =
7100
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7101
0
                if (copy_job.finish_time_ms() > 0) {
7102
0
                    if (!config::force_immediate_recycle &&
7103
0
                        current_time < copy_job.finish_time_ms() +
7104
0
                                               config::copy_job_max_retention_second * 1000) {
7105
0
                        return 0;
7106
0
                    }
7107
0
                } else {
7108
0
                    if (!config::force_immediate_recycle &&
7109
0
                        current_time < copy_job.start_time_ms() +
7110
0
                                               config::copy_job_max_retention_second * 1000) {
7111
0
                        return 0;
7112
0
                    }
7113
0
                }
7114
0
            }
7115
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7116
0
            int64_t current_time =
7117
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7118
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7119
0
                return 0;
7120
0
            }
7121
0
        }
7122
0
        metrics_context.total_need_recycle_num++;
7123
0
        return 0;
7124
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_
7125
7126
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7127
0
    metrics_context.report(true);
7128
0
    return ret;
7129
0
}
7130
7131
// Scan and statistics stage that need to be recycled
7132
0
int InstanceRecycler::scan_and_statistics_stage() {
7133
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
7134
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7135
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7136
0
    std::string key0 = recycle_stage_key(key_info0);
7137
0
    std::string key1 = recycle_stage_key(key_info1);
7138
7139
    // for calculate the total num or bytes of recyled objects
7140
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
7141
0
                                                        std::string_view v) -> int {
7142
0
        RecycleStagePB recycle_stage;
7143
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7144
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7145
0
            return 0;
7146
0
        }
7147
7148
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
7149
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7150
0
            LOG(WARNING) << "invalid idx: " << idx;
7151
0
            return 0;
7152
0
        }
7153
7154
0
        std::shared_ptr<StorageVaultAccessor> accessor;
7155
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7156
0
                [&] {
7157
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7158
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7159
0
                    if (!s3_conf) {
7160
0
                        return 0;
7161
0
                    }
7162
7163
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7164
0
                    std::shared_ptr<S3Accessor> s3_accessor;
7165
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7166
0
                    if (ret != 0) {
7167
0
                        return 0;
7168
0
                    }
7169
7170
0
                    accessor = std::move(s3_accessor);
7171
0
                    return 0;
7172
0
                }(),
7173
0
                "recycle_stage:get_accessor", &accessor);
7174
7175
0
        if (ret != 0) {
7176
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7177
0
            return 0;
7178
0
        }
7179
7180
0
        metrics_context.total_need_recycle_num++;
7181
0
        return 0;
7182
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_
7183
7184
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7185
0
    metrics_context.report(true);
7186
0
    return ret;
7187
0
}
7188
7189
// Scan and statistics expired_stage_objects that need to be recycled
7190
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
7191
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7192
7193
    // for calculate the total num or bytes of recyled objects
7194
0
    auto scan_and_statistics = [&metrics_context, this]() {
7195
0
        for (const auto& stage : instance_info_.stages()) {
7196
0
            if (stopped()) {
7197
0
                break;
7198
0
            }
7199
0
            if (stage.type() == StagePB::EXTERNAL) {
7200
0
                continue;
7201
0
            }
7202
0
            int idx = stoi(stage.obj_info().id());
7203
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
7204
0
                continue;
7205
0
            }
7206
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
7207
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7208
0
            if (!s3_conf) {
7209
0
                continue;
7210
0
            }
7211
0
            s3_conf->prefix = stage.obj_info().prefix();
7212
0
            std::shared_ptr<S3Accessor> accessor;
7213
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
7214
0
            if (ret1 != 0) {
7215
0
                continue;
7216
0
            }
7217
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7218
0
                continue;
7219
0
            }
7220
0
            metrics_context.total_need_recycle_num++;
7221
0
        }
7222
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
7223
7224
0
    scan_and_statistics();
7225
0
    metrics_context.report(true);
7226
0
    return 0;
7227
0
}
7228
7229
// Scan and statistics versions that need to be recycled
7230
0
int InstanceRecycler::scan_and_statistics_versions() {
7231
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
7232
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
7233
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
7234
7235
0
    int64_t last_scanned_table_id = 0;
7236
0
    bool is_recycled = false; // Is last scanned kv recycled
7237
    // for calculate the total num or bytes of recyled objects
7238
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
7239
0
                                       std::string_view k, std::string_view) {
7240
0
        auto k1 = k;
7241
0
        k1.remove_prefix(1);
7242
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
7243
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7244
0
        decode_key(&k1, &out);
7245
0
        DCHECK_EQ(out.size(), 6) << k;
7246
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
7247
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
7248
0
            metrics_context.total_need_recycle_num +=
7249
0
                    is_recycled; // Version kv of this table has been recycled
7250
0
            return 0;
7251
0
        }
7252
0
        last_scanned_table_id = table_id;
7253
0
        is_recycled = false;
7254
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
7255
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
7256
0
        std::unique_ptr<Transaction> txn;
7257
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7258
0
        if (err != TxnErrorCode::TXN_OK) {
7259
0
            return 0;
7260
0
        }
7261
0
        std::unique_ptr<RangeGetIterator> iter;
7262
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
7263
0
        if (err != TxnErrorCode::TXN_OK) {
7264
0
            return 0;
7265
0
        }
7266
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
7267
0
            return 0;
7268
0
        }
7269
0
        metrics_context.total_need_recycle_num++;
7270
0
        is_recycled = true;
7271
0
        return 0;
7272
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_
7273
7274
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
7275
0
    metrics_context.report(true);
7276
0
    return ret;
7277
0
}
7278
7279
// Scan and statistics restore jobs that need to be recycled
7280
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
7281
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
7282
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
7283
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
7284
0
    std::string restore_job_key0;
7285
0
    std::string restore_job_key1;
7286
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
7287
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
7288
7289
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7290
7291
    // for calculate the total num or bytes of recyled objects
7292
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
7293
0
        RestoreJobCloudPB restore_job_pb;
7294
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
7295
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
7296
0
            return 0;
7297
0
        }
7298
0
        int64_t expiration =
7299
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
7300
0
        int64_t current_time = ::time(nullptr);
7301
0
        if (current_time < expiration) { // not expired
7302
0
            return 0;
7303
0
        }
7304
0
        metrics_context.total_need_recycle_num++;
7305
0
        if(restore_job_pb.need_recycle_data()) {
7306
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
7307
0
        }
7308
0
        return 0;
7309
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_
7310
7311
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
7312
0
    metrics_context.report(true);
7313
0
    return ret;
7314
0
}
7315
7316
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
7317
3
    if (!should_recycle_versioned_keys()) {
7318
0
        return;
7319
0
    }
7320
7321
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
7322
7323
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
7324
3
    if (recycle_checker.init() != 0) {
7325
0
        return;
7326
0
    }
7327
7328
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
7329
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
7330
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
7331
7332
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
7333
8
    for (; iter->valid(); iter->next()) {
7334
5
        OperationLogPB operation_log;
7335
5
        if (!iter->parse_value(&operation_log)) {
7336
0
            continue;
7337
0
        }
7338
7339
5
        std::string_view key = iter->key();
7340
5
        Versionstamp log_versionstamp;
7341
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
7342
0
            continue;
7343
0
        }
7344
7345
5
        OperationLogReferenceInfo ref_info;
7346
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
7347
5
                                         &ref_info)) {
7348
4
            metrics_context.total_need_recycle_num++;
7349
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
7350
4
        }
7351
5
    }
7352
7353
3
    metrics_context.report(true);
7354
3
}
7355
7356
int InstanceRecycler::classify_rowset_task_by_ref_count(
7357
60
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
7358
60
    constexpr int MAX_RETRY = 10;
7359
60
    const auto& rowset_meta = task.rowset_meta;
7360
60
    int64_t tablet_id = rowset_meta.tablet_id();
7361
60
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
7362
60
    std::string_view reference_instance_id = instance_id_;
7363
60
    if (rowset_meta.has_reference_instance_id()) {
7364
5
        reference_instance_id = rowset_meta.reference_instance_id();
7365
5
    }
7366
7367
61
    for (int i = 0; i < MAX_RETRY; ++i) {
7368
61
        std::unique_ptr<Transaction> txn;
7369
61
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7370
61
        if (err != TxnErrorCode::TXN_OK) {
7371
0
            LOG_WARNING("failed to create txn when classifying rowset task")
7372
0
                    .tag("instance_id", instance_id_)
7373
0
                    .tag("tablet_id", tablet_id)
7374
0
                    .tag("rowset_id", rowset_id)
7375
0
                    .tag("err", err);
7376
0
            return -1;
7377
0
        }
7378
7379
61
        std::string rowset_ref_count_key =
7380
61
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
7381
61
        task.rowset_ref_count_key = rowset_ref_count_key;
7382
7383
61
        int64_t ref_count = 0;
7384
61
        {
7385
61
            std::string value;
7386
61
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
7387
61
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7388
0
                ref_count = 1;
7389
61
            } else if (err != TxnErrorCode::TXN_OK) {
7390
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
7391
0
                        .tag("instance_id", instance_id_)
7392
0
                        .tag("tablet_id", tablet_id)
7393
0
                        .tag("rowset_id", rowset_id)
7394
0
                        .tag("err", err);
7395
0
                return -1;
7396
61
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
7397
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
7398
0
                        .tag("instance_id", instance_id_)
7399
0
                        .tag("tablet_id", tablet_id)
7400
0
                        .tag("rowset_id", rowset_id)
7401
0
                        .tag("value", hex(value));
7402
0
                return -1;
7403
0
            }
7404
61
        }
7405
7406
61
        if (ref_count > 1) {
7407
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
7408
12
            txn->atomic_add(rowset_ref_count_key, -1);
7409
12
            LOG_INFO("decrease rowset data ref count in classification phase")
7410
12
                    .tag("instance_id", instance_id_)
7411
12
                    .tag("tablet_id", tablet_id)
7412
12
                    .tag("rowset_id", rowset_id)
7413
12
                    .tag("ref_count", ref_count - 1)
7414
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
7415
7416
12
            if (!task.recycle_rowset_key.empty()) {
7417
12
                txn->remove(task.recycle_rowset_key);
7418
12
                LOG_INFO("remove recycle rowset key in classification phase")
7419
12
                        .tag("key", hex(task.recycle_rowset_key));
7420
12
            }
7421
12
            if (!task.non_versioned_rowset_key.empty()) {
7422
12
                txn->remove(task.non_versioned_rowset_key);
7423
12
                LOG_INFO("remove non versioned rowset key in classification phase")
7424
12
                        .tag("key", hex(task.non_versioned_rowset_key));
7425
12
            }
7426
7427
12
            err = txn->commit();
7428
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
7429
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
7430
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
7431
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
7432
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
7433
1
                continue;
7434
11
            } else if (err != TxnErrorCode::TXN_OK) {
7435
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
7436
0
                        .tag("instance_id", instance_id_)
7437
0
                        .tag("tablet_id", tablet_id)
7438
0
                        .tag("rowset_id", rowset_id)
7439
0
                        .tag("err", err);
7440
0
                return -1;
7441
0
            }
7442
11
            return 1; // handled, not added to batch delete
7443
49
        } else {
7444
            // ref_count == 1: Add to batch delete plan without modifying any KV.
7445
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
7446
49
            LOG_INFO("add rowset to batch delete plan")
7447
49
                    .tag("instance_id", instance_id_)
7448
49
                    .tag("tablet_id", tablet_id)
7449
49
                    .tag("rowset_id", rowset_id)
7450
49
                    .tag("resource_id", rowset_meta.resource_id())
7451
49
                    .tag("ref_count", ref_count);
7452
7453
49
            batch_delete_tasks.push_back(std::move(task));
7454
49
            return 0; // added to batch delete
7455
49
        }
7456
61
    }
7457
7458
0
    LOG_WARNING("failed to classify rowset task after retry")
7459
0
            .tag("instance_id", instance_id_)
7460
0
            .tag("tablet_id", tablet_id)
7461
0
            .tag("rowset_id", rowset_id)
7462
0
            .tag("retry", MAX_RETRY);
7463
0
    return -1;
7464
60
}
7465
7466
10
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
7467
10
    int ret = 0;
7468
49
    for (const auto& task : tasks) {
7469
49
        int64_t tablet_id = task.rowset_meta.tablet_id();
7470
49
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
7471
7472
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
7473
        // so we don't need to call it again here.
7474
7475
        // Remove all metadata keys in one transaction
7476
49
        std::unique_ptr<Transaction> txn;
7477
49
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7478
49
        if (err != TxnErrorCode::TXN_OK) {
7479
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
7480
0
                    .tag("instance_id", instance_id_)
7481
0
                    .tag("tablet_id", tablet_id)
7482
0
                    .tag("rowset_id", rowset_id)
7483
0
                    .tag("err", err);
7484
0
            ret = -1;
7485
0
            continue;
7486
0
        }
7487
7488
49
        std::string_view reference_instance_id = instance_id_;
7489
49
        if (task.rowset_meta.has_reference_instance_id()) {
7490
5
            reference_instance_id = task.rowset_meta.reference_instance_id();
7491
5
        }
7492
7493
49
        txn->remove(task.rowset_ref_count_key);
7494
49
        LOG_INFO("delete rowset data ref count key in cleanup phase")
7495
49
                .tag("instance_id", instance_id_)
7496
49
                .tag("tablet_id", tablet_id)
7497
49
                .tag("rowset_id", rowset_id)
7498
49
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
7499
7500
49
        std::string dbm_start_key =
7501
49
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
7502
49
        std::string dbm_end_key = meta_delete_bitmap_key(
7503
49
                {reference_instance_id, tablet_id, rowset_id,
7504
49
                 std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
7505
49
        txn->remove(dbm_start_key, dbm_end_key);
7506
49
        LOG_INFO("remove delete bitmap kv in cleanup phase")
7507
49
                .tag("instance_id", instance_id_)
7508
49
                .tag("tablet_id", tablet_id)
7509
49
                .tag("rowset_id", rowset_id)
7510
49
                .tag("begin", hex(dbm_start_key))
7511
49
                .tag("end", hex(dbm_end_key));
7512
7513
49
        std::string versioned_dbm_start_key =
7514
49
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
7515
49
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
7516
49
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
7517
49
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
7518
49
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
7519
49
                .tag("instance_id", instance_id_)
7520
49
                .tag("tablet_id", tablet_id)
7521
49
                .tag("rowset_id", rowset_id)
7522
49
                .tag("begin", hex(versioned_dbm_start_key))
7523
49
                .tag("end", hex(versioned_dbm_end_key));
7524
7525
        // Remove versioned meta rowset key
7526
49
        if (!task.versioned_rowset_key.empty()) {
7527
49
            std::string versioned_rowset_key_end = task.versioned_rowset_key;
7528
49
            encode_int64(INT64_MAX, &versioned_rowset_key_end);
7529
49
            txn->remove(task.versioned_rowset_key, versioned_rowset_key_end);
7530
49
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
7531
49
                    .tag("instance_id", instance_id_)
7532
49
                    .tag("tablet_id", tablet_id)
7533
49
                    .tag("rowset_id", rowset_id)
7534
49
                    .tag("begin", hex(task.versioned_rowset_key))
7535
49
                    .tag("end", hex(versioned_rowset_key_end));
7536
49
        }
7537
7538
49
        if (!task.non_versioned_rowset_key.empty()) {
7539
49
            txn->remove(task.non_versioned_rowset_key);
7540
49
            LOG_INFO("remove non versioned rowset key in cleanup phase")
7541
49
                    .tag("instance_id", instance_id_)
7542
49
                    .tag("tablet_id", tablet_id)
7543
49
                    .tag("rowset_id", rowset_id)
7544
49
                    .tag("key", hex(task.non_versioned_rowset_key));
7545
49
        }
7546
7547
        // Remove recycle_rowset_key last to ensure retry safety:
7548
        // if cleanup fails, this key remains and triggers next round retry.
7549
49
        if (!task.recycle_rowset_key.empty()) {
7550
49
            txn->remove(task.recycle_rowset_key);
7551
49
            LOG_INFO("remove recycle rowset key in cleanup phase")
7552
49
                    .tag("instance_id", instance_id_)
7553
49
                    .tag("tablet_id", tablet_id)
7554
49
                    .tag("rowset_id", rowset_id)
7555
49
                    .tag("key", hex(task.recycle_rowset_key));
7556
49
        }
7557
7558
49
        err = txn->commit();
7559
49
        if (err != TxnErrorCode::TXN_OK) {
7560
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
7561
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
7562
0
                    .tag("instance_id", instance_id_)
7563
0
                    .tag("tablet_id", tablet_id)
7564
0
                    .tag("rowset_id", rowset_id)
7565
0
                    .tag("err", err);
7566
0
            ret = -1;
7567
0
            continue;
7568
0
        }
7569
7570
49
        LOG_INFO("cleanup rowset metadata success")
7571
49
                .tag("instance_id", instance_id_)
7572
49
                .tag("tablet_id", tablet_id)
7573
49
                .tag("rowset_id", rowset_id);
7574
49
    }
7575
10
    return ret;
7576
10
}
7577
7578
} // namespace doris::cloud