Coverage Report

Created: 2026-04-14 03:35

/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
337
                   std::unique_ptr<RangeGetIterator>& it) {
120
337
    std::unique_ptr<Transaction> txn;
121
337
    TxnErrorCode err = txn_kv->create_txn(&txn);
122
337
    if (err != TxnErrorCode::TXN_OK) {
123
0
        return -1;
124
0
    }
125
337
    switch (txn->get(begin, end, &it, true)) {
126
337
    case TxnErrorCode::TXN_OK:
127
337
        return 0;
128
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
129
0
        return 1;
130
0
    default:
131
0
        return -1;
132
337
    };
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
306
                   std::unique_ptr<RangeGetIterator>& it) {
120
306
    std::unique_ptr<Transaction> txn;
121
306
    TxnErrorCode err = txn_kv->create_txn(&txn);
122
306
    if (err != TxnErrorCode::TXN_OK) {
123
0
        return -1;
124
0
    }
125
306
    switch (txn->get(begin, end, &it, true)) {
126
306
    case TxnErrorCode::TXN_OK:
127
306
        return 0;
128
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
129
0
        return 1;
130
0
    default:
131
0
        return -1;
132
306
    };
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
125
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
157
125
    std::unique_ptr<Transaction> txn;
158
125
    TxnErrorCode err = txn_kv->create_txn(&txn);
159
125
    if (err != TxnErrorCode::TXN_OK) {
160
0
        return -1;
161
0
    }
162
106k
    for (auto& k : keys) {
163
106k
        txn->remove(k);
164
106k
    }
165
125
    switch (txn->commit()) {
166
125
    case TxnErrorCode::TXN_OK:
167
125
        return 0;
168
0
    case TxnErrorCode::TXN_CONFLICT:
169
0
        return -1;
170
0
    default:
171
0
        return -1;
172
125
    }
173
125
}
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
92
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
157
92
    std::unique_ptr<Transaction> txn;
158
92
    TxnErrorCode err = txn_kv->create_txn(&txn);
159
92
    if (err != TxnErrorCode::TXN_OK) {
160
0
        return -1;
161
0
    }
162
106k
    for (auto& k : keys) {
163
106k
        txn->remove(k);
164
106k
    }
165
92
    switch (txn->commit()) {
166
92
    case TxnErrorCode::TXN_OK:
167
92
        return 0;
168
0
    case TxnErrorCode::TXN_CONFLICT:
169
0
        return -1;
170
0
    default:
171
0
        return -1;
172
92
    }
173
92
}
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
36
        InstanceInfoPB instance;
282
36
        {
283
36
            std::unique_lock lock(mtx_);
284
36
            pending_instance_cond_.wait(
285
48
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
285
48
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
286
36
            if (stopped()) {
287
6
                return;
288
6
            }
289
30
            instance = std::move(pending_instance_queue_.front());
290
30
            pending_instance_queue_.pop_front();
291
30
            pending_instance_set_.erase(instance.instance_id());
292
30
        }
293
0
        auto& instance_id = instance.instance_id();
294
30
        {
295
30
            std::lock_guard lock(mtx_);
296
            // skip instance in recycling
297
30
            if (recycling_instance_map_.count(instance_id)) continue;
298
30
        }
299
30
        auto instance_recycler = std::make_shared<InstanceRecycler>(
300
30
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
301
302
30
        if (int r = instance_recycler->init(); r != 0) {
303
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
304
0
                         << " ret=" << r;
305
0
            continue;
306
0
        }
307
30
        std::string recycle_job_key;
308
30
        job_recycle_key({instance_id}, &recycle_job_key);
309
30
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
310
30
                                               ip_port_, config::recycle_interval_seconds * 1000);
311
30
        if (ret != 0) { // Prepare failed
312
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
313
20
                         << " ret=" << ret;
314
20
            continue;
315
20
        } else {
316
10
            std::lock_guard lock(mtx_);
317
10
            recycling_instance_map_.emplace(instance_id, instance_recycler);
318
10
        }
319
10
        if (stopped()) return;
320
10
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
321
10
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
322
10
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
323
10
        g_bvar_recycler_instance_recycle_task_status.put({"submitted"}, 1);
324
10
        ret = instance_recycler->do_recycle();
325
        // If instance recycler has been aborted, don't finish this job
326
327
10
        if (!instance_recycler->stopped()) {
328
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
329
10
                                        ret == 0, ctime_ms);
330
10
        }
331
10
        if (instance_recycler->stopped() || ret != 0) {
332
0
            g_bvar_recycler_instance_recycle_task_status.put({"error"}, 1);
333
0
        }
334
10
        {
335
10
            std::lock_guard lock(mtx_);
336
10
            recycling_instance_map_.erase(instance_id);
337
10
        }
338
339
10
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
340
10
        auto elpased_ms = now - ctime_ms;
341
10
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
342
10
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
343
10
        g_bvar_recycler_instance_next_ts.put({instance_id},
344
10
                                             now + config::recycle_interval_seconds * 1000);
345
10
        g_bvar_recycler_instance_recycle_task_status.put({"completed"}, 1);
346
10
        LOG(INFO) << "recycle instance done, "
347
10
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
348
10
                  << " now: " << now;
349
350
10
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
351
352
10
        LOG_WARNING("finish recycle instance")
353
10
                .tag("instance_id", instance_id)
354
10
                .tag("cost_ms", elpased_ms);
355
10
    }
356
8
}
357
358
4
void Recycler::lease_recycle_jobs() {
359
54
    while (!stopped()) {
360
50
        std::vector<std::string> instances;
361
50
        instances.reserve(recycling_instance_map_.size());
362
50
        {
363
50
            std::lock_guard lock(mtx_);
364
50
            for (auto& [id, _] : recycling_instance_map_) {
365
30
                instances.push_back(id);
366
30
            }
367
50
        }
368
50
        for (auto& i : instances) {
369
30
            std::string recycle_job_key;
370
30
            job_recycle_key({i}, &recycle_job_key);
371
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
372
30
            if (ret == 1) {
373
0
                std::lock_guard lock(mtx_);
374
0
                if (auto it = recycling_instance_map_.find(i);
375
0
                    it != recycling_instance_map_.end()) {
376
0
                    it->second->stop();
377
0
                }
378
0
            }
379
30
        }
380
50
        {
381
50
            std::unique_lock lock(mtx_);
382
50
            notifier_.wait_for(lock,
383
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
384
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
384
100
                               [&]() { return stopped(); });
385
50
        }
386
50
    }
387
4
}
388
389
4
void Recycler::check_recycle_tasks() {
390
7
    while (!stopped()) {
391
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
392
3
        {
393
3
            std::lock_guard lock(mtx_);
394
3
            recycling_instance_map = recycling_instance_map_;
395
3
        }
396
3
        for (auto& entry : recycling_instance_map) {
397
0
            entry.second->check_recycle_tasks();
398
0
        }
399
400
3
        std::unique_lock lock(mtx_);
401
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
402
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
402
6
                           [&]() { return stopped(); });
403
3
    }
404
4
}
405
406
4
int Recycler::start(brpc::Server* server) {
407
4
    instance_filter_.reset(config::recycle_whitelist, config::recycle_blacklist);
408
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
409
4
    S3Environment::getInstance();
410
411
4
    if (config::enable_checker) {
412
0
        checker_ = std::make_unique<Checker>(txn_kv_);
413
0
        int ret = checker_->start();
414
0
        std::string msg;
415
0
        if (ret != 0) {
416
0
            msg = "failed to start checker";
417
0
            LOG(ERROR) << msg;
418
0
            std::cerr << msg << std::endl;
419
0
            return ret;
420
0
        }
421
0
        msg = "checker started";
422
0
        LOG(INFO) << msg;
423
0
        std::cout << msg << std::endl;
424
0
    }
425
426
4
    if (server) {
427
        // Add service
428
1
        auto recycler_service =
429
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
430
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
431
1
    }
432
433
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
433
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
434
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
435
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
435
8
        workers_.emplace_back([this] { recycle_callback(); });
436
8
    }
437
438
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
439
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
440
441
4
    if (config::enable_snapshot_data_migrator) {
442
0
        snapshot_data_migrator_ = std::make_shared<SnapshotDataMigrator>(txn_kv_);
443
0
        int ret = snapshot_data_migrator_->start();
444
0
        if (ret != 0) {
445
0
            LOG(ERROR) << "failed to start snapshot data migrator";
446
0
            return ret;
447
0
        }
448
0
        LOG(INFO) << "snapshot data migrator started";
449
0
    }
450
451
4
    if (config::enable_snapshot_chain_compactor) {
452
0
        snapshot_chain_compactor_ = std::make_shared<SnapshotChainCompactor>(txn_kv_);
453
0
        int ret = snapshot_chain_compactor_->start();
454
0
        if (ret != 0) {
455
0
            LOG(ERROR) << "failed to start snapshot chain compactor";
456
0
            return ret;
457
0
        }
458
0
        LOG(INFO) << "snapshot chain compactor started";
459
0
    }
460
461
4
    return 0;
462
4
}
463
464
4
void Recycler::stop() {
465
4
    stopped_ = true;
466
4
    notifier_.notify_all();
467
4
    pending_instance_cond_.notify_all();
468
4
    {
469
4
        std::lock_guard lock(mtx_);
470
4
        for (auto& [_, recycler] : recycling_instance_map_) {
471
0
            recycler->stop();
472
0
        }
473
4
    }
474
20
    for (auto& w : workers_) {
475
20
        if (w.joinable()) w.join();
476
20
    }
477
4
    if (checker_) {
478
0
        checker_->stop();
479
0
    }
480
4
    if (snapshot_data_migrator_) {
481
0
        snapshot_data_migrator_->stop();
482
0
    }
483
4
    if (snapshot_chain_compactor_) {
484
0
        snapshot_chain_compactor_->stop();
485
0
    }
486
4
}
487
488
class InstanceRecycler::InvertedIndexIdCache {
489
public:
490
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
491
131
            : 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
4.14k
                return 0;
504
4.14k
            }
505
24.2k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
506
24.2k
                it != inverted_index_id_map_.end()) {
507
16.5k
                res = it->second;
508
16.5k
                return 0;
509
16.5k
            }
510
24.2k
        }
511
        // Get schema from kv
512
        // TODO(plat1ko): Single flight
513
7.66k
        std::unique_ptr<Transaction> txn;
514
7.66k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
515
7.66k
        if (err != TxnErrorCode::TXN_OK) {
516
0
            LOG(WARNING) << "failed to create txn, err=" << err;
517
0
            return -1;
518
0
        }
519
7.66k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
520
7.66k
        ValueBuf val_buf;
521
7.66k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
522
7.66k
        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.16k
        doris::TabletSchemaCloudPB schema;
527
7.16k
        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.16k
        if (schema.index_size() > 0) {
532
5.61k
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
533
5.61k
            if (schema.has_inverted_index_storage_format()) {
534
5.60k
                index_format = schema.inverted_index_storage_format();
535
5.60k
            }
536
5.61k
            res.first = index_format;
537
5.61k
            res.second.reserve(schema.index_size());
538
13.4k
            for (auto& i : schema.index()) {
539
13.4k
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
540
13.4k
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
541
13.4k
                }
542
13.4k
            }
543
5.61k
        }
544
7.16k
        insert(index_id, schema_version, res);
545
7.16k
        return 0;
546
7.16k
    }
547
548
    // Empty `ids` means this schema has no inverted index
549
7.16k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
550
7.16k
        if (index_info.second.empty()) {
551
1.55k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
552
1.55k
            std::lock_guard lock(mtx_);
553
1.55k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
554
5.61k
        } else {
555
5.61k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
556
5.61k
            std::lock_guard lock(mtx_);
557
5.61k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
558
5.61k
        }
559
7.16k
    }
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
59.8k
        size_t operator()(const Key& key) const {
569
59.8k
            size_t seed = 0;
570
59.8k
            seed = std::hash<int64_t> {}(key.first);
571
59.8k
            seed = std::hash<int32_t> {}(key.second);
572
59.8k
            return seed;
573
59.8k
        }
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
131
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
592
131
    delete_bitmap_lock_white_list_->init();
593
131
    resource_mgr_->init();
594
131
    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
131
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
599
131
};
600
601
131
InstanceRecycler::~InstanceRecycler() = default;
602
603
115
int InstanceRecycler::init_obj_store_accessors() {
604
115
    for (const auto& obj_info : instance_info_.obj_info()) {
605
75
#ifdef UNIT_TEST
606
75
        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
75
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
623
75
    }
624
625
115
    return 0;
626
115
}
627
628
115
int InstanceRecycler::init_storage_vault_accessors() {
629
115
    if (instance_info_.resource_ids().empty()) {
630
108
        return 0;
631
108
    }
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
115
int InstanceRecycler::init() {
724
115
    int ret = init_obj_store_accessors();
725
115
    if (ret != 0) {
726
0
        return ret;
727
0
    }
728
729
115
    return init_storage_vault_accessors();
730
115
}
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
5
int InstanceRecycler::recycle_deleted_instance() {
810
5
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
811
812
5
    int ret = 0;
813
5
    auto start_time = steady_clock::now();
814
815
5
    DORIS_CLOUD_DEFER {
816
5
        auto cost = duration<float>(steady_clock::now() - start_time).count();
817
5
        LOG(WARNING) << (ret == 0 ? "successfully" : "failed to")
818
5
                     << " recycle deleted instance, cost=" << cost
819
5
                     << "s, instance_id=" << instance_id_;
820
5
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
815
5
    DORIS_CLOUD_DEFER {
816
5
        auto cost = duration<float>(steady_clock::now() - start_time).count();
817
5
        LOG(WARNING) << (ret == 0 ? "successfully" : "failed to")
818
5
                     << " recycle deleted instance, cost=" << cost
819
5
                     << "s, instance_id=" << instance_id_;
820
5
    };
821
822
    // Step 1: Recycle tmp rowsets (contains ref count but txn is not committed)
823
5
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
824
5
        int res = recycle_tmp_rowsets();
825
5
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
826
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
827
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
828
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
829
            // and cannot be recycled.
830
5
            res = recycle_tmp_rowsets();
831
5
        }
832
5
        return res;
833
5
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_1clEv
Line
Count
Source
823
5
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
824
5
        int res = recycle_tmp_rowsets();
825
5
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
826
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
827
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
828
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
829
            // and cannot be recycled.
830
5
            res = recycle_tmp_rowsets();
831
5
        }
832
5
        return res;
833
5
    };
834
5
    if (recycle_tmp_rowsets_with_mark_delete_enabled() != 0) {
835
0
        LOG_WARNING("failed to recycle tmp rowsets").tag("instance_id", instance_id_);
836
0
        ret = -1;
837
0
        return -1;
838
0
    }
839
840
    // Step 2: Recycle versioned rowsets in recycle space (already marked for deletion)
841
5
    if (recycle_versioned_rowsets() != 0) {
842
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
843
0
        ret = -1;
844
0
        return -1;
845
0
    }
846
847
    // Step 3: Recycle operation logs (can recycle logs not referenced by snapshots)
848
5
    if (recycle_operation_logs() != 0) {
849
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
850
0
        ret = -1;
851
0
        return -1;
852
0
    }
853
854
    // Step 4: Check if there are still cluster snapshots
855
5
    bool has_snapshots = false;
856
5
    if (has_cluster_snapshots(&has_snapshots) != 0) {
857
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
858
0
        ret = -1;
859
0
        return -1;
860
5
    } else if (has_snapshots) {
861
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
862
1
        return 0;
863
1
    }
864
865
4
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
866
4
                            instance_info().snapshot_switch_status() !=
867
1
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
868
4
    if (snapshot_enabled) {
869
1
        bool has_unrecycled_rowsets = false;
870
1
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
871
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
872
0
            ret = -1;
873
0
            return -1;
874
1
        } else if (has_unrecycled_rowsets) {
875
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
876
0
                    .tag("instance_id", instance_id_);
877
0
            return ret;
878
0
        }
879
3
    } else { // delete all remote data if snapshot is disabled
880
3
        for (auto& [_, accessor] : accessor_map_) {
881
3
            if (stopped()) {
882
0
                return ret;
883
0
            }
884
885
3
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
886
3
            int del_ret = accessor->delete_all();
887
3
            if (del_ret == 0) {
888
3
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
889
3
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
890
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
891
                // so the recycling has been successful.
892
0
                ret = -1;
893
0
            }
894
3
        }
895
896
3
        if (ret != 0) {
897
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
898
0
            return ret;
899
0
        }
900
3
    }
901
902
    // Check successor instance, if exists, skip deleting kv because successor instance may still need the data in kv
903
4
    if (instance_info_.has_successor_instance_id() &&
904
4
        !instance_info_.successor_instance_id().empty()) {
905
0
        std::string key = instance_key(instance_info_.successor_instance_id());
906
0
        std::unique_ptr<Transaction> txn;
907
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
908
0
        if (err != TxnErrorCode::TXN_OK) {
909
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_
910
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
911
0
                         << " err=" << err;
912
0
            ret = -1;
913
0
            return -1;
914
0
        }
915
916
0
        std::string value;
917
0
        err = txn->get(key, &value);
918
0
        if (err == TxnErrorCode::TXN_OK) {
919
0
            LOG(INFO) << "instance successor instance is still exist, skip deleting kv,"
920
0
                      << " instance_id=" << instance_id_
921
0
                      << " successor_instance_id=" << instance_info_.successor_instance_id();
922
0
            return 0;
923
0
        } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
924
0
            LOG(WARNING) << "failed to get successor instance, instance_id=" << instance_id_
925
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
926
0
                         << " err=" << err;
927
0
            ret = -1;
928
0
            return -1;
929
0
        }
930
0
    }
931
932
    // delete all kv
933
4
    std::unique_ptr<Transaction> txn;
934
4
    TxnErrorCode err = txn_kv_->create_txn(&txn);
935
4
    if (err != TxnErrorCode::TXN_OK) {
936
0
        LOG(WARNING) << "failed to create txn";
937
0
        ret = -1;
938
0
        return -1;
939
0
    }
940
4
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
941
    // delete kv before deleting objects to prevent the checker from misjudging data loss
942
4
    std::string start_txn_key = txn_key_prefix(instance_id_);
943
4
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
944
4
    txn->remove(start_txn_key, end_txn_key);
945
4
    std::string start_version_key = version_key_prefix(instance_id_);
946
4
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
947
4
    txn->remove(start_version_key, end_version_key);
948
4
    std::string start_meta_key = meta_key_prefix(instance_id_);
949
4
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
950
4
    txn->remove(start_meta_key, end_meta_key);
951
4
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
952
4
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
953
4
    txn->remove(start_recycle_key, end_recycle_key);
954
4
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
955
4
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
956
4
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
957
4
    std::string start_copy_key = copy_key_prefix(instance_id_);
958
4
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
959
4
    txn->remove(start_copy_key, end_copy_key);
960
    // should not remove job key range, because we need to reserve job recycle kv
961
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
962
4
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
963
4
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
964
4
    txn->remove(start_job_tablet_key, end_job_tablet_key);
965
4
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
966
4
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
967
4
    std::string start_vault_key = storage_vault_key(key_info0);
968
4
    std::string end_vault_key = storage_vault_key(key_info1);
969
4
    txn->remove(start_vault_key, end_vault_key);
970
4
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
971
4
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
972
4
    txn->remove(versioned_version_key_start, versioned_version_key_end);
973
4
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
974
4
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
975
4
    txn->remove(versioned_index_key_start, versioned_index_key_end);
976
4
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
977
4
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
978
4
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
979
4
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
980
4
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
981
4
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
982
4
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
983
4
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
984
4
    txn->remove(versioned_data_key_start, versioned_data_key_end);
985
4
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
986
4
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
987
4
    txn->remove(versioned_log_key_start, versioned_log_key_end);
988
4
    err = txn->commit();
989
4
    if (err != TxnErrorCode::TXN_OK) {
990
0
        LOG(WARNING) << "failed to delete all kv, instance_id=" << instance_id_ << ", err=" << err;
991
0
        ret = -1;
992
0
    }
993
994
4
    if (ret == 0) {
995
        // remove instance kv
996
        // ATTN: MUST ensure that cloud platform won't regenerate the same instance id
997
4
        err = txn_kv_->create_txn(&txn);
998
4
        if (err != TxnErrorCode::TXN_OK) {
999
0
            LOG(WARNING) << "failed to create txn";
1000
0
            ret = -1;
1001
0
            return ret;
1002
0
        }
1003
4
        std::string key;
1004
4
        instance_key({instance_id_}, &key);
1005
4
        txn->atomic_add(system_meta_service_instance_update_key(), 1);
1006
4
        txn->remove(key);
1007
4
        err = txn->commit();
1008
4
        if (err != TxnErrorCode::TXN_OK) {
1009
0
            LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
1010
0
                         << " err=" << err;
1011
0
            ret = -1;
1012
0
        }
1013
4
    }
1014
4
    return ret;
1015
4
}
1016
1017
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
1018
9
                                          bool* exists, PackedFileRecycleStats* stats) {
1019
9
    if (exists == nullptr) {
1020
0
        return -1;
1021
0
    }
1022
9
    *exists = false;
1023
1024
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
1025
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1026
9
    std::string scan_begin = begin;
1027
1028
9
    while (true) {
1029
9
        std::unique_ptr<RangeGetIterator> it_range;
1030
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
1031
9
        if (get_ret < 0) {
1032
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1033
0
                    .tag("instance_id", instance_id_)
1034
0
                    .tag("tablet_id", tablet_id)
1035
0
                    .tag("ret", get_ret);
1036
0
            return -1;
1037
0
        }
1038
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1039
6
            return 0;
1040
6
        }
1041
1042
3
        std::string last_key;
1043
3
        while (it_range->has_next()) {
1044
3
            auto [k, v] = it_range->next();
1045
3
            last_key.assign(k.data(), k.size());
1046
3
            doris::RowsetMetaCloudPB rowset_meta;
1047
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1048
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1049
0
                        .tag("instance_id", instance_id_)
1050
0
                        .tag("tablet_id", tablet_id)
1051
0
                        .tag("key", hex(k));
1052
0
                continue;
1053
0
            }
1054
3
            if (stats) {
1055
3
                ++stats->rowset_scan_count;
1056
3
            }
1057
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1058
3
                *exists = true;
1059
3
                return 0;
1060
3
            }
1061
3
        }
1062
1063
0
        if (!it_range->more()) {
1064
0
            return 0;
1065
0
        }
1066
1067
        // Continue scanning from the next key to keep each transaction short.
1068
0
        scan_begin = std::move(last_key);
1069
0
        scan_begin.push_back('\x00');
1070
0
    }
1071
9
}
1072
1073
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1074
                                                          const std::string& rowset_id,
1075
                                                          int64_t txn_id, bool* recycle_exists,
1076
11
                                                          bool* tmp_exists) {
1077
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1078
0
        return -1;
1079
0
    }
1080
11
    *recycle_exists = false;
1081
11
    *tmp_exists = false;
1082
1083
11
    if (txn_id <= 0) {
1084
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1085
0
                .tag("instance_id", instance_id_)
1086
0
                .tag("tablet_id", tablet_id)
1087
0
                .tag("rowset_id", rowset_id)
1088
0
                .tag("txn_id", txn_id);
1089
0
        return -1;
1090
0
    }
1091
1092
11
    std::unique_ptr<Transaction> txn;
1093
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1094
11
    if (err != TxnErrorCode::TXN_OK) {
1095
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1096
0
                .tag("instance_id", instance_id_)
1097
0
                .tag("tablet_id", tablet_id)
1098
0
                .tag("rowset_id", rowset_id)
1099
0
                .tag("txn_id", txn_id)
1100
0
                .tag("err", err);
1101
0
        return -1;
1102
0
    }
1103
1104
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1105
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1106
11
    if (ret == TxnErrorCode::TXN_OK) {
1107
1
        *recycle_exists = true;
1108
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1109
0
        LOG_WARNING("failed to check recycle rowset existence")
1110
0
                .tag("instance_id", instance_id_)
1111
0
                .tag("tablet_id", tablet_id)
1112
0
                .tag("rowset_id", rowset_id)
1113
0
                .tag("key", hex(recycle_key))
1114
0
                .tag("err", ret);
1115
0
        return -1;
1116
0
    }
1117
1118
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1119
11
    ret = key_exists(txn.get(), tmp_key, true);
1120
11
    if (ret == TxnErrorCode::TXN_OK) {
1121
1
        *tmp_exists = true;
1122
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1123
0
        LOG_WARNING("failed to check tmp rowset existence")
1124
0
                .tag("instance_id", instance_id_)
1125
0
                .tag("tablet_id", tablet_id)
1126
0
                .tag("txn_id", txn_id)
1127
0
                .tag("key", hex(tmp_key))
1128
0
                .tag("err", ret);
1129
0
        return -1;
1130
0
    }
1131
1132
11
    return 0;
1133
11
}
1134
1135
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1136
8
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1137
8
    if (!hint.empty()) {
1138
8
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1139
8
            return {hint, it->second};
1140
8
        }
1141
8
    }
1142
1143
0
    return {"", nullptr};
1144
8
}
1145
1146
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1147
                                               const std::string& packed_file_path,
1148
3
                                               PackedFileRecycleStats* stats) {
1149
3
    bool local_changed = false;
1150
3
    int64_t left_num = 0;
1151
3
    int64_t left_bytes = 0;
1152
3
    bool all_small_files_confirmed = true;
1153
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1154
1155
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1156
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1157
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1158
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1159
14
        LOG_INFO("packed slice correction status")
1160
14
                .tag("instance_id", instance_id_)
1161
14
                .tag("packed_file_path", packed_file_path)
1162
14
                .tag("small_file_path", file.path())
1163
14
                .tag("tablet_id", tablet_id)
1164
14
                .tag("rowset_id", rowset_id)
1165
14
                .tag("txn_id", txn_id)
1166
14
                .tag("size", file.size())
1167
14
                .tag("deleted", file.deleted())
1168
14
                .tag("corrected", file.corrected())
1169
14
                .tag("confirmed_this_round", confirmed_this_round);
1170
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
1155
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1156
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1157
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1158
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1159
14
        LOG_INFO("packed slice correction status")
1160
14
                .tag("instance_id", instance_id_)
1161
14
                .tag("packed_file_path", packed_file_path)
1162
14
                .tag("small_file_path", file.path())
1163
14
                .tag("tablet_id", tablet_id)
1164
14
                .tag("rowset_id", rowset_id)
1165
14
                .tag("txn_id", txn_id)
1166
14
                .tag("size", file.size())
1167
14
                .tag("deleted", file.deleted())
1168
14
                .tag("corrected", file.corrected())
1169
14
                .tag("confirmed_this_round", confirmed_this_round);
1170
14
    };
1171
1172
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1173
14
        auto* small_file = packed_info->mutable_slices(i);
1174
14
        if (small_file->deleted()) {
1175
3
            log_small_file_status(*small_file, small_file->corrected());
1176
3
            continue;
1177
3
        }
1178
1179
11
        if (small_file->corrected()) {
1180
0
            left_num++;
1181
0
            left_bytes += small_file->size();
1182
0
            log_small_file_status(*small_file, true);
1183
0
            continue;
1184
0
        }
1185
1186
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1187
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1188
0
                    .tag("instance_id", instance_id_)
1189
0
                    .tag("small_file_path", small_file->path())
1190
0
                    .tag("index", i);
1191
0
            return -1;
1192
0
        }
1193
1194
11
        int64_t tablet_id = small_file->tablet_id();
1195
11
        const std::string& rowset_id = small_file->rowset_id();
1196
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1197
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1198
0
                    .tag("instance_id", instance_id_)
1199
0
                    .tag("small_file_path", small_file->path())
1200
0
                    .tag("index", i)
1201
0
                    .tag("tablet_id", tablet_id)
1202
0
                    .tag("rowset_id", rowset_id)
1203
0
                    .tag("has_txn_id", small_file->has_txn_id())
1204
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1205
0
            return -1;
1206
0
        }
1207
11
        int64_t txn_id = small_file->txn_id();
1208
11
        bool recycle_exists = false;
1209
11
        bool tmp_exists = false;
1210
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1211
11
                                                &tmp_exists) != 0) {
1212
0
            return -1;
1213
0
        }
1214
1215
11
        bool small_file_confirmed = false;
1216
11
        if (tmp_exists) {
1217
1
            left_num++;
1218
1
            left_bytes += small_file->size();
1219
1
            small_file_confirmed = true;
1220
10
        } else if (recycle_exists) {
1221
1
            left_num++;
1222
1
            left_bytes += small_file->size();
1223
            // keep small_file_confirmed=false so the packed file remains uncorrected
1224
9
        } else {
1225
9
            bool rowset_exists = false;
1226
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1227
0
                return -1;
1228
0
            }
1229
1230
9
            if (!rowset_exists) {
1231
6
                if (!small_file->deleted()) {
1232
6
                    small_file->set_deleted(true);
1233
6
                    local_changed = true;
1234
6
                }
1235
6
                if (!small_file->corrected()) {
1236
6
                    small_file->set_corrected(true);
1237
6
                    local_changed = true;
1238
6
                }
1239
6
                small_file_confirmed = true;
1240
6
            } else {
1241
3
                left_num++;
1242
3
                left_bytes += small_file->size();
1243
3
                small_file_confirmed = true;
1244
3
            }
1245
9
        }
1246
1247
11
        if (!small_file_confirmed) {
1248
1
            all_small_files_confirmed = false;
1249
1
        }
1250
1251
11
        if (small_file->corrected() != small_file_confirmed) {
1252
4
            small_file->set_corrected(small_file_confirmed);
1253
4
            local_changed = true;
1254
4
        }
1255
1256
11
        log_small_file_status(*small_file, small_file_confirmed);
1257
11
    }
1258
1259
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1260
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1261
3
        local_changed = true;
1262
3
    }
1263
3
    if (packed_info->ref_cnt() != left_num) {
1264
3
        auto old_ref_cnt = packed_info->ref_cnt();
1265
3
        packed_info->set_ref_cnt(left_num);
1266
3
        LOG_INFO("corrected packed file ref count")
1267
3
                .tag("instance_id", instance_id_)
1268
3
                .tag("resource_id", packed_info->resource_id())
1269
3
                .tag("packed_file_path", packed_file_path)
1270
3
                .tag("old_ref_cnt", old_ref_cnt)
1271
3
                .tag("new_ref_cnt", left_num);
1272
3
        local_changed = true;
1273
3
    }
1274
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1275
2
        packed_info->set_corrected(all_small_files_confirmed);
1276
2
        local_changed = true;
1277
2
    }
1278
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1279
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1280
1
        local_changed = true;
1281
1
    }
1282
1283
3
    if (changed != nullptr) {
1284
3
        *changed = local_changed;
1285
3
    }
1286
3
    return 0;
1287
3
}
1288
1289
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1290
                                                 const std::string& packed_file_path,
1291
4
                                                 PackedFileRecycleStats* stats) {
1292
4
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1293
4
    bool correction_ok = false;
1294
4
    cloud::PackedFileInfoPB packed_info;
1295
1296
4
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1297
4
        if (stopped()) {
1298
0
            LOG_WARNING("recycler stopped before processing packed file")
1299
0
                    .tag("instance_id", instance_id_)
1300
0
                    .tag("packed_file_path", packed_file_path)
1301
0
                    .tag("attempt", attempt);
1302
0
            return -1;
1303
0
        }
1304
1305
4
        std::unique_ptr<Transaction> txn;
1306
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1307
4
        if (err != TxnErrorCode::TXN_OK) {
1308
0
            LOG_WARNING("failed to create txn when processing packed file")
1309
0
                    .tag("instance_id", instance_id_)
1310
0
                    .tag("packed_file_path", packed_file_path)
1311
0
                    .tag("attempt", attempt)
1312
0
                    .tag("err", err);
1313
0
            return -1;
1314
0
        }
1315
1316
4
        std::string packed_val;
1317
4
        err = txn->get(packed_key, &packed_val);
1318
4
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1319
0
            return 0;
1320
0
        }
1321
4
        if (err != TxnErrorCode::TXN_OK) {
1322
0
            LOG_WARNING("failed to get packed file kv")
1323
0
                    .tag("instance_id", instance_id_)
1324
0
                    .tag("packed_file_path", packed_file_path)
1325
0
                    .tag("attempt", attempt)
1326
0
                    .tag("err", err);
1327
0
            return -1;
1328
0
        }
1329
1330
4
        if (!packed_info.ParseFromString(packed_val)) {
1331
0
            LOG_WARNING("failed to parse packed file info")
1332
0
                    .tag("instance_id", instance_id_)
1333
0
                    .tag("packed_file_path", packed_file_path)
1334
0
                    .tag("attempt", attempt);
1335
0
            return -1;
1336
0
        }
1337
1338
4
        int64_t now_sec = ::time(nullptr);
1339
4
        bool corrected = packed_info.corrected();
1340
4
        bool due = config::force_immediate_recycle ||
1341
4
                   now_sec - packed_info.created_at_sec() >=
1342
4
                           config::packed_file_correction_delay_seconds;
1343
1344
4
        if (!corrected && due) {
1345
3
            bool changed = false;
1346
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1347
0
                LOG_WARNING("correct_packed_file_info failed")
1348
0
                        .tag("instance_id", instance_id_)
1349
0
                        .tag("packed_file_path", packed_file_path)
1350
0
                        .tag("attempt", attempt);
1351
0
                return -1;
1352
0
            }
1353
3
            if (changed) {
1354
3
                std::string updated;
1355
3
                if (!packed_info.SerializeToString(&updated)) {
1356
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1357
0
                            .tag("instance_id", instance_id_)
1358
0
                            .tag("packed_file_path", packed_file_path)
1359
0
                            .tag("attempt", attempt);
1360
0
                    return -1;
1361
0
                }
1362
3
                txn->put(packed_key, updated);
1363
3
                err = txn->commit();
1364
3
                if (err == TxnErrorCode::TXN_OK) {
1365
3
                    if (stats) {
1366
3
                        ++stats->num_corrected;
1367
3
                    }
1368
3
                } else {
1369
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1370
0
                        LOG_WARNING(
1371
0
                                "failed to commit correction for packed file due to conflict, "
1372
0
                                "retrying")
1373
0
                                .tag("instance_id", instance_id_)
1374
0
                                .tag("packed_file_path", packed_file_path)
1375
0
                                .tag("attempt", attempt);
1376
0
                        sleep_for_packed_file_retry();
1377
0
                        packed_info.Clear();
1378
0
                        continue;
1379
0
                    }
1380
0
                    LOG_WARNING("failed to commit correction for packed file")
1381
0
                            .tag("instance_id", instance_id_)
1382
0
                            .tag("packed_file_path", packed_file_path)
1383
0
                            .tag("attempt", attempt)
1384
0
                            .tag("err", err);
1385
0
                    return -1;
1386
0
                }
1387
3
            }
1388
3
        }
1389
1390
4
        correction_ok = true;
1391
4
        break;
1392
4
    }
1393
1394
4
    if (!correction_ok) {
1395
0
        return -1;
1396
0
    }
1397
1398
4
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1399
4
          packed_info.ref_cnt() == 0)) {
1400
3
        return 0;
1401
3
    }
1402
1403
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1404
0
        LOG_WARNING("packed file missing resource id when recycling")
1405
0
                .tag("instance_id", instance_id_)
1406
0
                .tag("packed_file_path", packed_file_path);
1407
0
        return -1;
1408
0
    }
1409
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1410
1
    if (!accessor) {
1411
0
        LOG_WARNING("no accessor available to delete packed file")
1412
0
                .tag("instance_id", instance_id_)
1413
0
                .tag("packed_file_path", packed_file_path)
1414
0
                .tag("resource_id", packed_info.resource_id());
1415
0
        return -1;
1416
0
    }
1417
1
    int del_ret = accessor->delete_file(packed_file_path);
1418
1
    if (del_ret != 0 && del_ret != 1) {
1419
0
        LOG_WARNING("failed to delete packed file")
1420
0
                .tag("instance_id", instance_id_)
1421
0
                .tag("packed_file_path", packed_file_path)
1422
0
                .tag("resource_id", resource_id)
1423
0
                .tag("ret", del_ret);
1424
0
        return -1;
1425
0
    }
1426
1
    if (del_ret == 1) {
1427
0
        LOG_INFO("packed file already removed")
1428
0
                .tag("instance_id", instance_id_)
1429
0
                .tag("packed_file_path", packed_file_path)
1430
0
                .tag("resource_id", resource_id);
1431
1
    } else {
1432
1
        LOG_INFO("deleted packed file")
1433
1
                .tag("instance_id", instance_id_)
1434
1
                .tag("packed_file_path", packed_file_path)
1435
1
                .tag("resource_id", resource_id);
1436
1
    }
1437
1438
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1439
1
        std::unique_ptr<Transaction> del_txn;
1440
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1441
1
        if (err != TxnErrorCode::TXN_OK) {
1442
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1443
0
                    .tag("instance_id", instance_id_)
1444
0
                    .tag("packed_file_path", packed_file_path)
1445
0
                    .tag("del_attempt", del_attempt)
1446
0
                    .tag("err", err);
1447
0
            return -1;
1448
0
        }
1449
1450
1
        std::string latest_val;
1451
1
        err = del_txn->get(packed_key, &latest_val);
1452
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1453
0
            return 0;
1454
0
        }
1455
1
        if (err != TxnErrorCode::TXN_OK) {
1456
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1457
0
                    .tag("instance_id", instance_id_)
1458
0
                    .tag("packed_file_path", packed_file_path)
1459
0
                    .tag("del_attempt", del_attempt)
1460
0
                    .tag("err", err);
1461
0
            return -1;
1462
0
        }
1463
1464
1
        cloud::PackedFileInfoPB latest_info;
1465
1
        if (!latest_info.ParseFromString(latest_val)) {
1466
0
            LOG_WARNING("failed to parse packed file info before removal")
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
            return -1;
1471
0
        }
1472
1473
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1474
1
              latest_info.ref_cnt() == 0)) {
1475
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1476
0
                    .tag("instance_id", instance_id_)
1477
0
                    .tag("packed_file_path", packed_file_path)
1478
0
                    .tag("del_attempt", del_attempt);
1479
0
            return 0;
1480
0
        }
1481
1482
1
        del_txn->remove(packed_key);
1483
1
        err = del_txn->commit();
1484
1
        if (err == TxnErrorCode::TXN_OK) {
1485
1
            if (stats) {
1486
1
                ++stats->num_deleted;
1487
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1488
1
                                        static_cast<int64_t>(latest_val.size());
1489
1
                if (del_ret == 0 || del_ret == 1) {
1490
1
                    ++stats->num_object_deleted;
1491
1
                    int64_t object_size = latest_info.total_slice_bytes();
1492
1
                    if (object_size <= 0) {
1493
0
                        object_size = packed_info.total_slice_bytes();
1494
0
                    }
1495
1
                    stats->bytes_object_deleted += object_size;
1496
1
                }
1497
1
            }
1498
1
            LOG_INFO("removed packed file metadata")
1499
1
                    .tag("instance_id", instance_id_)
1500
1
                    .tag("packed_file_path", packed_file_path);
1501
1
            return 0;
1502
1
        }
1503
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1504
0
            if (del_attempt >= max_retry_times) {
1505
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1506
0
                        .tag("instance_id", instance_id_)
1507
0
                        .tag("packed_file_path", packed_file_path)
1508
0
                        .tag("del_attempt", del_attempt);
1509
0
                return -1;
1510
0
            }
1511
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1512
0
                    .tag("instance_id", instance_id_)
1513
0
                    .tag("packed_file_path", packed_file_path)
1514
0
                    .tag("del_attempt", del_attempt);
1515
0
            sleep_for_packed_file_retry();
1516
0
            continue;
1517
0
        }
1518
0
        LOG_WARNING("failed to remove packed file kv")
1519
0
                .tag("instance_id", instance_id_)
1520
0
                .tag("packed_file_path", packed_file_path)
1521
0
                .tag("del_attempt", del_attempt)
1522
0
                .tag("err", err);
1523
0
        return -1;
1524
0
    }
1525
1526
0
    return -1;
1527
1
}
1528
1529
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view /*value*/,
1530
4
                                            PackedFileRecycleStats* stats, int* ret) {
1531
4
    if (stats) {
1532
4
        ++stats->num_scanned;
1533
4
    }
1534
4
    std::string packed_file_path;
1535
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1536
0
        LOG_WARNING("failed to decode packed file key")
1537
0
                .tag("instance_id", instance_id_)
1538
0
                .tag("key", hex(key));
1539
0
        if (stats) {
1540
0
            ++stats->num_failed;
1541
0
        }
1542
0
        if (ret) {
1543
0
            *ret = -1;
1544
0
        }
1545
0
        return 0;
1546
0
    }
1547
1548
4
    std::string packed_key(key);
1549
4
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1550
4
    if (process_ret != 0) {
1551
0
        if (stats) {
1552
0
            ++stats->num_failed;
1553
0
        }
1554
0
        if (ret) {
1555
0
            *ret = -1;
1556
0
        }
1557
0
    }
1558
4
    return 0;
1559
4
}
1560
1561
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1562
9.77k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1563
9.77k
    if (config::force_immediate_recycle) {
1564
15
        return 0L;
1565
15
    }
1566
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1567
9.75k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1568
9.75k
    int64_t retention_seconds = config::retention_seconds;
1569
9.75k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1570
7.80k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1571
7.80k
    }
1572
9.75k
    int64_t final_expiration = expiration + retention_seconds;
1573
9.75k
    if (*earlest_ts > final_expiration) {
1574
7
        *earlest_ts = final_expiration;
1575
7
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1576
7
    }
1577
9.75k
    return final_expiration;
1578
9.77k
}
1579
1580
int64_t calculate_partition_expired_time(
1581
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1582
9
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1583
9
    if (config::force_immediate_recycle) {
1584
3
        return 0L;
1585
3
    }
1586
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1587
6
                                                            : partition_meta_pb.creation_time();
1588
6
    int64_t retention_seconds = config::retention_seconds;
1589
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1590
6
        retention_seconds =
1591
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1592
6
    }
1593
6
    int64_t final_expiration = expiration + retention_seconds;
1594
6
    if (*earlest_ts > final_expiration) {
1595
2
        *earlest_ts = final_expiration;
1596
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1597
2
    }
1598
6
    return final_expiration;
1599
9
}
1600
1601
int64_t calculate_index_expired_time(const std::string& instance_id_,
1602
                                     const RecycleIndexPB& index_meta_pb,
1603
10
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1604
10
    if (config::force_immediate_recycle) {
1605
4
        return 0L;
1606
4
    }
1607
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1608
6
                                                        : index_meta_pb.creation_time();
1609
6
    int64_t retention_seconds = config::retention_seconds;
1610
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1611
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1612
6
    }
1613
6
    int64_t final_expiration = expiration + retention_seconds;
1614
6
    if (*earlest_ts > final_expiration) {
1615
2
        *earlest_ts = final_expiration;
1616
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1617
2
    }
1618
6
    return final_expiration;
1619
10
}
1620
1621
int64_t calculate_tmp_rowset_expired_time(
1622
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1623
106k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1624
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1625
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1626
    //  duration or timeout always < `retention_time` in practice.
1627
106k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1628
106k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1629
106k
                                 : tmp_rowset_meta_pb.creation_time();
1630
106k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1631
106k
    int64_t final_expiration = expiration + config::retention_seconds;
1632
106k
    if (*earlest_ts > final_expiration) {
1633
24
        *earlest_ts = final_expiration;
1634
24
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1635
24
    }
1636
106k
    return final_expiration;
1637
106k
}
1638
1639
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1640
30.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1641
30.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1642
30.0k
    if (*earlest_ts > final_expiration / 1000) {
1643
8
        *earlest_ts = final_expiration / 1000;
1644
8
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1645
8
    }
1646
30.0k
    return final_expiration;
1647
30.0k
}
1648
1649
int64_t calculate_restore_job_expired_time(
1650
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1651
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1652
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1653
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1654
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1655
        // final state, recycle immediately
1656
41
        return 0L;
1657
41
    }
1658
    // not final state, wait much longer than the FE's timeout(1 day)
1659
0
    int64_t last_modified_s =
1660
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1661
0
    int64_t expiration = restore_job.expired_at_s() > 0
1662
0
                                 ? last_modified_s + restore_job.expired_at_s()
1663
0
                                 : last_modified_s;
1664
0
    int64_t final_expiration = expiration + config::retention_seconds;
1665
0
    if (*earlest_ts > final_expiration) {
1666
0
        *earlest_ts = final_expiration;
1667
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1668
0
    }
1669
0
    return final_expiration;
1670
41
}
1671
1672
2
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1673
2
    AbortTxnRequest req;
1674
2
    TxnInfoPB txn_info;
1675
2
    MetaServiceCode code = MetaServiceCode::OK;
1676
2
    std::string msg;
1677
2
    std::stringstream ss;
1678
2
    std::unique_ptr<Transaction> txn;
1679
2
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1680
2
    if (err != TxnErrorCode::TXN_OK) {
1681
0
        LOG_WARNING("failed to create txn").tag("err", err);
1682
0
        return -1;
1683
0
    }
1684
1685
    // get txn index
1686
2
    TxnIndexPB txn_idx_pb;
1687
2
    auto index_key = txn_index_key({instance_id_, txn_id});
1688
2
    std::string index_val;
1689
2
    err = txn->get(index_key, &index_val);
1690
2
    if (err != TxnErrorCode::TXN_OK) {
1691
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1692
            // maybe recycled
1693
0
            LOG_INFO("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1694
0
                    .tag("key", hex(index_key))
1695
0
                    .tag("txn_id", txn_id);
1696
0
            return 0;
1697
0
        }
1698
0
        LOG_WARNING("failed to get txn index")
1699
0
                .tag("err", err)
1700
0
                .tag("key", hex(index_key))
1701
0
                .tag("txn_id", txn_id);
1702
0
        return -1;
1703
0
    }
1704
2
    if (!txn_idx_pb.ParseFromString(index_val)) {
1705
0
        LOG_WARNING("failed to parse txn index")
1706
0
                .tag("err", err)
1707
0
                .tag("key", hex(index_key))
1708
0
                .tag("txn_id", txn_id);
1709
0
        return -1;
1710
0
    }
1711
1712
2
    auto info_key = txn_info_key({instance_id_, txn_idx_pb.tablet_index().db_id(), txn_id});
1713
2
    std::string info_val;
1714
2
    err = txn->get(info_key, &info_val);
1715
2
    if (err != TxnErrorCode::TXN_OK) {
1716
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1717
            // maybe recycled
1718
0
            LOG_INFO("txn info not found, txn_id={} instance_id={}", txn_id, instance_id_)
1719
0
                    .tag("key", hex(info_key))
1720
0
                    .tag("txn_id", txn_id);
1721
0
            return 0;
1722
0
        }
1723
0
        LOG_WARNING("failed to get txn info")
1724
0
                .tag("err", err)
1725
0
                .tag("key", hex(info_key))
1726
0
                .tag("txn_id", txn_id);
1727
0
        return -1;
1728
0
    }
1729
2
    if (!txn_info.ParseFromString(info_val)) {
1730
0
        LOG_WARNING("failed to parse txn info")
1731
0
                .tag("err", err)
1732
0
                .tag("key", hex(info_key))
1733
0
                .tag("txn_id", txn_id);
1734
0
        return -1;
1735
0
    }
1736
1737
2
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
1738
0
        LOG_INFO("txn is not prepared status, txn_id={} status={}", txn_id, txn_info.status())
1739
0
                .tag("key", hex(info_key))
1740
0
                .tag("txn_id", txn_id);
1741
0
        return 0;
1742
0
    }
1743
1744
2
    req.set_txn_id(txn_id);
1745
1746
2
    LOG(INFO) << "begin abort txn for related rowset, txn_id=" << txn_id
1747
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString();
1748
1749
2
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
1750
2
    err = txn->commit();
1751
2
    if (err != TxnErrorCode::TXN_OK) {
1752
0
        code = cast_as<ErrCategory::COMMIT>(err);
1753
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
1754
0
        msg = ss.str();
1755
0
        return -1;
1756
0
    }
1757
1758
2
    LOG(INFO) << "finish abort txn for related rowset, txn_id=" << txn_id
1759
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString()
1760
2
              << " code=" << code << " msg=" << msg;
1761
1762
2
    return 0;
1763
2
}
1764
1765
4
int InstanceRecycler::abort_job_for_related_rowset(const RowsetMetaCloudPB& rowset_meta) {
1766
4
    FinishTabletJobRequest req;
1767
4
    FinishTabletJobResponse res;
1768
4
    req.set_action(FinishTabletJobRequest::ABORT);
1769
4
    MetaServiceCode code = MetaServiceCode::OK;
1770
4
    std::string msg;
1771
4
    std::stringstream ss;
1772
1773
4
    TabletIndexPB tablet_idx;
1774
4
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, rowset_meta.tablet_id(), tablet_idx);
1775
4
    if (ret == 1) {
1776
        // tablet maybe recycled, directly return 0
1777
1
        return 0;
1778
3
    } else if (ret != 0) {
1779
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << rowset_meta.tablet_id()
1780
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
1781
0
        return ret;
1782
0
    }
1783
1784
3
    std::unique_ptr<Transaction> txn;
1785
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1786
3
    if (err != TxnErrorCode::TXN_OK) {
1787
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
1788
0
        return -1;
1789
0
    }
1790
1791
3
    std::string job_key =
1792
3
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
1793
3
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
1794
3
    std::string job_val;
1795
3
    err = txn->get(job_key, &job_val);
1796
3
    if (err != TxnErrorCode::TXN_OK) {
1797
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1798
0
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
1799
0
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
1800
0
            return 0;
1801
0
        }
1802
0
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
1803
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
1804
0
                     << " key=" << hex(job_key);
1805
0
        return -1;
1806
0
    }
1807
1808
3
    TabletJobInfoPB job_pb;
1809
3
    if (!job_pb.ParseFromString(job_val)) {
1810
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
1811
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
1812
0
        return -1;
1813
0
    }
1814
1815
3
    std::string job_id {};
1816
3
    if (!job_pb.compaction().empty()) {
1817
2
        for (const auto& c : job_pb.compaction()) {
1818
2
            if (c.id() == rowset_meta.job_id()) {
1819
2
                job_id = c.id();
1820
2
                break;
1821
2
            }
1822
2
        }
1823
2
    } else if (job_pb.has_schema_change()) {
1824
1
        job_id = job_pb.schema_change().id();
1825
1
    }
1826
1827
3
    if (!job_id.empty() && rowset_meta.job_id() == job_id) {
1828
3
        LOG(INFO) << "begin to abort job for related rowset, job_id=" << rowset_meta.job_id()
1829
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
1830
3
        req.mutable_job()->CopyFrom(job_pb);
1831
3
        req.set_action(FinishTabletJobRequest::ABORT);
1832
3
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
1833
3
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
1834
3
                           ss);
1835
3
        if (code != MetaServiceCode::OK) {
1836
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
1837
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
1838
0
                         << " msg=" << msg;
1839
0
            return -1;
1840
0
        }
1841
3
        LOG(INFO) << "finish abort job for related rowset, job_id=" << rowset_meta.job_id()
1842
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
1843
3
                  << " code=" << code << " msg=" << msg;
1844
3
    } else {
1845
        // clang-format off
1846
0
        LOG(INFO) << "there is no job for related rowset, directly recycle rowset data"
1847
0
                  << ", instance_id=" << instance_id_ 
1848
0
                  << ", tablet_id=" << tablet_idx.tablet_id() 
1849
0
                  << ", job_id=" << job_id
1850
0
                  << ", rowset_id=" << rowset_meta.rowset_id_v2();
1851
        // clang-format on
1852
0
    }
1853
1854
3
    return 0;
1855
3
}
1856
1857
template <typename T>
1858
57.7k
int InstanceRecycler::abort_txn_or_job_for_recycle(T& rowset_meta_pb) {
1859
57.7k
    RowsetMetaCloudPB* rs_meta;
1860
57.7k
    RecycleRowsetPB::Type rowset_type = RecycleRowsetPB::PREPARE;
1861
1862
57.7k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1863
        // For keys that are not in the RecycleRowsetPB::PREPARE state
1864
        // we do not need to check the job or txn state
1865
        // because tmp_rowset_key already exists when this key is generated.
1866
3.75k
        rowset_type = rowset_meta_pb.type();
1867
3.75k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1868
54.0k
    } else {
1869
54.0k
        rs_meta = &rowset_meta_pb;
1870
54.0k
    }
1871
1872
57.7k
    DCHECK(rs_meta != nullptr);
1873
1874
    // compaction/sc will generate recycle_rowset_key for each input rowset with load_id
1875
    // we need skip them because the related txn has been finished
1876
    // load_rowset1 load_rowset2 => pick for compaction => compact_rowset
1877
    // compact_rowset1 compact_rowset2 => pick for compaction/sc job => new_rowset
1878
57.7k
    if (rowset_type == RecycleRowsetPB::PREPARE) {
1879
54.6k
        if (rs_meta->has_load_id()) {
1880
            // load
1881
2
            return abort_txn_for_related_rowset(rs_meta->txn_id());
1882
54.6k
        } else if (rs_meta->has_job_id()) {
1883
            // compaction / schema change
1884
3
            return abort_job_for_related_rowset(*rs_meta);
1885
3
        }
1886
54.6k
    }
1887
1888
57.7k
    return 0;
1889
57.7k
}
_ZN5doris5cloud16InstanceRecycler28abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRT_
Line
Count
Source
1858
3.75k
int InstanceRecycler::abort_txn_or_job_for_recycle(T& rowset_meta_pb) {
1859
3.75k
    RowsetMetaCloudPB* rs_meta;
1860
3.75k
    RecycleRowsetPB::Type rowset_type = RecycleRowsetPB::PREPARE;
1861
1862
3.75k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1863
        // For keys that are not in the RecycleRowsetPB::PREPARE state
1864
        // we do not need to check the job or txn state
1865
        // because tmp_rowset_key already exists when this key is generated.
1866
3.75k
        rowset_type = rowset_meta_pb.type();
1867
3.75k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1868
3.75k
    } else {
1869
3.75k
        rs_meta = &rowset_meta_pb;
1870
3.75k
    }
1871
1872
3.75k
    DCHECK(rs_meta != nullptr);
1873
1874
    // compaction/sc will generate recycle_rowset_key for each input rowset with load_id
1875
    // we need skip them because the related txn has been finished
1876
    // load_rowset1 load_rowset2 => pick for compaction => compact_rowset
1877
    // compact_rowset1 compact_rowset2 => pick for compaction/sc job => new_rowset
1878
3.75k
    if (rowset_type == RecycleRowsetPB::PREPARE) {
1879
652
        if (rs_meta->has_load_id()) {
1880
            // load
1881
1
            return abort_txn_for_related_rowset(rs_meta->txn_id());
1882
651
        } else if (rs_meta->has_job_id()) {
1883
            // compaction / schema change
1884
1
            return abort_job_for_related_rowset(*rs_meta);
1885
1
        }
1886
652
    }
1887
1888
3.75k
    return 0;
1889
3.75k
}
_ZN5doris5cloud16InstanceRecycler28abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRT_
Line
Count
Source
1858
54.0k
int InstanceRecycler::abort_txn_or_job_for_recycle(T& rowset_meta_pb) {
1859
54.0k
    RowsetMetaCloudPB* rs_meta;
1860
54.0k
    RecycleRowsetPB::Type rowset_type = RecycleRowsetPB::PREPARE;
1861
1862
54.0k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1863
        // For keys that are not in the RecycleRowsetPB::PREPARE state
1864
        // we do not need to check the job or txn state
1865
        // because tmp_rowset_key already exists when this key is generated.
1866
54.0k
        rowset_type = rowset_meta_pb.type();
1867
54.0k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1868
54.0k
    } else {
1869
54.0k
        rs_meta = &rowset_meta_pb;
1870
54.0k
    }
1871
1872
54.0k
    DCHECK(rs_meta != nullptr);
1873
1874
    // compaction/sc will generate recycle_rowset_key for each input rowset with load_id
1875
    // we need skip them because the related txn has been finished
1876
    // load_rowset1 load_rowset2 => pick for compaction => compact_rowset
1877
    // compact_rowset1 compact_rowset2 => pick for compaction/sc job => new_rowset
1878
54.0k
    if (rowset_type == RecycleRowsetPB::PREPARE) {
1879
54.0k
        if (rs_meta->has_load_id()) {
1880
            // load
1881
1
            return abort_txn_for_related_rowset(rs_meta->txn_id());
1882
54.0k
        } else if (rs_meta->has_job_id()) {
1883
            // compaction / schema change
1884
2
            return abort_job_for_related_rowset(*rs_meta);
1885
2
        }
1886
54.0k
    }
1887
1888
54.0k
    return 0;
1889
54.0k
}
1890
1891
template <typename T>
1892
int mark_rowset_as_recycled(TxnKv* txn_kv, const std::string& instance_id, std::string_view key,
1893
113k
                            T& rowset_meta_pb) {
1894
113k
    RowsetMetaCloudPB* rs_meta;
1895
1896
113k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1897
106k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1898
106k
    } else {
1899
106k
        rs_meta = &rowset_meta_pb;
1900
106k
    }
1901
1902
113k
    bool need_write_back = false;
1903
113k
    if ((!rs_meta->has_is_recycled() || !rs_meta->is_recycled())) {
1904
55.7k
        need_write_back = true;
1905
55.7k
        rs_meta->set_is_recycled(true);
1906
55.7k
    }
1907
1908
113k
    if (need_write_back) {
1909
55.7k
        std::unique_ptr<Transaction> txn;
1910
55.7k
        TxnErrorCode err = txn_kv->create_txn(&txn);
1911
55.7k
        if (err != TxnErrorCode::TXN_OK) {
1912
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1913
0
            return -1;
1914
0
        }
1915
        // double check becase of new transaction
1916
55.7k
        T rowset_meta;
1917
55.7k
        std::string val;
1918
55.7k
        err = txn->get(key, &val);
1919
55.7k
        if (!rowset_meta.ParseFromString(val)) {
1920
0
            LOG(WARNING) << "failed to parse rs_meta, instance_id=" << instance_id;
1921
0
            return -1;
1922
0
        }
1923
55.7k
        if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1924
52.0k
            rs_meta = rowset_meta.mutable_rowset_meta();
1925
52.0k
        } else {
1926
52.0k
            rs_meta = &rowset_meta;
1927
52.0k
        }
1928
55.7k
        if ((rs_meta->has_is_recycled() && rs_meta->is_recycled())) {
1929
0
            return 0;
1930
0
        }
1931
55.7k
        rs_meta->set_is_recycled(true);
1932
55.7k
        val.clear();
1933
55.7k
        rowset_meta.SerializeToString(&val);
1934
55.7k
        txn->put(key, val);
1935
55.7k
        err = txn->commit();
1936
55.7k
        if (err != TxnErrorCode::TXN_OK) {
1937
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
1938
0
            return -1;
1939
0
        }
1940
55.7k
    }
1941
113k
    return need_write_back ? 1 : 0;
1942
113k
}
_ZN5doris5cloud23mark_rowset_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS8_ERT_
Line
Count
Source
1893
7.50k
                            T& rowset_meta_pb) {
1894
7.50k
    RowsetMetaCloudPB* rs_meta;
1895
1896
7.50k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1897
7.50k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1898
7.50k
    } else {
1899
7.50k
        rs_meta = &rowset_meta_pb;
1900
7.50k
    }
1901
1902
7.50k
    bool need_write_back = false;
1903
7.50k
    if ((!rs_meta->has_is_recycled() || !rs_meta->is_recycled())) {
1904
3.75k
        need_write_back = true;
1905
3.75k
        rs_meta->set_is_recycled(true);
1906
3.75k
    }
1907
1908
7.50k
    if (need_write_back) {
1909
3.75k
        std::unique_ptr<Transaction> txn;
1910
3.75k
        TxnErrorCode err = txn_kv->create_txn(&txn);
1911
3.75k
        if (err != TxnErrorCode::TXN_OK) {
1912
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1913
0
            return -1;
1914
0
        }
1915
        // double check becase of new transaction
1916
3.75k
        T rowset_meta;
1917
3.75k
        std::string val;
1918
3.75k
        err = txn->get(key, &val);
1919
3.75k
        if (!rowset_meta.ParseFromString(val)) {
1920
0
            LOG(WARNING) << "failed to parse rs_meta, instance_id=" << instance_id;
1921
0
            return -1;
1922
0
        }
1923
3.75k
        if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1924
3.75k
            rs_meta = rowset_meta.mutable_rowset_meta();
1925
3.75k
        } else {
1926
3.75k
            rs_meta = &rowset_meta;
1927
3.75k
        }
1928
3.75k
        if ((rs_meta->has_is_recycled() && rs_meta->is_recycled())) {
1929
0
            return 0;
1930
0
        }
1931
3.75k
        rs_meta->set_is_recycled(true);
1932
3.75k
        val.clear();
1933
3.75k
        rowset_meta.SerializeToString(&val);
1934
3.75k
        txn->put(key, val);
1935
3.75k
        err = txn->commit();
1936
3.75k
        if (err != TxnErrorCode::TXN_OK) {
1937
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
1938
0
            return -1;
1939
0
        }
1940
3.75k
    }
1941
7.50k
    return need_write_back ? 1 : 0;
1942
7.50k
}
_ZN5doris5cloud23mark_rowset_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS8_ERT_
Line
Count
Source
1893
106k
                            T& rowset_meta_pb) {
1894
106k
    RowsetMetaCloudPB* rs_meta;
1895
1896
106k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1897
106k
        rs_meta = rowset_meta_pb.mutable_rowset_meta();
1898
106k
    } else {
1899
106k
        rs_meta = &rowset_meta_pb;
1900
106k
    }
1901
1902
106k
    bool need_write_back = false;
1903
106k
    if ((!rs_meta->has_is_recycled() || !rs_meta->is_recycled())) {
1904
52.0k
        need_write_back = true;
1905
52.0k
        rs_meta->set_is_recycled(true);
1906
52.0k
    }
1907
1908
106k
    if (need_write_back) {
1909
52.0k
        std::unique_ptr<Transaction> txn;
1910
52.0k
        TxnErrorCode err = txn_kv->create_txn(&txn);
1911
52.0k
        if (err != TxnErrorCode::TXN_OK) {
1912
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1913
0
            return -1;
1914
0
        }
1915
        // double check becase of new transaction
1916
52.0k
        T rowset_meta;
1917
52.0k
        std::string val;
1918
52.0k
        err = txn->get(key, &val);
1919
52.0k
        if (!rowset_meta.ParseFromString(val)) {
1920
0
            LOG(WARNING) << "failed to parse rs_meta, instance_id=" << instance_id;
1921
0
            return -1;
1922
0
        }
1923
52.0k
        if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1924
52.0k
            rs_meta = rowset_meta.mutable_rowset_meta();
1925
52.0k
        } else {
1926
52.0k
            rs_meta = &rowset_meta;
1927
52.0k
        }
1928
52.0k
        if ((rs_meta->has_is_recycled() && rs_meta->is_recycled())) {
1929
0
            return 0;
1930
0
        }
1931
52.0k
        rs_meta->set_is_recycled(true);
1932
52.0k
        val.clear();
1933
52.0k
        rowset_meta.SerializeToString(&val);
1934
52.0k
        txn->put(key, val);
1935
52.0k
        err = txn->commit();
1936
52.0k
        if (err != TxnErrorCode::TXN_OK) {
1937
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
1938
0
            return -1;
1939
0
        }
1940
52.0k
    }
1941
106k
    return need_write_back ? 1 : 0;
1942
106k
}
1943
1944
1
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
1945
1
    const std::string task_name = "recycle_ref_rowsets";
1946
1
    *has_unrecycled_rowsets = false;
1947
1948
1
    std::string data_rowset_ref_count_key_start =
1949
1
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
1950
1
    std::string data_rowset_ref_count_key_end =
1951
1
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
1952
1953
1
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
1954
1955
1
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
1956
1
    register_recycle_task(task_name, start_time);
1957
1958
1
    DORIS_CLOUD_DEFER {
1959
1
        unregister_recycle_task(task_name);
1960
1
        int64_t cost =
1961
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
1962
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
1963
1
                .tag("instance_id", instance_id_);
1964
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Line
Count
Source
1958
1
    DORIS_CLOUD_DEFER {
1959
1
        unregister_recycle_task(task_name);
1960
1
        int64_t cost =
1961
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
1962
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
1963
1
                .tag("instance_id", instance_id_);
1964
1
    };
1965
1966
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
1967
1
    std::set<int64_t> tablets_with_refs;
1968
1
    int64_t num_scanned = 0;
1969
1970
1
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
1971
0
        ++num_scanned;
1972
0
        int64_t tablet_id;
1973
0
        std::string rowset_id;
1974
0
        std::string_view key(k);
1975
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
1976
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
1977
0
            return 0; // Continue scanning
1978
0
        }
1979
1980
0
        tablets_with_refs.insert(tablet_id);
1981
0
        return 0;
1982
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
1983
1984
1
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
1985
1
                         std::move(scan_func)) != 0) {
1986
0
        LOG_WARNING("failed to scan data rowset ref count keys");
1987
0
        return -1;
1988
0
    }
1989
1990
1
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
1991
1
             tablets_with_refs.size(), num_scanned)
1992
1
            .tag("instance_id", instance_id_);
1993
1994
    // Phase 2: Recycle each tablet
1995
1
    int64_t num_recycled_tablets = 0;
1996
1
    for (int64_t tablet_id : tablets_with_refs) {
1997
0
        if (stopped()) {
1998
0
            LOG_INFO("recycler stopped, skip remaining tablets")
1999
0
                    .tag("instance_id", instance_id_)
2000
0
                    .tag("tablets_processed", num_recycled_tablets)
2001
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
2002
0
            break;
2003
0
        }
2004
2005
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
2006
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
2007
0
            LOG_WARNING("failed to recycle tablet")
2008
0
                    .tag("instance_id", instance_id_)
2009
0
                    .tag("tablet_id", tablet_id);
2010
0
            return -1;
2011
0
        }
2012
0
        ++num_recycled_tablets;
2013
0
    }
2014
2015
1
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
2016
1
            .tag("instance_id", instance_id_)
2017
1
            .tag("total_tablets", tablets_with_refs.size());
2018
2019
    // Phase 3: Scan again to check if any ref count keys still exist
2020
1
    std::unique_ptr<Transaction> txn;
2021
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2022
1
    if (err != TxnErrorCode::TXN_OK) {
2023
0
        LOG_WARNING("failed to create txn for final check")
2024
0
                .tag("instance_id", instance_id_)
2025
0
                .tag("err", err);
2026
0
        return -1;
2027
0
    }
2028
2029
1
    std::unique_ptr<RangeGetIterator> iter;
2030
1
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2031
1
    if (err != TxnErrorCode::TXN_OK) {
2032
0
        LOG_WARNING("failed to create range iterator for final check")
2033
0
                .tag("instance_id", instance_id_)
2034
0
                .tag("err", err);
2035
0
        return -1;
2036
0
    }
2037
2038
1
    *has_unrecycled_rowsets = iter->has_next();
2039
1
    if (*has_unrecycled_rowsets) {
2040
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2041
0
                .tag("instance_id", instance_id_);
2042
0
    }
2043
2044
1
    return 0;
2045
1
}
2046
2047
17
int InstanceRecycler::recycle_indexes() {
2048
17
    const std::string task_name = "recycle_indexes";
2049
17
    int64_t num_scanned = 0;
2050
17
    int64_t num_expired = 0;
2051
17
    int64_t num_recycled = 0;
2052
17
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2053
2054
17
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2055
17
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2056
17
    std::string index_key0;
2057
17
    std::string index_key1;
2058
17
    recycle_index_key(index_key_info0, &index_key0);
2059
17
    recycle_index_key(index_key_info1, &index_key1);
2060
2061
17
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2062
2063
17
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2064
17
    register_recycle_task(task_name, start_time);
2065
2066
17
    DORIS_CLOUD_DEFER {
2067
17
        unregister_recycle_task(task_name);
2068
17
        int64_t cost =
2069
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2070
17
        metrics_context.finish_report();
2071
17
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2072
17
                .tag("instance_id", instance_id_)
2073
17
                .tag("num_scanned", num_scanned)
2074
17
                .tag("num_expired", num_expired)
2075
17
                .tag("num_recycled", num_recycled);
2076
17
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2066
2
    DORIS_CLOUD_DEFER {
2067
2
        unregister_recycle_task(task_name);
2068
2
        int64_t cost =
2069
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2070
2
        metrics_context.finish_report();
2071
2
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2072
2
                .tag("instance_id", instance_id_)
2073
2
                .tag("num_scanned", num_scanned)
2074
2
                .tag("num_expired", num_expired)
2075
2
                .tag("num_recycled", num_recycled);
2076
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2066
15
    DORIS_CLOUD_DEFER {
2067
15
        unregister_recycle_task(task_name);
2068
15
        int64_t cost =
2069
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2070
15
        metrics_context.finish_report();
2071
15
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2072
15
                .tag("instance_id", instance_id_)
2073
15
                .tag("num_scanned", num_scanned)
2074
15
                .tag("num_expired", num_expired)
2075
15
                .tag("num_recycled", num_recycled);
2076
15
    };
2077
2078
17
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2079
2080
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2081
17
    std::vector<std::string_view> index_keys;
2082
17
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2083
10
        ++num_scanned;
2084
10
        RecycleIndexPB index_pb;
2085
10
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2086
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2087
0
            return -1;
2088
0
        }
2089
10
        int64_t current_time = ::time(nullptr);
2090
10
        if (current_time <
2091
10
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2092
0
            return 0;
2093
0
        }
2094
10
        ++num_expired;
2095
        // decode index_id
2096
10
        auto k1 = k;
2097
10
        k1.remove_prefix(1);
2098
10
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2099
10
        decode_key(&k1, &out);
2100
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2101
10
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2102
10
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2103
10
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2104
10
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2105
        // Change state to RECYCLING
2106
10
        std::unique_ptr<Transaction> txn;
2107
10
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2108
10
        if (err != TxnErrorCode::TXN_OK) {
2109
0
            LOG_WARNING("failed to create txn").tag("err", err);
2110
0
            return -1;
2111
0
        }
2112
10
        std::string val;
2113
10
        err = txn->get(k, &val);
2114
10
        if (err ==
2115
10
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2116
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2117
0
            return 0;
2118
0
        }
2119
10
        if (err != TxnErrorCode::TXN_OK) {
2120
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2121
0
            return -1;
2122
0
        }
2123
10
        index_pb.Clear();
2124
10
        if (!index_pb.ParseFromString(val)) {
2125
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2126
0
            return -1;
2127
0
        }
2128
10
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2129
9
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2130
9
            txn->put(k, index_pb.SerializeAsString());
2131
9
            err = txn->commit();
2132
9
            if (err != TxnErrorCode::TXN_OK) {
2133
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2134
0
                return -1;
2135
0
            }
2136
9
        }
2137
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2138
1
            LOG_WARNING("failed to recycle tablets under index")
2139
1
                    .tag("table_id", index_pb.table_id())
2140
1
                    .tag("instance_id", instance_id_)
2141
1
                    .tag("index_id", index_id);
2142
1
            return -1;
2143
1
        }
2144
2145
9
        if (index_pb.has_db_id()) {
2146
            // Recycle the versioned keys
2147
3
            std::unique_ptr<Transaction> txn;
2148
3
            err = txn_kv_->create_txn(&txn);
2149
3
            if (err != TxnErrorCode::TXN_OK) {
2150
0
                LOG_WARNING("failed to create txn").tag("err", err);
2151
0
                return -1;
2152
0
            }
2153
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2154
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2155
3
            std::string index_inverted_key = versioned::index_inverted_key(
2156
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2157
3
            versioned_remove_all(txn.get(), meta_key);
2158
3
            txn->remove(index_key);
2159
3
            txn->remove(index_inverted_key);
2160
3
            err = txn->commit();
2161
3
            if (err != TxnErrorCode::TXN_OK) {
2162
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2163
0
                return -1;
2164
0
            }
2165
3
        }
2166
2167
9
        metrics_context.total_recycled_num = ++num_recycled;
2168
9
        metrics_context.report();
2169
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2170
9
        index_keys.push_back(k);
2171
9
        return 0;
2172
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2082
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2083
2
        ++num_scanned;
2084
2
        RecycleIndexPB index_pb;
2085
2
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2086
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2087
0
            return -1;
2088
0
        }
2089
2
        int64_t current_time = ::time(nullptr);
2090
2
        if (current_time <
2091
2
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2092
0
            return 0;
2093
0
        }
2094
2
        ++num_expired;
2095
        // decode index_id
2096
2
        auto k1 = k;
2097
2
        k1.remove_prefix(1);
2098
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2099
2
        decode_key(&k1, &out);
2100
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2101
2
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2102
2
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2103
2
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2104
2
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2105
        // Change state to RECYCLING
2106
2
        std::unique_ptr<Transaction> txn;
2107
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2108
2
        if (err != TxnErrorCode::TXN_OK) {
2109
0
            LOG_WARNING("failed to create txn").tag("err", err);
2110
0
            return -1;
2111
0
        }
2112
2
        std::string val;
2113
2
        err = txn->get(k, &val);
2114
2
        if (err ==
2115
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2116
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2117
0
            return 0;
2118
0
        }
2119
2
        if (err != TxnErrorCode::TXN_OK) {
2120
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2121
0
            return -1;
2122
0
        }
2123
2
        index_pb.Clear();
2124
2
        if (!index_pb.ParseFromString(val)) {
2125
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2126
0
            return -1;
2127
0
        }
2128
2
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2129
1
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2130
1
            txn->put(k, index_pb.SerializeAsString());
2131
1
            err = txn->commit();
2132
1
            if (err != TxnErrorCode::TXN_OK) {
2133
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2134
0
                return -1;
2135
0
            }
2136
1
        }
2137
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2138
1
            LOG_WARNING("failed to recycle tablets under index")
2139
1
                    .tag("table_id", index_pb.table_id())
2140
1
                    .tag("instance_id", instance_id_)
2141
1
                    .tag("index_id", index_id);
2142
1
            return -1;
2143
1
        }
2144
2145
1
        if (index_pb.has_db_id()) {
2146
            // Recycle the versioned keys
2147
1
            std::unique_ptr<Transaction> txn;
2148
1
            err = txn_kv_->create_txn(&txn);
2149
1
            if (err != TxnErrorCode::TXN_OK) {
2150
0
                LOG_WARNING("failed to create txn").tag("err", err);
2151
0
                return -1;
2152
0
            }
2153
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2154
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2155
1
            std::string index_inverted_key = versioned::index_inverted_key(
2156
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2157
1
            versioned_remove_all(txn.get(), meta_key);
2158
1
            txn->remove(index_key);
2159
1
            txn->remove(index_inverted_key);
2160
1
            err = txn->commit();
2161
1
            if (err != TxnErrorCode::TXN_OK) {
2162
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2163
0
                return -1;
2164
0
            }
2165
1
        }
2166
2167
1
        metrics_context.total_recycled_num = ++num_recycled;
2168
1
        metrics_context.report();
2169
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2170
1
        index_keys.push_back(k);
2171
1
        return 0;
2172
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2082
8
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2083
8
        ++num_scanned;
2084
8
        RecycleIndexPB index_pb;
2085
8
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2086
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2087
0
            return -1;
2088
0
        }
2089
8
        int64_t current_time = ::time(nullptr);
2090
8
        if (current_time <
2091
8
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2092
0
            return 0;
2093
0
        }
2094
8
        ++num_expired;
2095
        // decode index_id
2096
8
        auto k1 = k;
2097
8
        k1.remove_prefix(1);
2098
8
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2099
8
        decode_key(&k1, &out);
2100
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2101
8
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2102
8
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2103
8
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2104
8
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2105
        // Change state to RECYCLING
2106
8
        std::unique_ptr<Transaction> txn;
2107
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2108
8
        if (err != TxnErrorCode::TXN_OK) {
2109
0
            LOG_WARNING("failed to create txn").tag("err", err);
2110
0
            return -1;
2111
0
        }
2112
8
        std::string val;
2113
8
        err = txn->get(k, &val);
2114
8
        if (err ==
2115
8
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2116
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2117
0
            return 0;
2118
0
        }
2119
8
        if (err != TxnErrorCode::TXN_OK) {
2120
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2121
0
            return -1;
2122
0
        }
2123
8
        index_pb.Clear();
2124
8
        if (!index_pb.ParseFromString(val)) {
2125
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2126
0
            return -1;
2127
0
        }
2128
8
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2129
8
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2130
8
            txn->put(k, index_pb.SerializeAsString());
2131
8
            err = txn->commit();
2132
8
            if (err != TxnErrorCode::TXN_OK) {
2133
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2134
0
                return -1;
2135
0
            }
2136
8
        }
2137
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2138
0
            LOG_WARNING("failed to recycle tablets under index")
2139
0
                    .tag("table_id", index_pb.table_id())
2140
0
                    .tag("instance_id", instance_id_)
2141
0
                    .tag("index_id", index_id);
2142
0
            return -1;
2143
0
        }
2144
2145
8
        if (index_pb.has_db_id()) {
2146
            // Recycle the versioned keys
2147
2
            std::unique_ptr<Transaction> txn;
2148
2
            err = txn_kv_->create_txn(&txn);
2149
2
            if (err != TxnErrorCode::TXN_OK) {
2150
0
                LOG_WARNING("failed to create txn").tag("err", err);
2151
0
                return -1;
2152
0
            }
2153
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2154
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2155
2
            std::string index_inverted_key = versioned::index_inverted_key(
2156
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2157
2
            versioned_remove_all(txn.get(), meta_key);
2158
2
            txn->remove(index_key);
2159
2
            txn->remove(index_inverted_key);
2160
2
            err = txn->commit();
2161
2
            if (err != TxnErrorCode::TXN_OK) {
2162
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2163
0
                return -1;
2164
0
            }
2165
2
        }
2166
2167
8
        metrics_context.total_recycled_num = ++num_recycled;
2168
8
        metrics_context.report();
2169
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2170
8
        index_keys.push_back(k);
2171
8
        return 0;
2172
8
    };
2173
2174
17
    auto loop_done = [&index_keys, this]() -> int {
2175
6
        if (index_keys.empty()) return 0;
2176
5
        DORIS_CLOUD_DEFER {
2177
5
            index_keys.clear();
2178
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2176
1
        DORIS_CLOUD_DEFER {
2177
1
            index_keys.clear();
2178
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2176
4
        DORIS_CLOUD_DEFER {
2177
4
            index_keys.clear();
2178
4
        };
2179
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2180
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2181
0
            return -1;
2182
0
        }
2183
5
        return 0;
2184
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2174
2
    auto loop_done = [&index_keys, this]() -> int {
2175
2
        if (index_keys.empty()) return 0;
2176
1
        DORIS_CLOUD_DEFER {
2177
1
            index_keys.clear();
2178
1
        };
2179
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2180
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2181
0
            return -1;
2182
0
        }
2183
1
        return 0;
2184
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2174
4
    auto loop_done = [&index_keys, this]() -> int {
2175
4
        if (index_keys.empty()) return 0;
2176
4
        DORIS_CLOUD_DEFER {
2177
4
            index_keys.clear();
2178
4
        };
2179
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2180
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2181
0
            return -1;
2182
0
        }
2183
4
        return 0;
2184
4
    };
2185
2186
17
    if (config::enable_recycler_stats_metrics) {
2187
0
        scan_and_statistics_indexes();
2188
0
    }
2189
    // recycle_func and loop_done for scan and recycle
2190
17
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
2191
17
}
2192
2193
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
2194
8.24k
                             int64_t tablet_id) {
2195
8.24k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
2196
2197
8.24k
    std::unique_ptr<Transaction> txn;
2198
8.24k
    TxnErrorCode err = txn_kv->create_txn(&txn);
2199
8.24k
    if (err != TxnErrorCode::TXN_OK) {
2200
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
2201
0
                     << " tablet_id=" << tablet_id << " err=" << err;
2202
0
        return false;
2203
0
    }
2204
2205
8.24k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
2206
8.24k
    std::string tablet_idx_val;
2207
8.24k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
2208
8.24k
    if (TxnErrorCode::TXN_OK != err) {
2209
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
2210
0
                     << " tablet_id=" << tablet_id << " err=" << err
2211
0
                     << " key=" << hex(tablet_idx_key);
2212
0
        return false;
2213
0
    }
2214
2215
8.24k
    TabletIndexPB tablet_idx_pb;
2216
8.24k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
2217
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
2218
0
                     << " tablet_id=" << tablet_id;
2219
0
        return false;
2220
0
    }
2221
2222
8.24k
    if (!tablet_idx_pb.has_db_id()) {
2223
        // In the previous version, the db_id was not set in the index_pb.
2224
        // If updating to the version which enable txn lazy commit, the db_id will be set.
2225
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
2226
0
                  << " instance_id=" << instance_id
2227
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
2228
0
        return true;
2229
0
    }
2230
2231
8.24k
    std::string ver_val;
2232
8.24k
    std::string ver_key =
2233
8.24k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
2234
8.24k
                                   tablet_idx_pb.partition_id()});
2235
8.24k
    err = txn->get(ver_key, &ver_val);
2236
2237
8.24k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
2238
204
        LOG(INFO) << ""
2239
204
                     "partition version not found, instance_id="
2240
204
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
2241
204
                  << " table_id=" << tablet_idx_pb.table_id()
2242
204
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
2243
204
                  << " key=" << hex(ver_key);
2244
204
        return true;
2245
204
    }
2246
2247
8.03k
    if (TxnErrorCode::TXN_OK != err) {
2248
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
2249
0
                     << " db_id=" << tablet_idx_pb.db_id()
2250
0
                     << " table_id=" << tablet_idx_pb.table_id()
2251
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2252
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
2253
0
        return false;
2254
0
    }
2255
2256
8.03k
    VersionPB version_pb;
2257
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
2258
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
2259
0
                     << " db_id=" << tablet_idx_pb.db_id()
2260
0
                     << " table_id=" << tablet_idx_pb.table_id()
2261
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2262
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
2263
0
        return false;
2264
0
    }
2265
2266
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
2267
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
2268
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
2269
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
2270
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
2271
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
2272
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
2273
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
2274
4.00k
                     << " key=" << hex(ver_key);
2275
4.00k
        return false;
2276
4.00k
    }
2277
4.03k
    return true;
2278
8.03k
}
2279
2280
15
int InstanceRecycler::recycle_partitions() {
2281
15
    const std::string task_name = "recycle_partitions";
2282
15
    int64_t num_scanned = 0;
2283
15
    int64_t num_expired = 0;
2284
15
    int64_t num_recycled = 0;
2285
15
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2286
2287
15
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
2288
15
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
2289
15
    std::string part_key0;
2290
15
    std::string part_key1;
2291
15
    recycle_partition_key(part_key_info0, &part_key0);
2292
15
    recycle_partition_key(part_key_info1, &part_key1);
2293
2294
15
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
2295
2296
15
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2297
15
    register_recycle_task(task_name, start_time);
2298
2299
15
    DORIS_CLOUD_DEFER {
2300
15
        unregister_recycle_task(task_name);
2301
15
        int64_t cost =
2302
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2303
15
        metrics_context.finish_report();
2304
15
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2305
15
                .tag("instance_id", instance_id_)
2306
15
                .tag("num_scanned", num_scanned)
2307
15
                .tag("num_expired", num_expired)
2308
15
                .tag("num_recycled", num_recycled);
2309
15
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2299
2
    DORIS_CLOUD_DEFER {
2300
2
        unregister_recycle_task(task_name);
2301
2
        int64_t cost =
2302
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2303
2
        metrics_context.finish_report();
2304
2
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2305
2
                .tag("instance_id", instance_id_)
2306
2
                .tag("num_scanned", num_scanned)
2307
2
                .tag("num_expired", num_expired)
2308
2
                .tag("num_recycled", num_recycled);
2309
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2299
13
    DORIS_CLOUD_DEFER {
2300
13
        unregister_recycle_task(task_name);
2301
13
        int64_t cost =
2302
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2303
13
        metrics_context.finish_report();
2304
13
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2305
13
                .tag("instance_id", instance_id_)
2306
13
                .tag("num_scanned", num_scanned)
2307
13
                .tag("num_expired", num_expired)
2308
13
                .tag("num_recycled", num_recycled);
2309
13
    };
2310
2311
15
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2312
2313
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
2314
15
    std::vector<std::string_view> partition_keys;
2315
15
    std::vector<std::string> partition_version_keys;
2316
15
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2317
9
        ++num_scanned;
2318
9
        RecyclePartitionPB part_pb;
2319
9
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2320
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2321
0
            return -1;
2322
0
        }
2323
9
        int64_t current_time = ::time(nullptr);
2324
9
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2325
9
                                                            &earlest_ts)) { // not expired
2326
0
            return 0;
2327
0
        }
2328
9
        ++num_expired;
2329
        // decode partition_id
2330
9
        auto k1 = k;
2331
9
        k1.remove_prefix(1);
2332
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2333
9
        decode_key(&k1, &out);
2334
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2335
9
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2336
9
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2337
9
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2338
9
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2339
        // Change state to RECYCLING
2340
9
        std::unique_ptr<Transaction> txn;
2341
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2342
9
        if (err != TxnErrorCode::TXN_OK) {
2343
0
            LOG_WARNING("failed to create txn").tag("err", err);
2344
0
            return -1;
2345
0
        }
2346
9
        std::string val;
2347
9
        err = txn->get(k, &val);
2348
9
        if (err ==
2349
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2350
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2351
0
            return 0;
2352
0
        }
2353
9
        if (err != TxnErrorCode::TXN_OK) {
2354
0
            LOG_WARNING("failed to get kv");
2355
0
            return -1;
2356
0
        }
2357
9
        part_pb.Clear();
2358
9
        if (!part_pb.ParseFromString(val)) {
2359
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2360
0
            return -1;
2361
0
        }
2362
        // Partitions with PREPARED state MUST have no data
2363
9
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2364
8
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2365
8
            txn->put(k, part_pb.SerializeAsString());
2366
8
            err = txn->commit();
2367
8
            if (err != TxnErrorCode::TXN_OK) {
2368
0
                LOG_WARNING("failed to commit txn: {}", err);
2369
0
                return -1;
2370
0
            }
2371
8
        }
2372
2373
9
        int ret = 0;
2374
33
        for (int64_t index_id : part_pb.index_id()) {
2375
33
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2376
1
                LOG_WARNING("failed to recycle tablets under partition")
2377
1
                        .tag("table_id", part_pb.table_id())
2378
1
                        .tag("instance_id", instance_id_)
2379
1
                        .tag("index_id", index_id)
2380
1
                        .tag("partition_id", partition_id);
2381
1
                ret = -1;
2382
1
            }
2383
33
        }
2384
9
        if (ret == 0 && part_pb.has_db_id()) {
2385
            // Recycle the versioned keys
2386
8
            std::unique_ptr<Transaction> txn;
2387
8
            err = txn_kv_->create_txn(&txn);
2388
8
            if (err != TxnErrorCode::TXN_OK) {
2389
0
                LOG_WARNING("failed to create txn").tag("err", err);
2390
0
                return -1;
2391
0
            }
2392
8
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2393
8
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2394
8
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2395
8
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2396
8
            std::string partition_version_key =
2397
8
                    versioned::partition_version_key({instance_id_, partition_id});
2398
8
            versioned_remove_all(txn.get(), meta_key);
2399
8
            txn->remove(index_key);
2400
8
            txn->remove(inverted_index_key);
2401
8
            versioned_remove_all(txn.get(), partition_version_key);
2402
8
            err = txn->commit();
2403
8
            if (err != TxnErrorCode::TXN_OK) {
2404
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2405
0
                return -1;
2406
0
            }
2407
8
        }
2408
2409
9
        if (ret == 0) {
2410
8
            ++num_recycled;
2411
8
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2412
8
            partition_keys.push_back(k);
2413
8
            if (part_pb.db_id() > 0) {
2414
8
                partition_version_keys.push_back(partition_version_key(
2415
8
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2416
8
            }
2417
8
            metrics_context.total_recycled_num = num_recycled;
2418
8
            metrics_context.report();
2419
8
        }
2420
9
        return ret;
2421
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2316
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2317
2
        ++num_scanned;
2318
2
        RecyclePartitionPB part_pb;
2319
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2320
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2321
0
            return -1;
2322
0
        }
2323
2
        int64_t current_time = ::time(nullptr);
2324
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2325
2
                                                            &earlest_ts)) { // not expired
2326
0
            return 0;
2327
0
        }
2328
2
        ++num_expired;
2329
        // decode partition_id
2330
2
        auto k1 = k;
2331
2
        k1.remove_prefix(1);
2332
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2333
2
        decode_key(&k1, &out);
2334
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2335
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2336
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2337
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2338
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2339
        // Change state to RECYCLING
2340
2
        std::unique_ptr<Transaction> txn;
2341
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2342
2
        if (err != TxnErrorCode::TXN_OK) {
2343
0
            LOG_WARNING("failed to create txn").tag("err", err);
2344
0
            return -1;
2345
0
        }
2346
2
        std::string val;
2347
2
        err = txn->get(k, &val);
2348
2
        if (err ==
2349
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2350
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2351
0
            return 0;
2352
0
        }
2353
2
        if (err != TxnErrorCode::TXN_OK) {
2354
0
            LOG_WARNING("failed to get kv");
2355
0
            return -1;
2356
0
        }
2357
2
        part_pb.Clear();
2358
2
        if (!part_pb.ParseFromString(val)) {
2359
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2360
0
            return -1;
2361
0
        }
2362
        // Partitions with PREPARED state MUST have no data
2363
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2364
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2365
1
            txn->put(k, part_pb.SerializeAsString());
2366
1
            err = txn->commit();
2367
1
            if (err != TxnErrorCode::TXN_OK) {
2368
0
                LOG_WARNING("failed to commit txn: {}", err);
2369
0
                return -1;
2370
0
            }
2371
1
        }
2372
2373
2
        int ret = 0;
2374
2
        for (int64_t index_id : part_pb.index_id()) {
2375
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2376
1
                LOG_WARNING("failed to recycle tablets under partition")
2377
1
                        .tag("table_id", part_pb.table_id())
2378
1
                        .tag("instance_id", instance_id_)
2379
1
                        .tag("index_id", index_id)
2380
1
                        .tag("partition_id", partition_id);
2381
1
                ret = -1;
2382
1
            }
2383
2
        }
2384
2
        if (ret == 0 && part_pb.has_db_id()) {
2385
            // Recycle the versioned keys
2386
1
            std::unique_ptr<Transaction> txn;
2387
1
            err = txn_kv_->create_txn(&txn);
2388
1
            if (err != TxnErrorCode::TXN_OK) {
2389
0
                LOG_WARNING("failed to create txn").tag("err", err);
2390
0
                return -1;
2391
0
            }
2392
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2393
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2394
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2395
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2396
1
            std::string partition_version_key =
2397
1
                    versioned::partition_version_key({instance_id_, partition_id});
2398
1
            versioned_remove_all(txn.get(), meta_key);
2399
1
            txn->remove(index_key);
2400
1
            txn->remove(inverted_index_key);
2401
1
            versioned_remove_all(txn.get(), partition_version_key);
2402
1
            err = txn->commit();
2403
1
            if (err != TxnErrorCode::TXN_OK) {
2404
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2405
0
                return -1;
2406
0
            }
2407
1
        }
2408
2409
2
        if (ret == 0) {
2410
1
            ++num_recycled;
2411
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2412
1
            partition_keys.push_back(k);
2413
1
            if (part_pb.db_id() > 0) {
2414
1
                partition_version_keys.push_back(partition_version_key(
2415
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2416
1
            }
2417
1
            metrics_context.total_recycled_num = num_recycled;
2418
1
            metrics_context.report();
2419
1
        }
2420
2
        return ret;
2421
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2316
7
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2317
7
        ++num_scanned;
2318
7
        RecyclePartitionPB part_pb;
2319
7
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2320
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2321
0
            return -1;
2322
0
        }
2323
7
        int64_t current_time = ::time(nullptr);
2324
7
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2325
7
                                                            &earlest_ts)) { // not expired
2326
0
            return 0;
2327
0
        }
2328
7
        ++num_expired;
2329
        // decode partition_id
2330
7
        auto k1 = k;
2331
7
        k1.remove_prefix(1);
2332
7
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2333
7
        decode_key(&k1, &out);
2334
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2335
7
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2336
7
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2337
7
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2338
7
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2339
        // Change state to RECYCLING
2340
7
        std::unique_ptr<Transaction> txn;
2341
7
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2342
7
        if (err != TxnErrorCode::TXN_OK) {
2343
0
            LOG_WARNING("failed to create txn").tag("err", err);
2344
0
            return -1;
2345
0
        }
2346
7
        std::string val;
2347
7
        err = txn->get(k, &val);
2348
7
        if (err ==
2349
7
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2350
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2351
0
            return 0;
2352
0
        }
2353
7
        if (err != TxnErrorCode::TXN_OK) {
2354
0
            LOG_WARNING("failed to get kv");
2355
0
            return -1;
2356
0
        }
2357
7
        part_pb.Clear();
2358
7
        if (!part_pb.ParseFromString(val)) {
2359
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2360
0
            return -1;
2361
0
        }
2362
        // Partitions with PREPARED state MUST have no data
2363
7
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2364
7
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2365
7
            txn->put(k, part_pb.SerializeAsString());
2366
7
            err = txn->commit();
2367
7
            if (err != TxnErrorCode::TXN_OK) {
2368
0
                LOG_WARNING("failed to commit txn: {}", err);
2369
0
                return -1;
2370
0
            }
2371
7
        }
2372
2373
7
        int ret = 0;
2374
31
        for (int64_t index_id : part_pb.index_id()) {
2375
31
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2376
0
                LOG_WARNING("failed to recycle tablets under partition")
2377
0
                        .tag("table_id", part_pb.table_id())
2378
0
                        .tag("instance_id", instance_id_)
2379
0
                        .tag("index_id", index_id)
2380
0
                        .tag("partition_id", partition_id);
2381
0
                ret = -1;
2382
0
            }
2383
31
        }
2384
7
        if (ret == 0 && part_pb.has_db_id()) {
2385
            // Recycle the versioned keys
2386
7
            std::unique_ptr<Transaction> txn;
2387
7
            err = txn_kv_->create_txn(&txn);
2388
7
            if (err != TxnErrorCode::TXN_OK) {
2389
0
                LOG_WARNING("failed to create txn").tag("err", err);
2390
0
                return -1;
2391
0
            }
2392
7
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2393
7
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2394
7
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2395
7
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2396
7
            std::string partition_version_key =
2397
7
                    versioned::partition_version_key({instance_id_, partition_id});
2398
7
            versioned_remove_all(txn.get(), meta_key);
2399
7
            txn->remove(index_key);
2400
7
            txn->remove(inverted_index_key);
2401
7
            versioned_remove_all(txn.get(), partition_version_key);
2402
7
            err = txn->commit();
2403
7
            if (err != TxnErrorCode::TXN_OK) {
2404
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2405
0
                return -1;
2406
0
            }
2407
7
        }
2408
2409
7
        if (ret == 0) {
2410
7
            ++num_recycled;
2411
7
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2412
7
            partition_keys.push_back(k);
2413
7
            if (part_pb.db_id() > 0) {
2414
7
                partition_version_keys.push_back(partition_version_key(
2415
7
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2416
7
            }
2417
7
            metrics_context.total_recycled_num = num_recycled;
2418
7
            metrics_context.report();
2419
7
        }
2420
7
        return ret;
2421
7
    };
2422
2423
15
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2424
5
        if (partition_keys.empty()) return 0;
2425
4
        DORIS_CLOUD_DEFER {
2426
4
            partition_keys.clear();
2427
4
            partition_version_keys.clear();
2428
4
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2425
1
        DORIS_CLOUD_DEFER {
2426
1
            partition_keys.clear();
2427
1
            partition_version_keys.clear();
2428
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2425
3
        DORIS_CLOUD_DEFER {
2426
3
            partition_keys.clear();
2427
3
            partition_version_keys.clear();
2428
3
        };
2429
4
        std::unique_ptr<Transaction> txn;
2430
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2431
4
        if (err != TxnErrorCode::TXN_OK) {
2432
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2433
0
            return -1;
2434
0
        }
2435
8
        for (auto& k : partition_keys) {
2436
8
            txn->remove(k);
2437
8
        }
2438
8
        for (auto& k : partition_version_keys) {
2439
8
            txn->remove(k);
2440
8
        }
2441
4
        err = txn->commit();
2442
4
        if (err != TxnErrorCode::TXN_OK) {
2443
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2444
0
                         << " err=" << err;
2445
0
            return -1;
2446
0
        }
2447
4
        return 0;
2448
4
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2423
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2424
2
        if (partition_keys.empty()) return 0;
2425
1
        DORIS_CLOUD_DEFER {
2426
1
            partition_keys.clear();
2427
1
            partition_version_keys.clear();
2428
1
        };
2429
1
        std::unique_ptr<Transaction> txn;
2430
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2431
1
        if (err != TxnErrorCode::TXN_OK) {
2432
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2433
0
            return -1;
2434
0
        }
2435
1
        for (auto& k : partition_keys) {
2436
1
            txn->remove(k);
2437
1
        }
2438
1
        for (auto& k : partition_version_keys) {
2439
1
            txn->remove(k);
2440
1
        }
2441
1
        err = txn->commit();
2442
1
        if (err != TxnErrorCode::TXN_OK) {
2443
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2444
0
                         << " err=" << err;
2445
0
            return -1;
2446
0
        }
2447
1
        return 0;
2448
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2423
3
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2424
3
        if (partition_keys.empty()) return 0;
2425
3
        DORIS_CLOUD_DEFER {
2426
3
            partition_keys.clear();
2427
3
            partition_version_keys.clear();
2428
3
        };
2429
3
        std::unique_ptr<Transaction> txn;
2430
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2431
3
        if (err != TxnErrorCode::TXN_OK) {
2432
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2433
0
            return -1;
2434
0
        }
2435
7
        for (auto& k : partition_keys) {
2436
7
            txn->remove(k);
2437
7
        }
2438
7
        for (auto& k : partition_version_keys) {
2439
7
            txn->remove(k);
2440
7
        }
2441
3
        err = txn->commit();
2442
3
        if (err != TxnErrorCode::TXN_OK) {
2443
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2444
0
                         << " err=" << err;
2445
0
            return -1;
2446
0
        }
2447
3
        return 0;
2448
3
    };
2449
2450
15
    if (config::enable_recycler_stats_metrics) {
2451
0
        scan_and_statistics_partitions();
2452
0
    }
2453
    // recycle_func and loop_done for scan and recycle
2454
15
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
2455
15
}
2456
2457
14
int InstanceRecycler::recycle_versions() {
2458
14
    if (should_recycle_versioned_keys()) {
2459
2
        return recycle_orphan_partitions();
2460
2
    }
2461
2462
12
    int64_t num_scanned = 0;
2463
12
    int64_t num_recycled = 0;
2464
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
2465
2466
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
2467
2468
12
    auto start_time = steady_clock::now();
2469
2470
12
    DORIS_CLOUD_DEFER {
2471
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2472
12
        metrics_context.finish_report();
2473
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
2474
12
                .tag("instance_id", instance_id_)
2475
12
                .tag("num_scanned", num_scanned)
2476
12
                .tag("num_recycled", num_recycled);
2477
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
2470
12
    DORIS_CLOUD_DEFER {
2471
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2472
12
        metrics_context.finish_report();
2473
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
2474
12
                .tag("instance_id", instance_id_)
2475
12
                .tag("num_scanned", num_scanned)
2476
12
                .tag("num_recycled", num_recycled);
2477
12
    };
2478
2479
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
2480
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
2481
12
    int64_t last_scanned_table_id = 0;
2482
12
    bool is_recycled = false; // Is last scanned kv recycled
2483
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
2484
12
                         &metrics_context, this](std::string_view k, std::string_view) {
2485
2
        ++num_scanned;
2486
2
        auto k1 = k;
2487
2
        k1.remove_prefix(1);
2488
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
2489
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2490
2
        decode_key(&k1, &out);
2491
2
        DCHECK_EQ(out.size(), 6) << k;
2492
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
2493
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
2494
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
2495
0
            return 0;
2496
0
        }
2497
2
        last_scanned_table_id = table_id;
2498
2
        is_recycled = false;
2499
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
2500
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
2501
2
        std::unique_ptr<Transaction> txn;
2502
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2503
2
        if (err != TxnErrorCode::TXN_OK) {
2504
0
            return -1;
2505
0
        }
2506
2
        std::unique_ptr<RangeGetIterator> iter;
2507
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
2508
2
        if (err != TxnErrorCode::TXN_OK) {
2509
0
            return -1;
2510
0
        }
2511
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
2512
1
            return 0;
2513
1
        }
2514
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2515
        // 1. Remove all partition version kvs of this table
2516
1
        auto partition_version_key_begin =
2517
1
                partition_version_key({instance_id_, db_id, table_id, 0});
2518
1
        auto partition_version_key_end =
2519
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
2520
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
2521
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
2522
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
2523
1
                     << " table_id=" << table_id;
2524
        // 2. Remove the table version kv of this table
2525
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
2526
1
        txn->remove(tbl_version_key);
2527
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
2528
        // 3. Remove mow delete bitmap update lock and tablet job lock
2529
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2530
1
        txn->remove(lock_key);
2531
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2532
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2533
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2534
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
2535
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2536
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2537
1
                     << " table_id=" << table_id;
2538
1
        err = txn->commit();
2539
1
        if (err != TxnErrorCode::TXN_OK) {
2540
0
            return -1;
2541
0
        }
2542
1
        metrics_context.total_recycled_num = ++num_recycled;
2543
1
        metrics_context.report();
2544
1
        is_recycled = true;
2545
1
        return 0;
2546
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2484
2
                         &metrics_context, this](std::string_view k, std::string_view) {
2485
2
        ++num_scanned;
2486
2
        auto k1 = k;
2487
2
        k1.remove_prefix(1);
2488
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
2489
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2490
2
        decode_key(&k1, &out);
2491
2
        DCHECK_EQ(out.size(), 6) << k;
2492
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
2493
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
2494
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
2495
0
            return 0;
2496
0
        }
2497
2
        last_scanned_table_id = table_id;
2498
2
        is_recycled = false;
2499
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
2500
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
2501
2
        std::unique_ptr<Transaction> txn;
2502
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2503
2
        if (err != TxnErrorCode::TXN_OK) {
2504
0
            return -1;
2505
0
        }
2506
2
        std::unique_ptr<RangeGetIterator> iter;
2507
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
2508
2
        if (err != TxnErrorCode::TXN_OK) {
2509
0
            return -1;
2510
0
        }
2511
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
2512
1
            return 0;
2513
1
        }
2514
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2515
        // 1. Remove all partition version kvs of this table
2516
1
        auto partition_version_key_begin =
2517
1
                partition_version_key({instance_id_, db_id, table_id, 0});
2518
1
        auto partition_version_key_end =
2519
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
2520
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
2521
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
2522
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
2523
1
                     << " table_id=" << table_id;
2524
        // 2. Remove the table version kv of this table
2525
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
2526
1
        txn->remove(tbl_version_key);
2527
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
2528
        // 3. Remove mow delete bitmap update lock and tablet job lock
2529
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2530
1
        txn->remove(lock_key);
2531
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2532
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2533
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2534
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
2535
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2536
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2537
1
                     << " table_id=" << table_id;
2538
1
        err = txn->commit();
2539
1
        if (err != TxnErrorCode::TXN_OK) {
2540
0
            return -1;
2541
0
        }
2542
1
        metrics_context.total_recycled_num = ++num_recycled;
2543
1
        metrics_context.report();
2544
1
        is_recycled = true;
2545
1
        return 0;
2546
1
    };
2547
2548
12
    if (config::enable_recycler_stats_metrics) {
2549
0
        scan_and_statistics_versions();
2550
0
    }
2551
    // recycle_func and loop_done for scan and recycle
2552
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
2553
14
}
2554
2555
3
int InstanceRecycler::recycle_orphan_partitions() {
2556
3
    int64_t num_scanned = 0;
2557
3
    int64_t num_recycled = 0;
2558
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
2559
2560
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
2561
3
            .tag("instance_id", instance_id_);
2562
2563
3
    auto start_time = steady_clock::now();
2564
2565
3
    DORIS_CLOUD_DEFER {
2566
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2567
3
        metrics_context.finish_report();
2568
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
2569
3
                .tag("instance_id", instance_id_)
2570
3
                .tag("num_scanned", num_scanned)
2571
3
                .tag("num_recycled", num_recycled);
2572
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
2565
3
    DORIS_CLOUD_DEFER {
2566
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2567
3
        metrics_context.finish_report();
2568
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
2569
3
                .tag("instance_id", instance_id_)
2570
3
                .tag("num_scanned", num_scanned)
2571
3
                .tag("num_recycled", num_recycled);
2572
3
    };
2573
2574
3
    bool is_empty_table = false;        // whether the table has no indexes
2575
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
2576
3
    int64_t current_table_id = 0;       // current scanning table id
2577
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
2578
3
                         &current_table_id, &is_table_kvs_recycled,
2579
3
                         this](std::string_view k, std::string_view) {
2580
2
        ++num_scanned;
2581
2582
2
        std::string_view k1(k);
2583
2
        int64_t db_id, table_id, partition_id;
2584
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
2585
2
                                                            &partition_id)) {
2586
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
2587
0
            return -1;
2588
2
        } else if (table_id != current_table_id) {
2589
2
            current_table_id = table_id;
2590
2
            is_table_kvs_recycled = false;
2591
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
2592
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
2593
2
            if (err != TxnErrorCode::TXN_OK) {
2594
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
2595
0
                             << " table_id=" << table_id << " err=" << err;
2596
0
                return -1;
2597
0
            }
2598
2
        }
2599
2600
2
        if (!is_empty_table) {
2601
            // table is not empty, skip recycle
2602
1
            return 0;
2603
1
        }
2604
2605
1
        std::unique_ptr<Transaction> txn;
2606
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2607
1
        if (err != TxnErrorCode::TXN_OK) {
2608
0
            return -1;
2609
0
        }
2610
2611
        // 1. Remove all partition related kvs
2612
1
        std::string partition_meta_key =
2613
1
                versioned::meta_partition_key({instance_id_, partition_id});
2614
1
        std::string partition_index_key =
2615
1
                versioned::partition_index_key({instance_id_, partition_id});
2616
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
2617
1
                {instance_id_, db_id, table_id, partition_id});
2618
1
        std::string partition_version_key =
2619
1
                versioned::partition_version_key({instance_id_, partition_id});
2620
1
        txn->remove(partition_index_key);
2621
1
        txn->remove(partition_inverted_key);
2622
1
        versioned_remove_all(txn.get(), partition_meta_key);
2623
1
        versioned_remove_all(txn.get(), partition_version_key);
2624
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
2625
1
                     << " table_id=" << table_id << " db_id=" << db_id
2626
1
                     << " partition_meta_key=" << hex(partition_meta_key)
2627
1
                     << " partition_version_key=" << hex(partition_version_key);
2628
2629
1
        if (!is_table_kvs_recycled) {
2630
1
            is_table_kvs_recycled = true;
2631
2632
            // 2. Remove the table version kv of this table
2633
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
2634
1
            versioned_remove_all(txn.get(), table_version_key);
2635
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
2636
            // 3. Remove mow delete bitmap update lock and tablet job lock
2637
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2638
1
            txn->remove(lock_key);
2639
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2640
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2641
1
            std::string tablet_job_key_end =
2642
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2643
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
2644
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2645
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2646
1
                         << " table_id=" << table_id;
2647
1
        }
2648
2649
1
        err = txn->commit();
2650
1
        if (err != TxnErrorCode::TXN_OK) {
2651
0
            return -1;
2652
0
        }
2653
1
        metrics_context.total_recycled_num = ++num_recycled;
2654
1
        metrics_context.report();
2655
1
        return 0;
2656
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
2579
2
                         this](std::string_view k, std::string_view) {
2580
2
        ++num_scanned;
2581
2582
2
        std::string_view k1(k);
2583
2
        int64_t db_id, table_id, partition_id;
2584
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
2585
2
                                                            &partition_id)) {
2586
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
2587
0
            return -1;
2588
2
        } else if (table_id != current_table_id) {
2589
2
            current_table_id = table_id;
2590
2
            is_table_kvs_recycled = false;
2591
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
2592
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
2593
2
            if (err != TxnErrorCode::TXN_OK) {
2594
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
2595
0
                             << " table_id=" << table_id << " err=" << err;
2596
0
                return -1;
2597
0
            }
2598
2
        }
2599
2600
2
        if (!is_empty_table) {
2601
            // table is not empty, skip recycle
2602
1
            return 0;
2603
1
        }
2604
2605
1
        std::unique_ptr<Transaction> txn;
2606
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2607
1
        if (err != TxnErrorCode::TXN_OK) {
2608
0
            return -1;
2609
0
        }
2610
2611
        // 1. Remove all partition related kvs
2612
1
        std::string partition_meta_key =
2613
1
                versioned::meta_partition_key({instance_id_, partition_id});
2614
1
        std::string partition_index_key =
2615
1
                versioned::partition_index_key({instance_id_, partition_id});
2616
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
2617
1
                {instance_id_, db_id, table_id, partition_id});
2618
1
        std::string partition_version_key =
2619
1
                versioned::partition_version_key({instance_id_, partition_id});
2620
1
        txn->remove(partition_index_key);
2621
1
        txn->remove(partition_inverted_key);
2622
1
        versioned_remove_all(txn.get(), partition_meta_key);
2623
1
        versioned_remove_all(txn.get(), partition_version_key);
2624
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
2625
1
                     << " table_id=" << table_id << " db_id=" << db_id
2626
1
                     << " partition_meta_key=" << hex(partition_meta_key)
2627
1
                     << " partition_version_key=" << hex(partition_version_key);
2628
2629
1
        if (!is_table_kvs_recycled) {
2630
1
            is_table_kvs_recycled = true;
2631
2632
            // 2. Remove the table version kv of this table
2633
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
2634
1
            versioned_remove_all(txn.get(), table_version_key);
2635
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
2636
            // 3. Remove mow delete bitmap update lock and tablet job lock
2637
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2638
1
            txn->remove(lock_key);
2639
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2640
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2641
1
            std::string tablet_job_key_end =
2642
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2643
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
2644
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2645
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2646
1
                         << " table_id=" << table_id;
2647
1
        }
2648
2649
1
        err = txn->commit();
2650
1
        if (err != TxnErrorCode::TXN_OK) {
2651
0
            return -1;
2652
0
        }
2653
1
        metrics_context.total_recycled_num = ++num_recycled;
2654
1
        metrics_context.report();
2655
1
        return 0;
2656
1
    };
2657
2658
    // recycle_func and loop_done for scan and recycle
2659
3
    return scan_and_recycle(
2660
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
2661
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
2662
3
            std::move(recycle_func));
2663
3
}
2664
2665
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
2666
                                      RecyclerMetricsContext& metrics_context,
2667
49
                                      int64_t partition_id) {
2668
49
    bool is_multi_version =
2669
49
            instance_info_.has_multi_version_status() &&
2670
49
            instance_info_.multi_version_status() != MultiVersionStatus::MULTI_VERSION_DISABLED;
2671
49
    int64_t num_scanned = 0;
2672
49
    std::atomic_long num_recycled = 0;
2673
2674
49
    std::string tablet_key_begin, tablet_key_end;
2675
49
    std::string stats_key_begin, stats_key_end;
2676
49
    std::string job_key_begin, job_key_end;
2677
2678
49
    std::string tablet_belongs;
2679
49
    if (partition_id > 0) {
2680
        // recycle tablets in a partition belonging to the index
2681
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
2682
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
2683
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
2684
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
2685
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
2686
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
2687
33
        tablet_belongs = "partition";
2688
33
    } else {
2689
        // recycle tablets in the index
2690
16
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
2691
16
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
2692
16
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
2693
16
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
2694
16
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
2695
16
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
2696
16
        tablet_belongs = "index";
2697
16
    }
2698
2699
49
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
2700
49
            .tag("table_id", table_id)
2701
49
            .tag("index_id", index_id)
2702
49
            .tag("partition_id", partition_id);
2703
2704
49
    auto start_time = steady_clock::now();
2705
2706
49
    DORIS_CLOUD_DEFER {
2707
49
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2708
49
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
2709
49
                .tag("instance_id", instance_id_)
2710
49
                .tag("table_id", table_id)
2711
49
                .tag("index_id", index_id)
2712
49
                .tag("partition_id", partition_id)
2713
49
                .tag("num_scanned", num_scanned)
2714
49
                .tag("num_recycled", num_recycled);
2715
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
2706
4
    DORIS_CLOUD_DEFER {
2707
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2708
4
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
2709
4
                .tag("instance_id", instance_id_)
2710
4
                .tag("table_id", table_id)
2711
4
                .tag("index_id", index_id)
2712
4
                .tag("partition_id", partition_id)
2713
4
                .tag("num_scanned", num_scanned)
2714
4
                .tag("num_recycled", num_recycled);
2715
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
2706
45
    DORIS_CLOUD_DEFER {
2707
45
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2708
45
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
2709
45
                .tag("instance_id", instance_id_)
2710
45
                .tag("table_id", table_id)
2711
45
                .tag("index_id", index_id)
2712
45
                .tag("partition_id", partition_id)
2713
45
                .tag("num_scanned", num_scanned)
2714
45
                .tag("num_recycled", num_recycled);
2715
45
    };
2716
2717
    // The first string_view represents the tablet key which has been recycled
2718
    // The second bool represents whether the following fdb's tablet key deletion could be done using range move or not
2719
49
    using TabletKeyPair = std::pair<std::string_view, bool>;
2720
49
    SyncExecutor<TabletKeyPair> sync_executor(
2721
49
            _thread_pool_group.recycle_tablet_pool,
2722
49
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
2723
49
                        index_id, partition_id),
2724
4.23k
            [](const TabletKeyPair& k) { return k.first.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKSt4pairISt17basic_string_viewIcSt11char_traitsIcEEbE
Line
Count
Source
2724
4.00k
            [](const TabletKeyPair& k) { return k.first.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKSt4pairISt17basic_string_viewIcSt11char_traitsIcEEbE
Line
Count
Source
2724
237
            [](const TabletKeyPair& k) { return k.first.empty(); });
2725
2726
    // Elements in `tablet_keys` has the same lifetime as `it` in `scan_and_recycle`
2727
49
    std::vector<std::string> tablet_idx_keys;
2728
49
    std::vector<std::string> restore_job_keys;
2729
49
    std::vector<std::string> init_rs_keys;
2730
49
    std::vector<std::string> tablet_compact_stats_keys;
2731
49
    std::vector<std::string> tablet_load_stats_keys;
2732
49
    std::vector<std::string> versioned_meta_tablet_keys;
2733
8.24k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2734
8.24k
        bool use_range_remove = true;
2735
8.24k
        ++num_scanned;
2736
8.24k
        doris::TabletMetaCloudPB tablet_meta_pb;
2737
8.24k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
2738
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
2739
0
            use_range_remove = false;
2740
0
            return -1;
2741
0
        }
2742
8.24k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
2743
2744
8.24k
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
2745
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
2746
4.00k
            return -1;
2747
4.00k
        }
2748
2749
4.24k
        tablet_idx_keys.push_back(meta_tablet_idx_key({instance_id_, tablet_id}));
2750
4.24k
        restore_job_keys.push_back(job_restore_tablet_key({instance_id_, tablet_id}));
2751
4.24k
        if (is_multi_version) {
2752
            // The tablet index/inverted index are recycled in recycle_versioned_tablet.
2753
6
            tablet_compact_stats_keys.push_back(
2754
6
                    versioned::tablet_compact_stats_key({instance_id_, tablet_id}));
2755
6
            tablet_load_stats_keys.push_back(
2756
6
                    versioned::tablet_load_stats_key({instance_id_, tablet_id}));
2757
6
            versioned_meta_tablet_keys.push_back(
2758
6
                    versioned::meta_tablet_key({instance_id_, tablet_id}));
2759
6
        }
2760
4.24k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
2761
4.23k
        sync_executor.add([this, &num_recycled, tid = tablet_id, range_move = use_range_remove,
2762
4.23k
                           &metrics_context, k]() mutable -> TabletKeyPair {
2763
4.23k
            if (recycle_tablet(tid, metrics_context) != 0) {
2764
1
                LOG_WARNING("failed to recycle tablet")
2765
1
                        .tag("instance_id", instance_id_)
2766
1
                        .tag("tablet_id", tid);
2767
1
                range_move = false;
2768
1
                return {std::string_view(), range_move};
2769
1
            }
2770
4.23k
            ++num_recycled;
2771
4.23k
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2772
4.23k
            return {k, range_move};
2773
4.23k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENUlvE_clEv
Line
Count
Source
2762
4.00k
                           &metrics_context, k]() mutable -> TabletKeyPair {
2763
4.00k
            if (recycle_tablet(tid, metrics_context) != 0) {
2764
0
                LOG_WARNING("failed to recycle tablet")
2765
0
                        .tag("instance_id", instance_id_)
2766
0
                        .tag("tablet_id", tid);
2767
0
                range_move = false;
2768
0
                return {std::string_view(), range_move};
2769
0
            }
2770
4.00k
            ++num_recycled;
2771
4.00k
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2772
4.00k
            return {k, range_move};
2773
4.00k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENUlvE_clEv
Line
Count
Source
2762
237
                           &metrics_context, k]() mutable -> TabletKeyPair {
2763
237
            if (recycle_tablet(tid, metrics_context) != 0) {
2764
1
                LOG_WARNING("failed to recycle tablet")
2765
1
                        .tag("instance_id", instance_id_)
2766
1
                        .tag("tablet_id", tid);
2767
1
                range_move = false;
2768
1
                return {std::string_view(), range_move};
2769
1
            }
2770
236
            ++num_recycled;
2771
236
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2772
236
            return {k, range_move};
2773
237
        });
2774
4.23k
        return 0;
2775
4.24k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
2733
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2734
8.00k
        bool use_range_remove = true;
2735
8.00k
        ++num_scanned;
2736
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
2737
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
2738
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
2739
0
            use_range_remove = false;
2740
0
            return -1;
2741
0
        }
2742
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
2743
2744
8.00k
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
2745
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
2746
4.00k
            return -1;
2747
4.00k
        }
2748
2749
4.00k
        tablet_idx_keys.push_back(meta_tablet_idx_key({instance_id_, tablet_id}));
2750
4.00k
        restore_job_keys.push_back(job_restore_tablet_key({instance_id_, tablet_id}));
2751
4.00k
        if (is_multi_version) {
2752
            // The tablet index/inverted index are recycled in recycle_versioned_tablet.
2753
0
            tablet_compact_stats_keys.push_back(
2754
0
                    versioned::tablet_compact_stats_key({instance_id_, tablet_id}));
2755
0
            tablet_load_stats_keys.push_back(
2756
0
                    versioned::tablet_load_stats_key({instance_id_, tablet_id}));
2757
0
            versioned_meta_tablet_keys.push_back(
2758
0
                    versioned::meta_tablet_key({instance_id_, tablet_id}));
2759
0
        }
2760
4.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
2761
4.00k
        sync_executor.add([this, &num_recycled, tid = tablet_id, range_move = use_range_remove,
2762
4.00k
                           &metrics_context, k]() mutable -> TabletKeyPair {
2763
4.00k
            if (recycle_tablet(tid, metrics_context) != 0) {
2764
4.00k
                LOG_WARNING("failed to recycle tablet")
2765
4.00k
                        .tag("instance_id", instance_id_)
2766
4.00k
                        .tag("tablet_id", tid);
2767
4.00k
                range_move = false;
2768
4.00k
                return {std::string_view(), range_move};
2769
4.00k
            }
2770
4.00k
            ++num_recycled;
2771
4.00k
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2772
4.00k
            return {k, range_move};
2773
4.00k
        });
2774
4.00k
        return 0;
2775
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
2733
240
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2734
240
        bool use_range_remove = true;
2735
240
        ++num_scanned;
2736
240
        doris::TabletMetaCloudPB tablet_meta_pb;
2737
240
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
2738
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
2739
0
            use_range_remove = false;
2740
0
            return -1;
2741
0
        }
2742
240
        int64_t tablet_id = tablet_meta_pb.tablet_id();
2743
2744
240
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
2745
0
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
2746
0
            return -1;
2747
0
        }
2748
2749
240
        tablet_idx_keys.push_back(meta_tablet_idx_key({instance_id_, tablet_id}));
2750
240
        restore_job_keys.push_back(job_restore_tablet_key({instance_id_, tablet_id}));
2751
240
        if (is_multi_version) {
2752
            // The tablet index/inverted index are recycled in recycle_versioned_tablet.
2753
6
            tablet_compact_stats_keys.push_back(
2754
6
                    versioned::tablet_compact_stats_key({instance_id_, tablet_id}));
2755
6
            tablet_load_stats_keys.push_back(
2756
6
                    versioned::tablet_load_stats_key({instance_id_, tablet_id}));
2757
6
            versioned_meta_tablet_keys.push_back(
2758
6
                    versioned::meta_tablet_key({instance_id_, tablet_id}));
2759
6
        }
2760
240
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
2761
237
        sync_executor.add([this, &num_recycled, tid = tablet_id, range_move = use_range_remove,
2762
237
                           &metrics_context, k]() mutable -> TabletKeyPair {
2763
237
            if (recycle_tablet(tid, metrics_context) != 0) {
2764
237
                LOG_WARNING("failed to recycle tablet")
2765
237
                        .tag("instance_id", instance_id_)
2766
237
                        .tag("tablet_id", tid);
2767
237
                range_move = false;
2768
237
                return {std::string_view(), range_move};
2769
237
            }
2770
237
            ++num_recycled;
2771
237
            LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2772
237
            return {k, range_move};
2773
237
        });
2774
237
        return 0;
2775
240
    };
2776
2777
    // TODO(AlexYue): Add one ut to cover use_range_remove = false
2778
49
    auto loop_done = [&, this]() -> int {
2779
49
        bool finished = true;
2780
49
        auto tablet_keys = sync_executor.when_all(&finished);
2781
49
        if (!finished) {
2782
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
2783
1
            return -1;
2784
1
        }
2785
48
        if (tablet_keys.empty() && tablet_idx_keys.empty()) return 0;
2786
46
        if (!tablet_keys.empty() &&
2787
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
2787
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
2787
42
            std::ranges::all_of(tablet_keys, [](const auto& k) { return k.first.empty(); })) {
2788
0
            return -1;
2789
0
        }
2790
        // sort the vector using key's order
2791
46
        std::sort(tablet_keys.begin(), tablet_keys.end(),
2792
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
2792
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
2792
944
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
2793
46
        bool use_range_remove = true;
2794
4.23k
        for (auto& [_, remove] : tablet_keys) {
2795
4.23k
            if (!remove) {
2796
0
                use_range_remove = remove;
2797
0
                break;
2798
0
            }
2799
4.23k
        }
2800
46
        DORIS_CLOUD_DEFER {
2801
46
            tablet_idx_keys.clear();
2802
46
            restore_job_keys.clear();
2803
46
            init_rs_keys.clear();
2804
46
            tablet_compact_stats_keys.clear();
2805
46
            tablet_load_stats_keys.clear();
2806
46
            versioned_meta_tablet_keys.clear();
2807
46
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2800
2
        DORIS_CLOUD_DEFER {
2801
2
            tablet_idx_keys.clear();
2802
2
            restore_job_keys.clear();
2803
2
            init_rs_keys.clear();
2804
2
            tablet_compact_stats_keys.clear();
2805
2
            tablet_load_stats_keys.clear();
2806
2
            versioned_meta_tablet_keys.clear();
2807
2
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2800
44
        DORIS_CLOUD_DEFER {
2801
44
            tablet_idx_keys.clear();
2802
44
            restore_job_keys.clear();
2803
44
            init_rs_keys.clear();
2804
44
            tablet_compact_stats_keys.clear();
2805
44
            tablet_load_stats_keys.clear();
2806
44
            versioned_meta_tablet_keys.clear();
2807
44
        };
2808
46
        std::unique_ptr<Transaction> txn;
2809
46
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2810
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
2811
0
            return -1;
2812
0
        }
2813
46
        std::string tablet_key_end;
2814
46
        if (!tablet_keys.empty()) {
2815
44
            if (use_range_remove) {
2816
44
                tablet_key_end = std::string(tablet_keys.back().first) + '\x00';
2817
44
                txn->remove(tablet_keys.front().first, tablet_key_end);
2818
44
            } else {
2819
0
                for (auto& [k, _] : tablet_keys) {
2820
0
                    txn->remove(k);
2821
0
                }
2822
0
            }
2823
44
        }
2824
46
        if (is_multi_version) {
2825
6
            for (auto& k : tablet_compact_stats_keys) {
2826
                // Remove all versions of tablet compact stats for recycled tablet
2827
6
                LOG_INFO("remove versioned tablet compact stats key")
2828
6
                        .tag("compact_stats_key", hex(k));
2829
6
                versioned_remove_all(txn.get(), k);
2830
6
            }
2831
6
            for (auto& k : tablet_load_stats_keys) {
2832
                // Remove all versions of tablet load stats for recycled tablet
2833
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
2834
6
                versioned_remove_all(txn.get(), k);
2835
6
            }
2836
6
            for (auto& k : versioned_meta_tablet_keys) {
2837
                // Remove all versions of meta tablet for recycled tablet
2838
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
2839
6
                versioned_remove_all(txn.get(), k);
2840
6
            }
2841
5
        }
2842
4.24k
        for (auto& k : tablet_idx_keys) {
2843
4.24k
            txn->remove(k);
2844
4.24k
        }
2845
4.24k
        for (auto& k : restore_job_keys) {
2846
4.24k
            txn->remove(k);
2847
4.24k
        }
2848
46
        for (auto& k : init_rs_keys) {
2849
0
            txn->remove(k);
2850
0
        }
2851
46
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
2852
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
2853
0
                         << ", err=" << err;
2854
0
            return -1;
2855
0
        }
2856
46
        return 0;
2857
46
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
2778
4
    auto loop_done = [&, this]() -> int {
2779
4
        bool finished = true;
2780
4
        auto tablet_keys = sync_executor.when_all(&finished);
2781
4
        if (!finished) {
2782
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
2783
0
            return -1;
2784
0
        }
2785
4
        if (tablet_keys.empty() && tablet_idx_keys.empty()) return 0;
2786
2
        if (!tablet_keys.empty() &&
2787
2
            std::ranges::all_of(tablet_keys, [](const auto& k) { return k.first.empty(); })) {
2788
0
            return -1;
2789
0
        }
2790
        // sort the vector using key's order
2791
2
        std::sort(tablet_keys.begin(), tablet_keys.end(),
2792
2
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
2793
2
        bool use_range_remove = true;
2794
4.00k
        for (auto& [_, remove] : tablet_keys) {
2795
4.00k
            if (!remove) {
2796
0
                use_range_remove = remove;
2797
0
                break;
2798
0
            }
2799
4.00k
        }
2800
2
        DORIS_CLOUD_DEFER {
2801
2
            tablet_idx_keys.clear();
2802
2
            restore_job_keys.clear();
2803
2
            init_rs_keys.clear();
2804
2
            tablet_compact_stats_keys.clear();
2805
2
            tablet_load_stats_keys.clear();
2806
2
            versioned_meta_tablet_keys.clear();
2807
2
        };
2808
2
        std::unique_ptr<Transaction> txn;
2809
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2810
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
2811
0
            return -1;
2812
0
        }
2813
2
        std::string tablet_key_end;
2814
2
        if (!tablet_keys.empty()) {
2815
2
            if (use_range_remove) {
2816
2
                tablet_key_end = std::string(tablet_keys.back().first) + '\x00';
2817
2
                txn->remove(tablet_keys.front().first, tablet_key_end);
2818
2
            } else {
2819
0
                for (auto& [k, _] : tablet_keys) {
2820
0
                    txn->remove(k);
2821
0
                }
2822
0
            }
2823
2
        }
2824
2
        if (is_multi_version) {
2825
0
            for (auto& k : tablet_compact_stats_keys) {
2826
                // Remove all versions of tablet compact stats for recycled tablet
2827
0
                LOG_INFO("remove versioned tablet compact stats key")
2828
0
                        .tag("compact_stats_key", hex(k));
2829
0
                versioned_remove_all(txn.get(), k);
2830
0
            }
2831
0
            for (auto& k : tablet_load_stats_keys) {
2832
                // Remove all versions of tablet load stats for recycled tablet
2833
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
2834
0
                versioned_remove_all(txn.get(), k);
2835
0
            }
2836
0
            for (auto& k : versioned_meta_tablet_keys) {
2837
                // Remove all versions of meta tablet for recycled tablet
2838
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
2839
0
                versioned_remove_all(txn.get(), k);
2840
0
            }
2841
0
        }
2842
4.00k
        for (auto& k : tablet_idx_keys) {
2843
4.00k
            txn->remove(k);
2844
4.00k
        }
2845
4.00k
        for (auto& k : restore_job_keys) {
2846
4.00k
            txn->remove(k);
2847
4.00k
        }
2848
2
        for (auto& k : init_rs_keys) {
2849
0
            txn->remove(k);
2850
0
        }
2851
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
2852
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
2853
0
                         << ", err=" << err;
2854
0
            return -1;
2855
0
        }
2856
2
        return 0;
2857
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
2778
45
    auto loop_done = [&, this]() -> int {
2779
45
        bool finished = true;
2780
45
        auto tablet_keys = sync_executor.when_all(&finished);
2781
45
        if (!finished) {
2782
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
2783
1
            return -1;
2784
1
        }
2785
44
        if (tablet_keys.empty() && tablet_idx_keys.empty()) return 0;
2786
44
        if (!tablet_keys.empty() &&
2787
44
            std::ranges::all_of(tablet_keys, [](const auto& k) { return k.first.empty(); })) {
2788
0
            return -1;
2789
0
        }
2790
        // sort the vector using key's order
2791
44
        std::sort(tablet_keys.begin(), tablet_keys.end(),
2792
44
                  [](const auto& prev, const auto& last) { return prev.first < last.first; });
2793
44
        bool use_range_remove = true;
2794
236
        for (auto& [_, remove] : tablet_keys) {
2795
236
            if (!remove) {
2796
0
                use_range_remove = remove;
2797
0
                break;
2798
0
            }
2799
236
        }
2800
44
        DORIS_CLOUD_DEFER {
2801
44
            tablet_idx_keys.clear();
2802
44
            restore_job_keys.clear();
2803
44
            init_rs_keys.clear();
2804
44
            tablet_compact_stats_keys.clear();
2805
44
            tablet_load_stats_keys.clear();
2806
44
            versioned_meta_tablet_keys.clear();
2807
44
        };
2808
44
        std::unique_ptr<Transaction> txn;
2809
44
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2810
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
2811
0
            return -1;
2812
0
        }
2813
44
        std::string tablet_key_end;
2814
44
        if (!tablet_keys.empty()) {
2815
42
            if (use_range_remove) {
2816
42
                tablet_key_end = std::string(tablet_keys.back().first) + '\x00';
2817
42
                txn->remove(tablet_keys.front().first, tablet_key_end);
2818
42
            } else {
2819
0
                for (auto& [k, _] : tablet_keys) {
2820
0
                    txn->remove(k);
2821
0
                }
2822
0
            }
2823
42
        }
2824
44
        if (is_multi_version) {
2825
6
            for (auto& k : tablet_compact_stats_keys) {
2826
                // Remove all versions of tablet compact stats for recycled tablet
2827
6
                LOG_INFO("remove versioned tablet compact stats key")
2828
6
                        .tag("compact_stats_key", hex(k));
2829
6
                versioned_remove_all(txn.get(), k);
2830
6
            }
2831
6
            for (auto& k : tablet_load_stats_keys) {
2832
                // Remove all versions of tablet load stats for recycled tablet
2833
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
2834
6
                versioned_remove_all(txn.get(), k);
2835
6
            }
2836
6
            for (auto& k : versioned_meta_tablet_keys) {
2837
                // Remove all versions of meta tablet for recycled tablet
2838
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
2839
6
                versioned_remove_all(txn.get(), k);
2840
6
            }
2841
5
        }
2842
239
        for (auto& k : tablet_idx_keys) {
2843
239
            txn->remove(k);
2844
239
        }
2845
239
        for (auto& k : restore_job_keys) {
2846
239
            txn->remove(k);
2847
239
        }
2848
44
        for (auto& k : init_rs_keys) {
2849
0
            txn->remove(k);
2850
0
        }
2851
44
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
2852
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
2853
0
                         << ", err=" << err;
2854
0
            return -1;
2855
0
        }
2856
44
        return 0;
2857
44
    };
2858
2859
49
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
2860
49
                               std::move(loop_done));
2861
49
    if (ret != 0) {
2862
3
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
2863
3
        return ret;
2864
3
    }
2865
2866
    // directly remove tablet stats and tablet jobs of these dropped index or partition
2867
46
    std::unique_ptr<Transaction> txn;
2868
46
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2869
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
2870
0
        return -1;
2871
0
    }
2872
46
    txn->remove(stats_key_begin, stats_key_end);
2873
46
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
2874
46
                 << " end=" << hex(stats_key_end);
2875
46
    txn->remove(job_key_begin, job_key_end);
2876
46
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
2877
46
    std::string schema_key_begin, schema_key_end;
2878
46
    std::string schema_dict_key;
2879
46
    std::string versioned_schema_key_begin, versioned_schema_key_end;
2880
46
    if (partition_id <= 0) {
2881
        // Delete schema kv of this index
2882
14
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
2883
14
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
2884
14
        txn->remove(schema_key_begin, schema_key_end);
2885
14
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
2886
14
                     << " end=" << hex(schema_key_end);
2887
14
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
2888
14
        txn->remove(schema_dict_key);
2889
14
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
2890
14
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
2891
14
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
2892
14
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
2893
14
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
2894
14
                     << " end=" << hex(versioned_schema_key_end);
2895
14
    }
2896
2897
46
    TxnErrorCode err = txn->commit();
2898
46
    if (err != TxnErrorCode::TXN_OK) {
2899
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
2900
0
                     << " err=" << err;
2901
0
        return -1;
2902
0
    }
2903
2904
46
    return ret;
2905
46
}
2906
2907
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
2908
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
2909
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
2910
5.61k
    if (num_segments <= 0) return 0;
2911
2912
5.61k
    std::vector<std::string> file_paths;
2913
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
2914
0
        return -1;
2915
0
    }
2916
2917
    // Process inverted indexes
2918
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
2919
    // default format as v1.
2920
5.61k
    InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
2921
5.61k
    bool delete_rowset_data_by_prefix = false;
2922
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
2923
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
2924
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
2925
0
        delete_rowset_data_by_prefix = true;
2926
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
2927
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
2928
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
2929
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
2930
10.0k
            }
2931
10.0k
        }
2932
4.80k
        if (rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
2933
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
2934
2.00k
        }
2935
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
2936
        // schema version and index id are not found, delete rowset data by prefix directly.
2937
0
        delete_rowset_data_by_prefix = true;
2938
809
    } else {
2939
        // otherwise, try to get schema kv
2940
809
        InvertedIndexInfo index_info;
2941
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
2942
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
2943
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
2944
809
                                 &inverted_index_get_ret);
2945
809
        if (inverted_index_get_ret == 0) {
2946
809
            index_format = index_info.first;
2947
809
            index_ids = index_info.second;
2948
809
        } else if (inverted_index_get_ret == 1) {
2949
            // 1. Schema kv not found means tablet has been recycled
2950
            // Maybe some tablet recycle failed by some bugs
2951
            // We need to delete again to double check
2952
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
2953
            // because we are uncertain about the inverted index information.
2954
            // If there are inverted indexes, some data might not be deleted,
2955
            // but this is acceptable as we have made our best effort to delete the data.
2956
0
            LOG_INFO(
2957
0
                    "delete rowset data schema kv not found, need to delete again to double "
2958
0
                    "check")
2959
0
                    .tag("instance_id", instance_id_)
2960
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
2961
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
2962
            // Currently index_ids is guaranteed to be empty,
2963
            // but we clear it again here as a safeguard against future code changes
2964
            // that might cause index_ids to no longer be empty
2965
0
            index_format = InvertedIndexStorageFormatPB::V2;
2966
0
            index_ids.clear();
2967
0
        } else {
2968
            // failed to get schema kv, delete rowset data by prefix directly.
2969
0
            delete_rowset_data_by_prefix = true;
2970
0
        }
2971
809
    }
2972
2973
5.61k
    if (delete_rowset_data_by_prefix) {
2974
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
2975
0
                                  rs_meta_pb.rowset_id_v2());
2976
0
    }
2977
2978
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
2979
5.61k
    if (it == accessor_map_.end()) {
2980
1.60k
        LOG_WARNING("instance has no such resource id")
2981
1.60k
                .tag("instance_id", instance_id_)
2982
1.60k
                .tag("resource_id", rs_meta_pb.resource_id());
2983
1.60k
        return -1;
2984
1.60k
    }
2985
4.01k
    auto& accessor = it->second;
2986
2987
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
2988
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
2989
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
2990
20.0k
        file_paths.push_back(segment_path(tablet_id, rowset_id, i));
2991
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
2992
40.0k
            for (const auto& index_id : index_ids) {
2993
40.0k
                file_paths.push_back(inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
2994
40.0k
                                                            index_id.second));
2995
40.0k
            }
2996
20.0k
        } else if (!index_ids.empty()) {
2997
0
            file_paths.push_back(inverted_index_path_v2(tablet_id, rowset_id, i));
2998
0
        }
2999
20.0k
    }
3000
3001
    // Process delete bitmap - check if it's stored in packed file
3002
4.01k
    bool delete_bitmap_is_packed = false;
3003
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3004
4.01k
                                                       &delete_bitmap_is_packed) != 0) {
3005
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3006
0
                .tag("instance_id", instance_id_)
3007
0
                .tag("tablet_id", tablet_id)
3008
0
                .tag("rowset_id", rowset_id);
3009
0
        return -1;
3010
0
    }
3011
    // Only delete standalone delete bitmap file if not stored in packed file
3012
4.01k
    if (!delete_bitmap_is_packed) {
3013
4.01k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3014
4.01k
    }
3015
    // TODO(AlexYue): seems could do do batch
3016
4.01k
    return accessor->delete_files(file_paths);
3017
4.01k
}
3018
3019
62.3k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3020
62.3k
    LOG_INFO("begin process_packed_file_location_index")
3021
62.3k
            .tag("instance_id", instance_id_)
3022
62.3k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3023
62.3k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3024
62.3k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3025
62.3k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3026
62.3k
    if (index_map.empty()) {
3027
62.3k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3028
62.3k
                .tag("instance_id", instance_id_)
3029
62.3k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3030
62.3k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3031
62.3k
        return 0;
3032
62.3k
    }
3033
3034
19
    struct PackedSmallFileInfo {
3035
19
        std::string small_file_path;
3036
19
    };
3037
19
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3038
19
    packed_file_updates.reserve(index_map.size());
3039
27
    for (const auto& [small_path, index_pb] : index_map) {
3040
27
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3041
0
            continue;
3042
0
        }
3043
27
        packed_file_updates[index_pb.packed_file_path()].push_back(
3044
27
                PackedSmallFileInfo {small_path});
3045
27
    }
3046
19
    if (packed_file_updates.empty()) {
3047
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3048
0
                .tag("instance_id", instance_id_)
3049
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3050
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3051
0
                .tag("index_map_size", index_map.size());
3052
0
        return 0;
3053
0
    }
3054
3055
19
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3056
19
    int ret = 0;
3057
24
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3058
24
        if (small_files.empty()) {
3059
0
            continue;
3060
0
        }
3061
3062
24
        bool success = false;
3063
24
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3064
24
            std::unique_ptr<Transaction> txn;
3065
24
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3066
24
            if (err != TxnErrorCode::TXN_OK) {
3067
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3068
0
                        .tag("instance_id", instance_id_)
3069
0
                        .tag("packed_file_path", packed_file_path)
3070
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3071
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3072
0
                        .tag("err", err);
3073
0
                ret = -1;
3074
0
                break;
3075
0
            }
3076
3077
24
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3078
24
            std::string packed_val;
3079
24
            err = txn->get(packed_key, &packed_val);
3080
24
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3081
0
                LOG_WARNING("packed file info not found when recycling rowset")
3082
0
                        .tag("instance_id", instance_id_)
3083
0
                        .tag("packed_file_path", packed_file_path)
3084
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3085
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3086
0
                        .tag("key", hex(packed_key))
3087
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3088
                // Skip this packed file entry and continue with others
3089
0
                success = true;
3090
0
                break;
3091
0
            }
3092
24
            if (err != TxnErrorCode::TXN_OK) {
3093
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
3094
0
                        .tag("instance_id", instance_id_)
3095
0
                        .tag("packed_file_path", packed_file_path)
3096
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3097
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3098
0
                        .tag("err", err);
3099
0
                ret = -1;
3100
0
                break;
3101
0
            }
3102
3103
24
            cloud::PackedFileInfoPB packed_info;
3104
24
            if (!packed_info.ParseFromString(packed_val)) {
3105
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
3106
0
                        .tag("instance_id", instance_id_)
3107
0
                        .tag("packed_file_path", packed_file_path)
3108
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3109
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3110
0
                ret = -1;
3111
0
                break;
3112
0
            }
3113
3114
24
            LOG_INFO("packed file update check")
3115
24
                    .tag("instance_id", instance_id_)
3116
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3117
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3118
24
                    .tag("merged_file_path", packed_file_path)
3119
24
                    .tag("requested_small_files", small_files.size())
3120
24
                    .tag("merge_entries", packed_info.slices_size());
3121
3122
24
            auto* small_file_entries = packed_info.mutable_slices();
3123
24
            int64_t changed_files = 0;
3124
24
            int64_t missing_entries = 0;
3125
24
            int64_t already_deleted = 0;
3126
27
            for (const auto& small_file_info : small_files) {
3127
27
                bool found = false;
3128
87
                for (auto& small_file_entry : *small_file_entries) {
3129
87
                    if (small_file_entry.path() == small_file_info.small_file_path) {
3130
27
                        if (!small_file_entry.deleted()) {
3131
27
                            small_file_entry.set_deleted(true);
3132
27
                            if (!small_file_entry.corrected()) {
3133
27
                                small_file_entry.set_corrected(true);
3134
27
                            }
3135
27
                            ++changed_files;
3136
27
                        } else {
3137
0
                            ++already_deleted;
3138
0
                        }
3139
27
                        found = true;
3140
27
                        break;
3141
27
                    }
3142
87
                }
3143
27
                if (!found) {
3144
0
                    ++missing_entries;
3145
0
                    LOG_WARNING("packed file info missing small file entry")
3146
0
                            .tag("instance_id", instance_id_)
3147
0
                            .tag("packed_file_path", packed_file_path)
3148
0
                            .tag("small_file_path", small_file_info.small_file_path)
3149
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3150
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
3151
0
                }
3152
27
            }
3153
3154
24
            if (changed_files == 0) {
3155
0
                LOG_INFO("skip merge file update: no merge entries changed")
3156
0
                        .tag("instance_id", instance_id_)
3157
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3158
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3159
0
                        .tag("merged_file_path", packed_file_path)
3160
0
                        .tag("missing_entries", missing_entries)
3161
0
                        .tag("already_deleted", already_deleted)
3162
0
                        .tag("requested_small_files", small_files.size())
3163
0
                        .tag("merge_entries", packed_info.slices_size());
3164
0
                success = true;
3165
0
                break;
3166
0
            }
3167
3168
            // Calculate remaining files
3169
24
            int64_t left_file_count = 0;
3170
24
            int64_t left_file_bytes = 0;
3171
141
            for (const auto& small_file_entry : packed_info.slices()) {
3172
141
                if (!small_file_entry.deleted()) {
3173
57
                    ++left_file_count;
3174
57
                    left_file_bytes += small_file_entry.size();
3175
57
                }
3176
141
            }
3177
24
            packed_info.set_remaining_slice_bytes(left_file_bytes);
3178
24
            packed_info.set_ref_cnt(left_file_count);
3179
24
            LOG_INFO("updated packed file reference info")
3180
24
                    .tag("instance_id", instance_id_)
3181
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3182
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3183
24
                    .tag("packed_file_path", packed_file_path)
3184
24
                    .tag("ref_cnt", left_file_count)
3185
24
                    .tag("left_file_bytes", left_file_bytes);
3186
3187
24
            if (left_file_count == 0) {
3188
7
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3189
7
            }
3190
3191
24
            std::string updated_val;
3192
24
            if (!packed_info.SerializeToString(&updated_val)) {
3193
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
3194
0
                        .tag("instance_id", instance_id_)
3195
0
                        .tag("packed_file_path", packed_file_path)
3196
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3197
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3198
0
                ret = -1;
3199
0
                break;
3200
0
            }
3201
3202
24
            txn->put(packed_key, updated_val);
3203
24
            err = txn->commit();
3204
24
            if (err == TxnErrorCode::TXN_OK) {
3205
24
                success = true;
3206
24
                if (left_file_count == 0) {
3207
7
                    LOG_INFO("packed file ready to delete, deleting immediately")
3208
7
                            .tag("instance_id", instance_id_)
3209
7
                            .tag("packed_file_path", packed_file_path);
3210
7
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3211
0
                        ret = -1;
3212
0
                    }
3213
7
                }
3214
24
                break;
3215
24
            }
3216
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
3217
0
                if (attempt >= max_retry_times) {
3218
0
                    LOG_WARNING("packed file info update conflict after max retry")
3219
0
                            .tag("instance_id", instance_id_)
3220
0
                            .tag("packed_file_path", packed_file_path)
3221
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3222
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
3223
0
                            .tag("changed_files", changed_files)
3224
0
                            .tag("attempt", attempt);
3225
0
                    ret = -1;
3226
0
                    break;
3227
0
                }
3228
0
                LOG_WARNING("packed file info update conflict, retrying")
3229
0
                        .tag("instance_id", instance_id_)
3230
0
                        .tag("packed_file_path", packed_file_path)
3231
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3232
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3233
0
                        .tag("changed_files", changed_files)
3234
0
                        .tag("attempt", attempt);
3235
0
                sleep_for_packed_file_retry();
3236
0
                continue;
3237
0
            }
3238
3239
0
            LOG_WARNING("failed to commit packed file info update")
3240
0
                    .tag("instance_id", instance_id_)
3241
0
                    .tag("packed_file_path", packed_file_path)
3242
0
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3243
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3244
0
                    .tag("err", err)
3245
0
                    .tag("changed_files", changed_files);
3246
0
            ret = -1;
3247
0
            break;
3248
0
        }
3249
3250
24
        if (!success) {
3251
0
            ret = -1;
3252
0
        }
3253
24
    }
3254
3255
19
    return ret;
3256
19
}
3257
3258
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(int64_t tablet_id,
3259
                                                                     const std::string& rowset_id,
3260
58.2k
                                                                     bool* out_is_packed) {
3261
58.2k
    if (out_is_packed) {
3262
58.2k
        *out_is_packed = false;
3263
58.2k
    }
3264
3265
    // Get delete bitmap storage info from FDB
3266
58.2k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
3267
58.2k
    std::unique_ptr<Transaction> txn;
3268
58.2k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
3269
58.2k
    if (err != TxnErrorCode::TXN_OK) {
3270
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
3271
0
                .tag("instance_id", instance_id_)
3272
0
                .tag("tablet_id", tablet_id)
3273
0
                .tag("rowset_id", rowset_id)
3274
0
                .tag("err", err);
3275
0
        return -1;
3276
0
    }
3277
3278
58.2k
    std::string dbm_val;
3279
58.2k
    err = txn->get(dbm_key, &dbm_val);
3280
58.2k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3281
        // No delete bitmap for this rowset, nothing to do
3282
4.63k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
3283
4.63k
                .tag("instance_id", instance_id_)
3284
4.63k
                .tag("tablet_id", tablet_id)
3285
4.63k
                .tag("rowset_id", rowset_id);
3286
4.63k
        return 0;
3287
4.63k
    }
3288
53.5k
    if (err != TxnErrorCode::TXN_OK) {
3289
0
        LOG_WARNING("failed to get delete bitmap storage")
3290
0
                .tag("instance_id", instance_id_)
3291
0
                .tag("tablet_id", tablet_id)
3292
0
                .tag("rowset_id", rowset_id)
3293
0
                .tag("err", err);
3294
0
        return -1;
3295
0
    }
3296
3297
53.5k
    DeleteBitmapStoragePB storage;
3298
53.5k
    if (!storage.ParseFromString(dbm_val)) {
3299
0
        LOG_WARNING("failed to parse delete bitmap storage")
3300
0
                .tag("instance_id", instance_id_)
3301
0
                .tag("tablet_id", tablet_id)
3302
0
                .tag("rowset_id", rowset_id);
3303
0
        return -1;
3304
0
    }
3305
3306
    // Check if delete bitmap is stored in packed file
3307
53.5k
    if (!storage.has_packed_slice_location() ||
3308
53.5k
        storage.packed_slice_location().packed_file_path().empty()) {
3309
        // Not stored in packed file, nothing to do
3310
53.5k
        return 0;
3311
53.5k
    }
3312
3313
18.4E
    if (out_is_packed) {
3314
0
        *out_is_packed = true;
3315
0
    }
3316
3317
18.4E
    const auto& packed_loc = storage.packed_slice_location();
3318
18.4E
    const std::string& packed_file_path = packed_loc.packed_file_path();
3319
3320
18.4E
    LOG_INFO("decrementing delete bitmap packed file ref count")
3321
18.4E
            .tag("instance_id", instance_id_)
3322
18.4E
            .tag("tablet_id", tablet_id)
3323
18.4E
            .tag("rowset_id", rowset_id)
3324
18.4E
            .tag("packed_file_path", packed_file_path);
3325
3326
18.4E
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3327
18.4E
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3328
0
        std::unique_ptr<Transaction> update_txn;
3329
0
        err = txn_kv_->create_txn(&update_txn);
3330
0
        if (err != TxnErrorCode::TXN_OK) {
3331
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
3332
0
                    .tag("instance_id", instance_id_)
3333
0
                    .tag("tablet_id", tablet_id)
3334
0
                    .tag("rowset_id", rowset_id)
3335
0
                    .tag("err", err);
3336
0
            return -1;
3337
0
        }
3338
3339
0
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3340
0
        std::string packed_val;
3341
0
        err = update_txn->get(packed_key, &packed_val);
3342
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3343
0
            LOG_WARNING("packed file info not found for delete bitmap")
3344
0
                    .tag("instance_id", instance_id_)
3345
0
                    .tag("tablet_id", tablet_id)
3346
0
                    .tag("rowset_id", rowset_id)
3347
0
                    .tag("packed_file_path", packed_file_path);
3348
0
            return 0;
3349
0
        }
3350
0
        if (err != TxnErrorCode::TXN_OK) {
3351
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
3352
0
                    .tag("instance_id", instance_id_)
3353
0
                    .tag("tablet_id", tablet_id)
3354
0
                    .tag("rowset_id", rowset_id)
3355
0
                    .tag("packed_file_path", packed_file_path)
3356
0
                    .tag("err", err);
3357
0
            return -1;
3358
0
        }
3359
3360
0
        cloud::PackedFileInfoPB packed_info;
3361
0
        if (!packed_info.ParseFromString(packed_val)) {
3362
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
3363
0
                    .tag("instance_id", instance_id_)
3364
0
                    .tag("tablet_id", tablet_id)
3365
0
                    .tag("rowset_id", rowset_id)
3366
0
                    .tag("packed_file_path", packed_file_path);
3367
0
            return -1;
3368
0
        }
3369
3370
        // Find and mark the small file entry as deleted
3371
        // Use tablet_id and rowset_id to match entry instead of path,
3372
        // because path format may vary with path_version (with or without shard prefix)
3373
0
        auto* entries = packed_info.mutable_slices();
3374
0
        bool found = false;
3375
0
        bool already_deleted = false;
3376
0
        for (auto& entry : *entries) {
3377
0
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
3378
0
                if (!entry.deleted()) {
3379
0
                    entry.set_deleted(true);
3380
0
                    if (!entry.corrected()) {
3381
0
                        entry.set_corrected(true);
3382
0
                    }
3383
0
                } else {
3384
0
                    already_deleted = true;
3385
0
                }
3386
0
                found = true;
3387
0
                break;
3388
0
            }
3389
0
        }
3390
3391
0
        if (!found) {
3392
0
            LOG_WARNING("delete bitmap entry not found in packed file")
3393
0
                    .tag("instance_id", instance_id_)
3394
0
                    .tag("tablet_id", tablet_id)
3395
0
                    .tag("rowset_id", rowset_id)
3396
0
                    .tag("packed_file_path", packed_file_path);
3397
0
            return 0;
3398
0
        }
3399
3400
0
        if (already_deleted) {
3401
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
3402
0
                    .tag("instance_id", instance_id_)
3403
0
                    .tag("tablet_id", tablet_id)
3404
0
                    .tag("rowset_id", rowset_id)
3405
0
                    .tag("packed_file_path", packed_file_path);
3406
0
            return 0;
3407
0
        }
3408
3409
        // Calculate remaining files
3410
0
        int64_t left_file_count = 0;
3411
0
        int64_t left_file_bytes = 0;
3412
0
        for (const auto& entry : packed_info.slices()) {
3413
0
            if (!entry.deleted()) {
3414
0
                ++left_file_count;
3415
0
                left_file_bytes += entry.size();
3416
0
            }
3417
0
        }
3418
0
        packed_info.set_remaining_slice_bytes(left_file_bytes);
3419
0
        packed_info.set_ref_cnt(left_file_count);
3420
3421
0
        if (left_file_count == 0) {
3422
0
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3423
0
        }
3424
3425
0
        std::string updated_val;
3426
0
        if (!packed_info.SerializeToString(&updated_val)) {
3427
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
3428
0
                    .tag("instance_id", instance_id_)
3429
0
                    .tag("tablet_id", tablet_id)
3430
0
                    .tag("rowset_id", rowset_id)
3431
0
                    .tag("packed_file_path", packed_file_path);
3432
0
            return -1;
3433
0
        }
3434
3435
0
        update_txn->put(packed_key, updated_val);
3436
0
        err = update_txn->commit();
3437
0
        if (err == TxnErrorCode::TXN_OK) {
3438
0
            LOG_INFO("delete bitmap packed file ref count decremented")
3439
0
                    .tag("instance_id", instance_id_)
3440
0
                    .tag("tablet_id", tablet_id)
3441
0
                    .tag("rowset_id", rowset_id)
3442
0
                    .tag("packed_file_path", packed_file_path)
3443
0
                    .tag("left_file_count", left_file_count);
3444
0
            if (left_file_count == 0) {
3445
0
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3446
0
                    return -1;
3447
0
                }
3448
0
            }
3449
0
            return 0;
3450
0
        }
3451
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
3452
0
            if (attempt >= max_retry_times) {
3453
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
3454
0
                        .tag("instance_id", instance_id_)
3455
0
                        .tag("tablet_id", tablet_id)
3456
0
                        .tag("rowset_id", rowset_id)
3457
0
                        .tag("packed_file_path", packed_file_path)
3458
0
                        .tag("attempt", attempt);
3459
0
                return -1;
3460
0
            }
3461
0
            sleep_for_packed_file_retry();
3462
0
            continue;
3463
0
        }
3464
3465
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
3466
0
                .tag("instance_id", instance_id_)
3467
0
                .tag("tablet_id", tablet_id)
3468
0
                .tag("rowset_id", rowset_id)
3469
0
                .tag("packed_file_path", packed_file_path)
3470
0
                .tag("err", err);
3471
0
        return -1;
3472
0
    }
3473
3474
18.4E
    return -1;
3475
18.4E
}
3476
3477
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
3478
                                                const std::string& packed_key,
3479
7
                                                const cloud::PackedFileInfoPB& packed_info) {
3480
7
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
3481
0
        LOG_WARNING("packed file missing resource id when recycling")
3482
0
                .tag("instance_id", instance_id_)
3483
0
                .tag("packed_file_path", packed_file_path);
3484
0
        return -1;
3485
0
    }
3486
3487
7
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
3488
7
    if (!accessor) {
3489
0
        LOG_WARNING("no accessor available to delete packed file")
3490
0
                .tag("instance_id", instance_id_)
3491
0
                .tag("packed_file_path", packed_file_path)
3492
0
                .tag("resource_id", packed_info.resource_id());
3493
0
        return -1;
3494
0
    }
3495
3496
7
    int del_ret = accessor->delete_file(packed_file_path);
3497
7
    if (del_ret != 0 && del_ret != 1) {
3498
0
        LOG_WARNING("failed to delete packed file")
3499
0
                .tag("instance_id", instance_id_)
3500
0
                .tag("packed_file_path", packed_file_path)
3501
0
                .tag("resource_id", resource_id)
3502
0
                .tag("ret", del_ret);
3503
0
        return -1;
3504
0
    }
3505
7
    if (del_ret == 1) {
3506
0
        LOG_INFO("packed file already removed")
3507
0
                .tag("instance_id", instance_id_)
3508
0
                .tag("packed_file_path", packed_file_path)
3509
0
                .tag("resource_id", resource_id);
3510
7
    } else {
3511
7
        LOG_INFO("deleted packed file")
3512
7
                .tag("instance_id", instance_id_)
3513
7
                .tag("packed_file_path", packed_file_path)
3514
7
                .tag("resource_id", resource_id);
3515
7
    }
3516
3517
7
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
3518
7
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3519
7
        std::unique_ptr<Transaction> del_txn;
3520
7
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
3521
7
        if (err != TxnErrorCode::TXN_OK) {
3522
0
            LOG_WARNING("failed to create txn when removing packed file kv")
3523
0
                    .tag("instance_id", instance_id_)
3524
0
                    .tag("packed_file_path", packed_file_path)
3525
0
                    .tag("attempt", attempt)
3526
0
                    .tag("err", err);
3527
0
            return -1;
3528
0
        }
3529
3530
7
        std::string latest_val;
3531
7
        err = del_txn->get(packed_key, &latest_val);
3532
7
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3533
0
            return 0;
3534
0
        }
3535
7
        if (err != TxnErrorCode::TXN_OK) {
3536
0
            LOG_WARNING("failed to re-read packed file kv before removal")
3537
0
                    .tag("instance_id", instance_id_)
3538
0
                    .tag("packed_file_path", packed_file_path)
3539
0
                    .tag("attempt", attempt)
3540
0
                    .tag("err", err);
3541
0
            return -1;
3542
0
        }
3543
3544
7
        cloud::PackedFileInfoPB latest_info;
3545
7
        if (!latest_info.ParseFromString(latest_val)) {
3546
0
            LOG_WARNING("failed to parse packed file info before removal")
3547
0
                    .tag("instance_id", instance_id_)
3548
0
                    .tag("packed_file_path", packed_file_path)
3549
0
                    .tag("attempt", attempt);
3550
0
            return -1;
3551
0
        }
3552
3553
7
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
3554
7
              latest_info.ref_cnt() == 0)) {
3555
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
3556
0
                    .tag("instance_id", instance_id_)
3557
0
                    .tag("packed_file_path", packed_file_path)
3558
0
                    .tag("attempt", attempt);
3559
0
            return 0;
3560
0
        }
3561
3562
7
        del_txn->remove(packed_key);
3563
7
        err = del_txn->commit();
3564
7
        if (err == TxnErrorCode::TXN_OK) {
3565
7
            LOG_INFO("removed packed file metadata")
3566
7
                    .tag("instance_id", instance_id_)
3567
7
                    .tag("packed_file_path", packed_file_path);
3568
7
            return 0;
3569
7
        }
3570
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
3571
0
            if (attempt >= max_retry_times) {
3572
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
3573
0
                        .tag("instance_id", instance_id_)
3574
0
                        .tag("packed_file_path", packed_file_path)
3575
0
                        .tag("attempt", attempt);
3576
0
                return -1;
3577
0
            }
3578
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
3579
0
                    .tag("instance_id", instance_id_)
3580
0
                    .tag("packed_file_path", packed_file_path)
3581
0
                    .tag("attempt", attempt);
3582
0
            sleep_for_packed_file_retry();
3583
0
            continue;
3584
0
        }
3585
0
        LOG_WARNING("failed to remove packed file kv")
3586
0
                .tag("instance_id", instance_id_)
3587
0
                .tag("packed_file_path", packed_file_path)
3588
0
                .tag("attempt", attempt)
3589
0
                .tag("err", err);
3590
0
        return -1;
3591
0
    }
3592
0
    return -1;
3593
7
}
3594
3595
int InstanceRecycler::delete_rowset_data(
3596
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
3597
98
        RecyclerMetricsContext& metrics_context) {
3598
98
    int ret = 0;
3599
    // resource_id -> file_paths
3600
98
    std::map<std::string, std::vector<std::string>> resource_file_paths;
3601
    // (resource_id, tablet_id, rowset_id)
3602
98
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
3603
98
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
3604
3605
57.1k
    for (const auto& [_, rs] : rowsets) {
3606
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
3607
        // due to aborted schema change.
3608
57.1k
        if (is_formal_rowset) {
3609
3.16k
            std::lock_guard lock(recycled_tablets_mtx_);
3610
3.16k
            if (recycled_tablets_.count(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
3611
                // Tablet has been recycled and this rowset has no packed slices, so file data
3612
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
3613
                // slice info must still run to decrement packed file ref counts.
3614
0
                continue;
3615
0
            }
3616
3.16k
        }
3617
3618
57.1k
        int64_t num_segments = rs.num_segments();
3619
        // Check num_segments before accessor lookup, because empty rowsets
3620
        // (e.g. base compaction output of empty rowsets) may have no resource_id
3621
        // set. Skipping them early avoids a spurious "no such resource id" error
3622
        // that marks the entire batch as failed and prevents txn_remove from
3623
        // cleaning up recycle KV keys.
3624
57.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
57.1k
        auto it = accessor_map_.find(rs.resource_id());
3631
        // possible if the accessor is not initilized correctly
3632
57.1k
        if (it == accessor_map_.end()) [[unlikely]] {
3633
3.00k
            LOG_WARNING("instance has no such resource id")
3634
3.00k
                    .tag("instance_id", instance_id_)
3635
3.00k
                    .tag("resource_id", rs.resource_id());
3636
3.00k
            ret = -1;
3637
3.00k
            continue;
3638
3.00k
        }
3639
3640
54.1k
        auto& file_paths = resource_file_paths[rs.resource_id()];
3641
54.1k
        const auto& rowset_id = rs.rowset_id_v2();
3642
54.1k
        int64_t tablet_id = rs.tablet_id();
3643
54.1k
        LOG_INFO("recycle rowset merge index size")
3644
54.1k
                .tag("instance_id", instance_id_)
3645
54.1k
                .tag("tablet_id", tablet_id)
3646
54.1k
                .tag("rowset_id", rowset_id)
3647
54.1k
                .tag("merge_index_size", rs.packed_slice_locations_size());
3648
54.1k
        if (decrement_packed_file_ref_counts(rs) != 0) {
3649
0
            ret = -1;
3650
0
            continue;
3651
0
        }
3652
3653
        // Process delete bitmap - check if it's stored in packed file
3654
54.1k
        bool delete_bitmap_is_packed = false;
3655
54.1k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3656
54.1k
                                                           &delete_bitmap_is_packed) != 0) {
3657
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3658
0
                    .tag("instance_id", instance_id_)
3659
0
                    .tag("tablet_id", tablet_id)
3660
0
                    .tag("rowset_id", rowset_id);
3661
0
            ret = -1;
3662
0
            continue;
3663
0
        }
3664
        // Only delete standalone delete bitmap file if not stored in packed file
3665
54.2k
        if (!delete_bitmap_is_packed) {
3666
54.2k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3667
54.2k
        }
3668
3669
        // Process inverted indexes
3670
54.1k
        std::vector<std::pair<int64_t, std::string>> index_ids;
3671
        // default format as v1.
3672
54.1k
        InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
3673
54.1k
        int inverted_index_get_ret = 0;
3674
54.1k
        if (rs.has_tablet_schema()) {
3675
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
3676
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3677
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3678
53.5k
                }
3679
53.5k
            }
3680
26.6k
            if (rs.tablet_schema().has_inverted_index_storage_format()) {
3681
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
3682
26.5k
            }
3683
27.5k
        } else {
3684
27.5k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
3685
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
3686
0
                                "instance_id="
3687
0
                             << instance_id_ << " tablet_id=" << tablet_id
3688
0
                             << " rowset_id=" << rowset_id;
3689
0
                ret = -1;
3690
0
                continue;
3691
0
            }
3692
27.5k
            InvertedIndexInfo index_info;
3693
27.5k
            inverted_index_get_ret =
3694
27.5k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
3695
27.5k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3696
27.5k
                                     &inverted_index_get_ret);
3697
27.5k
            if (inverted_index_get_ret == 0) {
3698
27.0k
                index_format = index_info.first;
3699
27.0k
                index_ids = index_info.second;
3700
27.0k
            } else if (inverted_index_get_ret == 1) {
3701
                // 1. Schema kv not found means tablet has been recycled
3702
                // Maybe some tablet recycle failed by some bugs
3703
                // We need to delete again to double check
3704
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3705
                // because we are uncertain about the inverted index information.
3706
                // If there are inverted indexes, some data might not be deleted,
3707
                // but this is acceptable as we have made our best effort to delete the data.
3708
507
                LOG_INFO(
3709
507
                        "delete rowset data schema kv not found, need to delete again to "
3710
507
                        "double "
3711
507
                        "check")
3712
507
                        .tag("instance_id", instance_id_)
3713
507
                        .tag("tablet_id", tablet_id)
3714
507
                        .tag("rowset", rs.ShortDebugString());
3715
                // Currently index_ids is guaranteed to be empty,
3716
                // but we clear it again here as a safeguard against future code changes
3717
                // that might cause index_ids to no longer be empty
3718
507
                index_format = InvertedIndexStorageFormatPB::V2;
3719
507
                index_ids.clear();
3720
18.4E
            } else {
3721
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
3722
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
3723
18.4E
                ret = -1;
3724
18.4E
                continue;
3725
18.4E
            }
3726
27.5k
        }
3727
54.2k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3728
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3729
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3730
5
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
3731
5
            continue;
3732
5
        }
3733
323k
        for (int64_t i = 0; i < num_segments; ++i) {
3734
269k
            file_paths.push_back(segment_path(tablet_id, rowset_id, i));
3735
269k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
3736
535k
                for (const auto& index_id : index_ids) {
3737
535k
                    file_paths.push_back(inverted_index_path_v1(tablet_id, rowset_id, i,
3738
535k
                                                                index_id.first, index_id.second));
3739
535k
                }
3740
267k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
3741
                // try to recycle inverted index v2 when get_ret == 1
3742
                // we treat schema not found as if it has a v2 format inverted index
3743
                // to reduce chance of data leakage
3744
2.50k
                if (inverted_index_get_ret == 1) {
3745
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
3746
2.50k
                            .tag("instance_id", instance_id_)
3747
2.50k
                            .tag("inverted index v2 path",
3748
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, i));
3749
2.50k
                }
3750
2.50k
                file_paths.push_back(inverted_index_path_v2(tablet_id, rowset_id, i));
3751
2.50k
            }
3752
269k
        }
3753
54.1k
    }
3754
3755
98
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
3756
98
                                                 "delete_rowset_data",
3757
98
                                                 [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clERKi
Line
Count
Source
3757
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
3757
51
                                                 [](const int& ret) { return ret != 0; });
3758
98
    for (auto& [resource_id, file_paths] : resource_file_paths) {
3759
51
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
3760
51
            DCHECK(accessor_map_.count(*rid))
3761
0
                    << "uninitilized accessor, instance_id=" << instance_id_
3762
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
3763
51
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
3764
51
                                     &accessor_map_);
3765
51
            if (!accessor_map_.contains(*rid)) {
3766
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
3767
0
                        .tag("resource_id", resource_id)
3768
0
                        .tag("instance_id", instance_id_);
3769
0
                return -1;
3770
0
            }
3771
51
            auto& accessor = accessor_map_[*rid];
3772
51
            int ret = accessor->delete_files(*paths);
3773
51
            if (!ret) {
3774
                // deduplication of different files with the same rowset id
3775
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
3776
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
3777
51
                std::set<std::string> deleted_rowset_id;
3778
3779
51
                std::for_each(paths->begin(), paths->end(),
3780
51
                              [&metrics_context, &rowsets, &deleted_rowset_id,
3781
862k
                               this](const std::string& path) {
3782
862k
                                  std::vector<std::string> str;
3783
862k
                                  butil::SplitString(path, '/', &str);
3784
862k
                                  std::string rowset_id;
3785
862k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3786
857k
                                      rowset_id = str.back().substr(0, pos);
3787
857k
                                  } else {
3788
4.77k
                                      if (path.find("packed_file/") != std::string::npos) {
3789
0
                                          return; // packed files do not have rowset_id encoded
3790
0
                                      }
3791
4.77k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3792
4.77k
                                      return;
3793
4.77k
                                  }
3794
857k
                                  auto rs_meta = rowsets.find(rowset_id);
3795
857k
                                  if (rs_meta != rowsets.end() &&
3796
862k
                                      !deleted_rowset_id.contains(rowset_id)) {
3797
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
3798
54.1k
                                      metrics_context.total_recycled_data_size +=
3799
54.1k
                                              rs_meta->second.total_disk_size();
3800
54.1k
                                      segment_metrics_context_.total_recycled_num +=
3801
54.1k
                                              rs_meta->second.num_segments();
3802
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
3803
54.1k
                                              rs_meta->second.total_disk_size();
3804
54.1k
                                      metrics_context.total_recycled_num++;
3805
54.1k
                                  }
3806
857k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
3781
14
                               this](const std::string& path) {
3782
14
                                  std::vector<std::string> str;
3783
14
                                  butil::SplitString(path, '/', &str);
3784
14
                                  std::string rowset_id;
3785
14
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3786
14
                                      rowset_id = str.back().substr(0, pos);
3787
14
                                  } else {
3788
0
                                      if (path.find("packed_file/") != std::string::npos) {
3789
0
                                          return; // packed files do not have rowset_id encoded
3790
0
                                      }
3791
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3792
0
                                      return;
3793
0
                                  }
3794
14
                                  auto rs_meta = rowsets.find(rowset_id);
3795
14
                                  if (rs_meta != rowsets.end() &&
3796
14
                                      !deleted_rowset_id.contains(rowset_id)) {
3797
7
                                      deleted_rowset_id.emplace(rowset_id);
3798
7
                                      metrics_context.total_recycled_data_size +=
3799
7
                                              rs_meta->second.total_disk_size();
3800
7
                                      segment_metrics_context_.total_recycled_num +=
3801
7
                                              rs_meta->second.num_segments();
3802
7
                                      segment_metrics_context_.total_recycled_data_size +=
3803
7
                                              rs_meta->second.total_disk_size();
3804
7
                                      metrics_context.total_recycled_num++;
3805
7
                                  }
3806
14
                              });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
3781
862k
                               this](const std::string& path) {
3782
862k
                                  std::vector<std::string> str;
3783
862k
                                  butil::SplitString(path, '/', &str);
3784
862k
                                  std::string rowset_id;
3785
862k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3786
857k
                                      rowset_id = str.back().substr(0, pos);
3787
857k
                                  } else {
3788
4.77k
                                      if (path.find("packed_file/") != std::string::npos) {
3789
0
                                          return; // packed files do not have rowset_id encoded
3790
0
                                      }
3791
4.77k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3792
4.77k
                                      return;
3793
4.77k
                                  }
3794
857k
                                  auto rs_meta = rowsets.find(rowset_id);
3795
857k
                                  if (rs_meta != rowsets.end() &&
3796
862k
                                      !deleted_rowset_id.contains(rowset_id)) {
3797
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
3798
54.1k
                                      metrics_context.total_recycled_data_size +=
3799
54.1k
                                              rs_meta->second.total_disk_size();
3800
54.1k
                                      segment_metrics_context_.total_recycled_num +=
3801
54.1k
                                              rs_meta->second.num_segments();
3802
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
3803
54.1k
                                              rs_meta->second.total_disk_size();
3804
54.1k
                                      metrics_context.total_recycled_num++;
3805
54.1k
                                  }
3806
857k
                              });
3807
51
            }
3808
51
            return ret;
3809
51
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
3759
5
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
3760
5
            DCHECK(accessor_map_.count(*rid))
3761
0
                    << "uninitilized accessor, instance_id=" << instance_id_
3762
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
3763
5
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
3764
5
                                     &accessor_map_);
3765
5
            if (!accessor_map_.contains(*rid)) {
3766
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
3767
0
                        .tag("resource_id", resource_id)
3768
0
                        .tag("instance_id", instance_id_);
3769
0
                return -1;
3770
0
            }
3771
5
            auto& accessor = accessor_map_[*rid];
3772
5
            int ret = accessor->delete_files(*paths);
3773
5
            if (!ret) {
3774
                // deduplication of different files with the same rowset id
3775
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
3776
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
3777
5
                std::set<std::string> deleted_rowset_id;
3778
3779
5
                std::for_each(paths->begin(), paths->end(),
3780
5
                              [&metrics_context, &rowsets, &deleted_rowset_id,
3781
5
                               this](const std::string& path) {
3782
5
                                  std::vector<std::string> str;
3783
5
                                  butil::SplitString(path, '/', &str);
3784
5
                                  std::string rowset_id;
3785
5
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3786
5
                                      rowset_id = str.back().substr(0, pos);
3787
5
                                  } else {
3788
5
                                      if (path.find("packed_file/") != std::string::npos) {
3789
5
                                          return; // packed files do not have rowset_id encoded
3790
5
                                      }
3791
5
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3792
5
                                      return;
3793
5
                                  }
3794
5
                                  auto rs_meta = rowsets.find(rowset_id);
3795
5
                                  if (rs_meta != rowsets.end() &&
3796
5
                                      !deleted_rowset_id.contains(rowset_id)) {
3797
5
                                      deleted_rowset_id.emplace(rowset_id);
3798
5
                                      metrics_context.total_recycled_data_size +=
3799
5
                                              rs_meta->second.total_disk_size();
3800
5
                                      segment_metrics_context_.total_recycled_num +=
3801
5
                                              rs_meta->second.num_segments();
3802
5
                                      segment_metrics_context_.total_recycled_data_size +=
3803
5
                                              rs_meta->second.total_disk_size();
3804
5
                                      metrics_context.total_recycled_num++;
3805
5
                                  }
3806
5
                              });
3807
5
            }
3808
5
            return ret;
3809
5
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
3759
46
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
3760
46
            DCHECK(accessor_map_.count(*rid))
3761
0
                    << "uninitilized accessor, instance_id=" << instance_id_
3762
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
3763
46
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
3764
46
                                     &accessor_map_);
3765
46
            if (!accessor_map_.contains(*rid)) {
3766
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
3767
0
                        .tag("resource_id", resource_id)
3768
0
                        .tag("instance_id", instance_id_);
3769
0
                return -1;
3770
0
            }
3771
46
            auto& accessor = accessor_map_[*rid];
3772
46
            int ret = accessor->delete_files(*paths);
3773
46
            if (!ret) {
3774
                // deduplication of different files with the same rowset id
3775
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
3776
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
3777
46
                std::set<std::string> deleted_rowset_id;
3778
3779
46
                std::for_each(paths->begin(), paths->end(),
3780
46
                              [&metrics_context, &rowsets, &deleted_rowset_id,
3781
46
                               this](const std::string& path) {
3782
46
                                  std::vector<std::string> str;
3783
46
                                  butil::SplitString(path, '/', &str);
3784
46
                                  std::string rowset_id;
3785
46
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3786
46
                                      rowset_id = str.back().substr(0, pos);
3787
46
                                  } else {
3788
46
                                      if (path.find("packed_file/") != std::string::npos) {
3789
46
                                          return; // packed files do not have rowset_id encoded
3790
46
                                      }
3791
46
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3792
46
                                      return;
3793
46
                                  }
3794
46
                                  auto rs_meta = rowsets.find(rowset_id);
3795
46
                                  if (rs_meta != rowsets.end() &&
3796
46
                                      !deleted_rowset_id.contains(rowset_id)) {
3797
46
                                      deleted_rowset_id.emplace(rowset_id);
3798
46
                                      metrics_context.total_recycled_data_size +=
3799
46
                                              rs_meta->second.total_disk_size();
3800
46
                                      segment_metrics_context_.total_recycled_num +=
3801
46
                                              rs_meta->second.num_segments();
3802
46
                                      segment_metrics_context_.total_recycled_data_size +=
3803
46
                                              rs_meta->second.total_disk_size();
3804
46
                                      metrics_context.total_recycled_num++;
3805
46
                                  }
3806
46
                              });
3807
46
            }
3808
46
            return ret;
3809
46
        });
3810
51
    }
3811
98
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
3812
5
        LOG_INFO(
3813
5
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
3814
5
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
3815
5
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
3816
5
        concurrent_delete_executor.add([&]() -> int {
3817
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
3818
5
            if (!ret) {
3819
5
                auto rs = rowsets.at(rowset_id);
3820
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
3821
5
                metrics_context.total_recycled_num++;
3822
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
3823
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
3824
5
            }
3825
5
            return ret;
3826
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
3816
5
        concurrent_delete_executor.add([&]() -> int {
3817
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
3818
5
            if (!ret) {
3819
5
                auto rs = rowsets.at(rowset_id);
3820
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
3821
5
                metrics_context.total_recycled_num++;
3822
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
3823
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
3824
5
            }
3825
5
            return ret;
3826
5
        });
3827
5
    }
3828
3829
98
    bool finished = true;
3830
98
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
3831
98
    for (int r : rets) {
3832
56
        if (r != 0) {
3833
0
            ret = -1;
3834
0
            break;
3835
0
        }
3836
56
    }
3837
98
    ret = finished ? ret : -1;
3838
98
    return ret;
3839
98
}
3840
3841
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
3842
3.30k
                                         const std::string& rowset_id) {
3843
3.30k
    auto it = accessor_map_.find(resource_id);
3844
3.30k
    if (it == accessor_map_.end()) {
3845
400
        LOG_WARNING("instance has no such resource id")
3846
400
                .tag("instance_id", instance_id_)
3847
400
                .tag("resource_id", resource_id)
3848
400
                .tag("tablet_id", tablet_id)
3849
400
                .tag("rowset_id", rowset_id);
3850
400
        return -1;
3851
400
    }
3852
2.90k
    auto& accessor = it->second;
3853
2.90k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
3854
3.30k
}
3855
3856
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
3857
4
    if (key.empty()) {
3858
0
        return false;
3859
0
    }
3860
4
    std::string_view key_view = key;
3861
4
    key_view.remove_prefix(1); // remove keyspace prefix
3862
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
3863
4
    if (decode_key(&key_view, &decoded) != 0) {
3864
0
        return false;
3865
0
    }
3866
4
    if (decoded.size() < 4) {
3867
0
        return false;
3868
0
    }
3869
4
    try {
3870
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
3871
4
    } catch (const std::bad_variant_access&) {
3872
0
        return false;
3873
0
    }
3874
4
    return true;
3875
4
}
3876
3877
14
int InstanceRecycler::recycle_packed_files() {
3878
14
    const std::string task_name = "recycle_packed_files";
3879
14
    auto start_tp = steady_clock::now();
3880
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
3881
14
    int ret = 0;
3882
14
    PackedFileRecycleStats stats;
3883
3884
14
    register_recycle_task(task_name, start_time);
3885
14
    DORIS_CLOUD_DEFER {
3886
14
        unregister_recycle_task(task_name);
3887
14
        int64_t cost =
3888
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3889
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
3890
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
3891
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
3892
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
3893
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
3894
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
3895
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
3896
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
3897
14
                                                             stats.bytes_object_deleted);
3898
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
3899
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
3900
14
                .tag("instance_id", instance_id_)
3901
14
                .tag("num_scanned", stats.num_scanned)
3902
14
                .tag("num_corrected", stats.num_corrected)
3903
14
                .tag("num_deleted", stats.num_deleted)
3904
14
                .tag("num_failed", stats.num_failed)
3905
14
                .tag("num_objects_deleted", stats.num_object_deleted)
3906
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
3907
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
3908
14
                .tag("bytes_deleted", stats.bytes_deleted)
3909
14
                .tag("ret", ret);
3910
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
3885
14
    DORIS_CLOUD_DEFER {
3886
14
        unregister_recycle_task(task_name);
3887
14
        int64_t cost =
3888
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3889
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
3890
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
3891
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
3892
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
3893
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
3894
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
3895
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
3896
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
3897
14
                                                             stats.bytes_object_deleted);
3898
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
3899
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
3900
14
                .tag("instance_id", instance_id_)
3901
14
                .tag("num_scanned", stats.num_scanned)
3902
14
                .tag("num_corrected", stats.num_corrected)
3903
14
                .tag("num_deleted", stats.num_deleted)
3904
14
                .tag("num_failed", stats.num_failed)
3905
14
                .tag("num_objects_deleted", stats.num_object_deleted)
3906
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
3907
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
3908
14
                .tag("bytes_deleted", stats.bytes_deleted)
3909
14
                .tag("ret", ret);
3910
14
    };
3911
3912
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
3913
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
3914
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
3915
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
3912
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
3913
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
3914
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
3915
4
    };
3916
3917
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
3918
3919
14
    std::string begin = packed_file_key({instance_id_, ""});
3920
14
    std::string end = packed_file_key({instance_id_, "\xff"});
3921
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
3922
0
        ret = -1;
3923
0
    }
3924
3925
14
    return ret;
3926
14
}
3927
3928
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
3929
                                                  RecyclerMetricsContext& metrics_context,
3930
0
                                                  int64_t partition_id, bool is_empty_tablet) {
3931
0
    std::string tablet_key_begin, tablet_key_end;
3932
3933
0
    if (partition_id > 0) {
3934
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
3935
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
3936
0
    } else {
3937
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
3938
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
3939
0
    }
3940
    // for calculate the total num or bytes of recyled objects
3941
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
3942
0
                                                          std::string_view v) -> int {
3943
0
        doris::TabletMetaCloudPB tablet_meta_pb;
3944
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3945
0
            return 0;
3946
0
        }
3947
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3948
3949
0
        if (!check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3950
0
            return 0;
3951
0
        }
3952
3953
0
        if (!is_empty_tablet) {
3954
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
3955
0
                return 0;
3956
0
            }
3957
0
            tablet_metrics_context_.total_need_recycle_num++;
3958
0
        }
3959
0
        return 0;
3960
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_
3961
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
3962
0
    metrics_context.report(true);
3963
0
    tablet_metrics_context_.report(true);
3964
0
    segment_metrics_context_.report(true);
3965
0
    return ret;
3966
0
}
3967
3968
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
3969
0
                                                 RecyclerMetricsContext& metrics_context) {
3970
0
    int ret = 0;
3971
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
3972
0
    std::unique_ptr<Transaction> txn;
3973
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3974
0
        LOG_WARNING("failed to recycle tablet ")
3975
0
                .tag("tablet id", tablet_id)
3976
0
                .tag("instance_id", instance_id_)
3977
0
                .tag("reason", "failed to create txn");
3978
0
        ret = -1;
3979
0
    }
3980
0
    GetRowsetResponse resp;
3981
0
    std::string msg;
3982
0
    MetaServiceCode code = MetaServiceCode::OK;
3983
    // get rowsets in tablet
3984
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
3985
0
                        tablet_id, code, msg, &resp);
3986
0
    if (code != MetaServiceCode::OK) {
3987
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
3988
0
                .tag("tablet id", tablet_id)
3989
0
                .tag("msg", msg)
3990
0
                .tag("code", code)
3991
0
                .tag("instance id", instance_id_);
3992
0
        ret = -1;
3993
0
    }
3994
0
    for (const auto& rs_meta : resp.rowset_meta()) {
3995
        /*
3996
        * For compatibility, we skip the loop for [0-1] here.
3997
        * The purpose of this loop is to delete object files,
3998
        * and since [0-1] only has meta and doesn't have object files,
3999
        * skipping it doesn't affect system correctness.
4000
        *
4001
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
4002
        * would return error -1 directly, causing the recycle operation to fail.
4003
        *
4004
        * [0-1] doesn't have resource id is a bug.
4005
        * In the future, we will fix this problem, after that,
4006
        * we can remove this if statement.
4007
        *
4008
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
4009
        */
4010
4011
0
        if (rs_meta.end_version() == 1) {
4012
            // Assert that [0-1] has no resource_id to make sure
4013
            // this if statement will not be forgetted to remove
4014
            // when the resource id bug is fixed
4015
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4016
0
            continue;
4017
0
        }
4018
0
        if (!rs_meta.has_resource_id()) {
4019
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4020
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4021
0
                    .tag("instance_id", instance_id_)
4022
0
                    .tag("tablet_id", tablet_id);
4023
0
            continue;
4024
0
        }
4025
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4026
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4027
        // possible if the accessor is not initilized correctly
4028
0
        if (it == accessor_map_.end()) [[unlikely]] {
4029
0
            LOG_WARNING(
4030
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4031
0
                    "recycle process")
4032
0
                    .tag("tablet id", tablet_id)
4033
0
                    .tag("instance_id", instance_id_)
4034
0
                    .tag("resource_id", rs_meta.resource_id())
4035
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4036
0
            continue;
4037
0
        }
4038
4039
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
4040
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4041
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4042
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
4043
0
    }
4044
0
    return ret;
4045
0
}
4046
4047
4.25k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
4048
4.25k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
4049
4.25k
            .tag("instance_id", instance_id_)
4050
4.25k
            .tag("tablet_id", tablet_id);
4051
4052
4.25k
    if (should_recycle_versioned_keys()) {
4053
11
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
4054
11
        if (ret != 0) {
4055
0
            return ret;
4056
0
        }
4057
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
4058
        // during the recycle_versioned_tablet process.
4059
        //
4060
        // .. And remove restore job rowsets of this tablet too
4061
11
    }
4062
4063
4.25k
    int ret = 0;
4064
4.25k
    auto start_time = steady_clock::now();
4065
4066
4.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4067
4068
    // collect resource ids
4069
248
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4070
248
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4071
248
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4072
248
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4073
248
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
4074
248
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
4075
4076
248
    std::set<std::string> resource_ids;
4077
248
    int64_t recycle_rowsets_number = 0;
4078
248
    int64_t recycle_segments_number = 0;
4079
248
    int64_t recycle_rowsets_data_size = 0;
4080
248
    int64_t recycle_rowsets_index_size = 0;
4081
248
    int64_t recycle_restore_job_rowsets_number = 0;
4082
248
    int64_t recycle_restore_job_segments_number = 0;
4083
248
    int64_t recycle_restore_job_rowsets_data_size = 0;
4084
248
    int64_t recycle_restore_job_rowsets_index_size = 0;
4085
248
    int64_t max_rowset_version = 0;
4086
248
    int64_t min_rowset_creation_time = INT64_MAX;
4087
248
    int64_t max_rowset_creation_time = 0;
4088
248
    int64_t min_rowset_expiration_time = INT64_MAX;
4089
248
    int64_t max_rowset_expiration_time = 0;
4090
4091
248
    DORIS_CLOUD_DEFER {
4092
248
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4093
248
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4094
248
                .tag("instance_id", instance_id_)
4095
248
                .tag("tablet_id", tablet_id)
4096
248
                .tag("recycle rowsets number", recycle_rowsets_number)
4097
248
                .tag("recycle segments number", recycle_segments_number)
4098
248
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4099
248
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4100
248
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4101
248
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4102
248
                .tag("all restore job rowsets recycle data size",
4103
248
                     recycle_restore_job_rowsets_data_size)
4104
248
                .tag("all restore job rowsets recycle index size",
4105
248
                     recycle_restore_job_rowsets_index_size)
4106
248
                .tag("max rowset version", max_rowset_version)
4107
248
                .tag("min rowset creation time", min_rowset_creation_time)
4108
248
                .tag("max rowset creation time", max_rowset_creation_time)
4109
248
                .tag("min rowset expiration time", min_rowset_expiration_time)
4110
248
                .tag("max rowset expiration time", max_rowset_expiration_time)
4111
248
                .tag("task type", metrics_context.operation_type)
4112
248
                .tag("ret", ret);
4113
248
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4091
248
    DORIS_CLOUD_DEFER {
4092
248
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4093
248
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4094
248
                .tag("instance_id", instance_id_)
4095
248
                .tag("tablet_id", tablet_id)
4096
248
                .tag("recycle rowsets number", recycle_rowsets_number)
4097
248
                .tag("recycle segments number", recycle_segments_number)
4098
248
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4099
248
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4100
248
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4101
248
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4102
248
                .tag("all restore job rowsets recycle data size",
4103
248
                     recycle_restore_job_rowsets_data_size)
4104
248
                .tag("all restore job rowsets recycle index size",
4105
248
                     recycle_restore_job_rowsets_index_size)
4106
248
                .tag("max rowset version", max_rowset_version)
4107
248
                .tag("min rowset creation time", min_rowset_creation_time)
4108
248
                .tag("max rowset creation time", max_rowset_creation_time)
4109
248
                .tag("min rowset expiration time", min_rowset_expiration_time)
4110
248
                .tag("max rowset expiration time", max_rowset_expiration_time)
4111
248
                .tag("task type", metrics_context.operation_type)
4112
248
                .tag("ret", ret);
4113
248
    };
4114
4115
248
    std::unique_ptr<Transaction> txn;
4116
248
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4117
0
        LOG_WARNING("failed to recycle tablet ")
4118
0
                .tag("tablet id", tablet_id)
4119
0
                .tag("instance_id", instance_id_)
4120
0
                .tag("reason", "failed to create txn");
4121
0
        ret = -1;
4122
0
    }
4123
248
    GetRowsetResponse resp;
4124
248
    std::string msg;
4125
248
    MetaServiceCode code = MetaServiceCode::OK;
4126
    // get rowsets in tablet
4127
248
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4128
248
                        tablet_id, code, msg, &resp);
4129
248
    if (code != MetaServiceCode::OK) {
4130
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4131
0
                .tag("tablet id", tablet_id)
4132
0
                .tag("msg", msg)
4133
0
                .tag("code", code)
4134
0
                .tag("instance id", instance_id_);
4135
0
        ret = -1;
4136
0
    }
4137
248
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
4138
4139
2.51k
    for (const auto& rs_meta : resp.rowset_meta()) {
4140
        // The rowset has no resource id and segments when it was generated by compaction
4141
        // with multiple hole rowsets or it's version is [0-1], so we can skip it.
4142
2.51k
        if (!rs_meta.has_resource_id() && rs_meta.num_segments() == 0) {
4143
0
            LOG_INFO("rowset meta does not have a resource id and no segments, skip this rowset")
4144
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4145
0
                    .tag("instance_id", instance_id_)
4146
0
                    .tag("tablet_id", tablet_id);
4147
0
            recycle_rowsets_number += 1;
4148
0
            continue;
4149
0
        }
4150
2.51k
        if (!rs_meta.has_resource_id()) {
4151
1
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4152
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
4153
1
                    .tag("instance_id", instance_id_)
4154
1
                    .tag("tablet_id", tablet_id);
4155
1
            return -1;
4156
1
        }
4157
18.4E
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4158
2.51k
        auto it = accessor_map_.find(rs_meta.resource_id());
4159
        // possible if the accessor is not initilized correctly
4160
2.51k
        if (it == accessor_map_.end()) [[unlikely]] {
4161
1
            LOG_WARNING(
4162
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4163
1
                    "recycle process")
4164
1
                    .tag("tablet id", tablet_id)
4165
1
                    .tag("instance_id", instance_id_)
4166
1
                    .tag("resource_id", rs_meta.resource_id())
4167
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4168
1
            return -1;
4169
1
        }
4170
2.51k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4171
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
4172
0
                    .tag("instance_id", instance_id_)
4173
0
                    .tag("tablet_id", tablet_id)
4174
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4175
0
            return -1;
4176
0
        }
4177
2.51k
        recycle_rowsets_number += 1;
4178
2.51k
        recycle_segments_number += rs_meta.num_segments();
4179
2.51k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4180
2.51k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4181
2.51k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4182
2.51k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4183
2.51k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4184
2.51k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4185
2.51k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4186
2.51k
        resource_ids.emplace(rs_meta.resource_id());
4187
2.51k
    }
4188
4189
    // get restore job rowset in tablet
4190
246
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
4191
246
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
4192
246
    if (code != MetaServiceCode::OK) {
4193
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
4194
0
                .tag("tablet id", tablet_id)
4195
0
                .tag("msg", msg)
4196
0
                .tag("code", code)
4197
0
                .tag("instance id", instance_id_);
4198
0
        return -1;
4199
0
    }
4200
4201
246
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
4202
0
        if (!rs_meta.has_resource_id()) {
4203
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4204
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4205
0
                    .tag("instance_id", instance_id_)
4206
0
                    .tag("tablet_id", tablet_id);
4207
0
            return -1;
4208
0
        }
4209
4210
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4211
        // possible if the accessor is not initilized correctly
4212
0
        if (it == accessor_map_.end()) [[unlikely]] {
4213
0
            LOG_WARNING(
4214
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4215
0
                    "recycle process")
4216
0
                    .tag("tablet id", tablet_id)
4217
0
                    .tag("instance_id", instance_id_)
4218
0
                    .tag("resource_id", rs_meta.resource_id())
4219
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4220
0
            return -1;
4221
0
        }
4222
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4223
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
4224
0
                    .tag("instance_id", instance_id_)
4225
0
                    .tag("tablet_id", tablet_id)
4226
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4227
0
            return -1;
4228
0
        }
4229
0
        recycle_restore_job_rowsets_number += 1;
4230
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
4231
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
4232
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
4233
0
        resource_ids.emplace(rs_meta.resource_id());
4234
0
    }
4235
4236
246
    LOG_INFO("recycle tablet start to delete object")
4237
246
            .tag("instance id", instance_id_)
4238
246
            .tag("tablet id", tablet_id)
4239
246
            .tag("recycle tablet resource ids are",
4240
246
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
4241
246
                                 [](std::string rs_id, const auto& it) {
4242
206
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4243
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
4241
206
                                 [](std::string rs_id, const auto& it) {
4242
206
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4243
206
                                 }));
4244
4245
246
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
4246
246
            _thread_pool_group.s3_producer_pool,
4247
246
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4248
246
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKSt4pairIiNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKSt4pairIiNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE
Line
Count
Source
4248
206
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
4249
4250
    // delete all rowset data in this tablet
4251
    // ATTN: there may be data leak if not all accessor initilized successfully
4252
    //       partial data deleted if the tablet is stored cross-storage vault
4253
    //       vault id is not attached to TabletMeta...
4254
246
    for (const auto& resource_id : resource_ids) {
4255
206
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
4256
206
        concurrent_delete_executor.add(
4257
206
                [&, rs_id = resource_id,
4258
206
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4259
206
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4260
206
                    if (res != 0) {
4261
2
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4262
2
                                     << " path=" << accessor_ptr->uri()
4263
2
                                     << " task type=" << metrics_context.operation_type;
4264
2
                        return std::make_pair(-1, rs_id);
4265
2
                    }
4266
204
                    return std::make_pair(0, rs_id);
4267
206
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
4258
206
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4259
206
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4260
206
                    if (res != 0) {
4261
2
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4262
2
                                     << " path=" << accessor_ptr->uri()
4263
2
                                     << " task type=" << metrics_context.operation_type;
4264
2
                        return std::make_pair(-1, rs_id);
4265
2
                    }
4266
204
                    return std::make_pair(0, rs_id);
4267
206
                });
4268
206
    }
4269
4270
246
    bool finished = true;
4271
246
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
4272
246
    for (auto& r : rets) {
4273
206
        if (r.first != 0) {
4274
2
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
4275
2
            ret = -1;
4276
2
        }
4277
206
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
4278
206
    }
4279
246
    ret = finished ? ret : -1;
4280
4281
246
    if (ret != 0) { // failed recycle tablet data
4282
2
        LOG_WARNING("ret!=0")
4283
2
                .tag("finished", finished)
4284
2
                .tag("ret", ret)
4285
2
                .tag("instance_id", instance_id_)
4286
2
                .tag("tablet_id", tablet_id);
4287
2
        return ret;
4288
2
    }
4289
4290
244
    tablet_metrics_context_.total_recycled_data_size +=
4291
244
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4292
244
    tablet_metrics_context_.total_recycled_num += 1;
4293
244
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
4294
244
    segment_metrics_context_.total_recycled_data_size +=
4295
244
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4296
244
    metrics_context.total_recycled_data_size +=
4297
244
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4298
244
    tablet_metrics_context_.report();
4299
244
    segment_metrics_context_.report();
4300
244
    metrics_context.report();
4301
4302
244
    txn.reset();
4303
244
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4304
0
        LOG_WARNING("failed to recycle tablet ")
4305
0
                .tag("tablet id", tablet_id)
4306
0
                .tag("instance_id", instance_id_)
4307
0
                .tag("reason", "failed to create txn");
4308
0
        ret = -1;
4309
0
    }
4310
    // delete all rowset kv in this tablet
4311
244
    txn->remove(rs_key0, rs_key1);
4312
244
    txn->remove(recyc_rs_key0, recyc_rs_key1);
4313
244
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
4314
4315
    // remove delete bitmap for MoW table
4316
244
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
4317
244
    txn->remove(pending_key);
4318
244
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
4319
244
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
4320
244
    txn->remove(delete_bitmap_start, delete_bitmap_end);
4321
4322
244
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
4323
244
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
4324
244
    txn->remove(dbm_start_key, dbm_end_key);
4325
244
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
4326
244
              << " end=" << hex(dbm_end_key);
4327
4328
244
    TxnErrorCode err = txn->commit();
4329
244
    if (err != TxnErrorCode::TXN_OK) {
4330
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
4331
0
        ret = -1;
4332
0
    }
4333
4334
244
    if (ret == 0) {
4335
        // All object files under tablet have been deleted
4336
244
        std::lock_guard lock(recycled_tablets_mtx_);
4337
244
        recycled_tablets_.insert(tablet_id);
4338
244
    }
4339
4340
244
    return ret;
4341
246
}
4342
4343
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
4344
11
                                               RecyclerMetricsContext& metrics_context) {
4345
11
    int ret = 0;
4346
11
    auto start_time = steady_clock::now();
4347
4348
11
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4349
4350
    // collect resource ids
4351
11
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4352
11
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4353
11
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4354
11
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4355
4356
11
    int64_t recycle_rowsets_number = 0;
4357
11
    int64_t recycle_segments_number = 0;
4358
11
    int64_t recycle_rowsets_data_size = 0;
4359
11
    int64_t recycle_rowsets_index_size = 0;
4360
11
    int64_t max_rowset_version = 0;
4361
11
    int64_t min_rowset_creation_time = INT64_MAX;
4362
11
    int64_t max_rowset_creation_time = 0;
4363
11
    int64_t min_rowset_expiration_time = INT64_MAX;
4364
11
    int64_t max_rowset_expiration_time = 0;
4365
4366
11
    DORIS_CLOUD_DEFER {
4367
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4368
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4369
11
                .tag("instance_id", instance_id_)
4370
11
                .tag("tablet_id", tablet_id)
4371
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4372
11
                .tag("recycle segments number", recycle_segments_number)
4373
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4374
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4375
11
                .tag("max rowset version", max_rowset_version)
4376
11
                .tag("min rowset creation time", min_rowset_creation_time)
4377
11
                .tag("max rowset creation time", max_rowset_creation_time)
4378
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4379
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4380
11
                .tag("ret", ret);
4381
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4366
11
    DORIS_CLOUD_DEFER {
4367
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4368
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4369
11
                .tag("instance_id", instance_id_)
4370
11
                .tag("tablet_id", tablet_id)
4371
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4372
11
                .tag("recycle segments number", recycle_segments_number)
4373
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4374
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4375
11
                .tag("max rowset version", max_rowset_version)
4376
11
                .tag("min rowset creation time", min_rowset_creation_time)
4377
11
                .tag("max rowset creation time", max_rowset_creation_time)
4378
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4379
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4380
11
                .tag("ret", ret);
4381
11
    };
4382
4383
11
    std::unique_ptr<Transaction> txn;
4384
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4385
0
        LOG_WARNING("failed to recycle tablet ")
4386
0
                .tag("tablet id", tablet_id)
4387
0
                .tag("instance_id", instance_id_)
4388
0
                .tag("reason", "failed to create txn");
4389
0
        ret = -1;
4390
0
    }
4391
4392
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
4393
    // by the related operation logs.
4394
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
4395
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
4396
11
    MetaReader meta_reader(instance_id_);
4397
11
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
4398
11
    if (err == TxnErrorCode::TXN_OK) {
4399
11
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
4400
11
    }
4401
11
    if (err != TxnErrorCode::TXN_OK) {
4402
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4403
0
                .tag("tablet id", tablet_id)
4404
0
                .tag("err", err)
4405
0
                .tag("instance id", instance_id_);
4406
0
        ret = -1;
4407
0
    }
4408
4409
11
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
4410
11
             load_rowset_metas.size(), compact_rowset_metas.size())
4411
11
            .tag("instance_id", instance_id_)
4412
11
            .tag("tablet_id", tablet_id);
4413
4414
11
    SyncExecutor<int> concurrent_delete_executor(
4415
11
            _thread_pool_group.s3_producer_pool,
4416
11
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4417
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
4418
4419
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
4420
60
        recycle_rowsets_number += 1;
4421
60
        recycle_segments_number += rs_meta.num_segments();
4422
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4423
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4424
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4425
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4426
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4427
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4428
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4429
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
4419
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
4420
60
        recycle_rowsets_number += 1;
4421
60
        recycle_segments_number += rs_meta.num_segments();
4422
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4423
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4424
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4425
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4426
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4427
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4428
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4429
60
    };
4430
4431
11
    std::vector<RowsetDeleteTask> all_tasks;
4432
60
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
4433
60
        update_rowset_stats(rs_meta);
4434
        // Version 0-1 rowset has no resource_id and no actual data files,
4435
        // but still needs ref_count key cleanup, so we add it to all_tasks.
4436
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
4437
60
        RowsetDeleteTask task;
4438
60
        task.rowset_meta = rs_meta;
4439
60
        task.versioned_rowset_key =
4440
60
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
4441
60
        task.non_versioned_rowset_key =
4442
60
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
4443
60
        task.versionstamp = versionstamp;
4444
60
        all_tasks.push_back(std::move(task));
4445
60
    }
4446
4447
11
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
4448
0
        update_rowset_stats(rs_meta);
4449
        // Version 0-1 rowset has no resource_id and no actual data files,
4450
        // but still needs ref_count key cleanup, so we add it to all_tasks.
4451
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
4452
0
        RowsetDeleteTask task;
4453
0
        task.rowset_meta = rs_meta;
4454
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
4455
0
                {instance_id_, tablet_id, rs_meta.end_version()});
4456
0
        task.non_versioned_rowset_key =
4457
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
4458
0
        task.versionstamp = versionstamp;
4459
0
        all_tasks.push_back(std::move(task));
4460
0
    }
4461
4462
11
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
4463
0
        RecycleRowsetPB recycle_rowset;
4464
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
4465
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4466
0
            return -1;
4467
0
        }
4468
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
4469
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
4470
                // in old version, keep this key-value pair and it needs to be checked manually
4471
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4472
0
                return -1;
4473
0
            }
4474
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
4475
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
4476
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
4477
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
4478
0
                return -1;
4479
0
            }
4480
            // decode rowset_id
4481
0
            auto k1 = k;
4482
0
            k1.remove_prefix(1);
4483
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
4484
0
            decode_key(&k1, &out);
4485
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
4486
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
4487
0
            LOG_INFO("delete old-version rowset data")
4488
0
                    .tag("instance_id", instance_id_)
4489
0
                    .tag("tablet_id", tablet_id)
4490
0
                    .tag("rowset_id", rowset_id);
4491
4492
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
4493
            // so we must use prefix deletion directly instead of batch delete.
4494
0
            concurrent_delete_executor.add(
4495
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
4496
                        // delete by prefix, the recycle rowset key will be deleted by range later.
4497
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
4498
0
                    });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Unexecuted instantiation: recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
4499
0
        } else {
4500
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
4501
            // Version 0-1 rowset has no resource_id and no actual data files,
4502
            // but still needs ref_count key cleanup, so we add it to all_tasks.
4503
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
4504
0
            RowsetDeleteTask task;
4505
0
            task.rowset_meta = rowset_meta;
4506
0
            task.recycle_rowset_key = k;
4507
0
            all_tasks.push_back(std::move(task));
4508
0
        }
4509
0
        return 0;
4510
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
4511
4512
11
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
4513
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
4514
0
                .tag("tablet id", tablet_id)
4515
0
                .tag("instance_id", instance_id_)
4516
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
4517
0
        ret = -1;
4518
0
    }
4519
4520
    // Phase 1: Classify tasks by ref_count
4521
11
    std::vector<RowsetDeleteTask> batch_delete_tasks;
4522
60
    for (auto& task : all_tasks) {
4523
60
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
4524
60
        if (classify_ret < 0) {
4525
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
4526
0
                    .tag("instance_id", instance_id_)
4527
0
                    .tag("tablet_id", tablet_id)
4528
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
4529
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
4530
0
                return recycle_rowset_meta_and_data(t);
4531
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_4clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_4clEv
4532
0
        }
4533
60
    }
4534
4535
11
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
4536
4537
11
    LOG_INFO("batch delete plan created")
4538
11
            .tag("instance_id", instance_id_)
4539
11
            .tag("tablet_id", tablet_id)
4540
11
            .tag("plan_count", batch_delete_tasks.size());
4541
4542
    // Phase 2: Execute batch delete using existing delete_rowset_data
4543
11
    if (!batch_delete_tasks.empty()) {
4544
10
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
4545
49
        for (const auto& task : batch_delete_tasks) {
4546
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
4547
49
            if (task.rowset_meta.resource_id().empty()) {
4548
10
                LOG_INFO("skip rowset with empty resource_id in batch delete")
4549
10
                        .tag("instance_id", instance_id_)
4550
10
                        .tag("tablet_id", tablet_id)
4551
10
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
4552
10
                continue;
4553
10
            }
4554
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
4555
39
        }
4556
4557
        // Only call delete_rowset_data if there are rowsets with actual data to delete
4558
10
        bool delete_success = true;
4559
10
        if (!rowsets_to_delete.empty()) {
4560
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
4561
9
                                                         "batch_delete_versioned_tablet");
4562
9
            int delete_ret = delete_rowset_data(
4563
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
4564
9
            if (delete_ret != 0) {
4565
0
                LOG_WARNING("batch delete execution failed")
4566
0
                        .tag("instance_id", instance_id_)
4567
0
                        .tag("tablet_id", tablet_id);
4568
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
4569
0
                ret = -1;
4570
0
                delete_success = false;
4571
0
            }
4572
9
        }
4573
4574
        // Phase 3: Only cleanup metadata if data deletion succeeded.
4575
        // If deletion failed, keep recycle_rowset_key so next round will retry.
4576
10
        if (delete_success) {
4577
10
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
4578
10
            if (cleanup_ret != 0) {
4579
0
                LOG_WARNING("batch delete cleanup failed")
4580
0
                        .tag("instance_id", instance_id_)
4581
0
                        .tag("tablet_id", tablet_id);
4582
0
                ret = -1;
4583
0
            }
4584
10
        }
4585
10
    }
4586
4587
    // Always wait for fallback tasks to complete before returning
4588
11
    bool finished = true;
4589
11
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4590
11
    for (int r : rets) {
4591
0
        if (r != 0) {
4592
0
            ret = -1;
4593
0
        }
4594
0
    }
4595
4596
11
    ret = finished ? ret : -1;
4597
4598
11
    if (ret != 0) { // failed recycle tablet data
4599
0
        LOG_WARNING("recycle versioned tablet failed")
4600
0
                .tag("finished", finished)
4601
0
                .tag("ret", ret)
4602
0
                .tag("instance_id", instance_id_)
4603
0
                .tag("tablet_id", tablet_id);
4604
0
        return ret;
4605
0
    }
4606
4607
11
    tablet_metrics_context_.total_recycled_data_size +=
4608
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4609
11
    tablet_metrics_context_.total_recycled_num += 1;
4610
11
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
4611
11
    segment_metrics_context_.total_recycled_data_size +=
4612
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4613
11
    metrics_context.total_recycled_data_size +=
4614
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4615
11
    tablet_metrics_context_.report();
4616
11
    segment_metrics_context_.report();
4617
11
    metrics_context.report();
4618
4619
11
    txn.reset();
4620
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4621
0
        LOG_WARNING("failed to recycle tablet ")
4622
0
                .tag("tablet id", tablet_id)
4623
0
                .tag("instance_id", instance_id_)
4624
0
                .tag("reason", "failed to create txn");
4625
0
        ret = -1;
4626
0
    }
4627
    // delete all rowset kv in this tablet
4628
11
    txn->remove(rs_key0, rs_key1);
4629
11
    txn->remove(recyc_rs_key0, recyc_rs_key1);
4630
4631
    // remove delete bitmap for MoW table
4632
11
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
4633
11
    txn->remove(pending_key);
4634
11
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
4635
11
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
4636
11
    txn->remove(delete_bitmap_start, delete_bitmap_end);
4637
4638
11
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
4639
11
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
4640
11
    txn->remove(dbm_start_key, dbm_end_key);
4641
11
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
4642
11
              << " end=" << hex(dbm_end_key);
4643
4644
11
    std::string versioned_idx_key = versioned::tablet_index_key({instance_id_, tablet_id});
4645
11
    std::string tablet_index_val;
4646
11
    err = txn->get(versioned_idx_key, &tablet_index_val);
4647
11
    if (err != TxnErrorCode::TXN_KEY_NOT_FOUND && err != TxnErrorCode::TXN_OK) {
4648
0
        LOG_WARNING("failed to get tablet index kv")
4649
0
                .tag("instance_id", instance_id_)
4650
0
                .tag("tablet_id", tablet_id)
4651
0
                .tag("err", err);
4652
0
        ret = -1;
4653
11
    } else if (err == TxnErrorCode::TXN_OK) {
4654
        // If the tablet index kv exists, we need to delete it
4655
10
        TabletIndexPB tablet_index_pb;
4656
10
        if (!tablet_index_pb.ParseFromString(tablet_index_val)) {
4657
0
            LOG_WARNING("failed to parse tablet index pb")
4658
0
                    .tag("instance_id", instance_id_)
4659
0
                    .tag("tablet_id", tablet_id);
4660
0
            ret = -1;
4661
10
        } else {
4662
10
            std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
4663
10
                    {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
4664
10
                     tablet_index_pb.index_id(), tablet_index_pb.partition_id(), tablet_id});
4665
10
            txn->remove(versioned_inverted_idx_key);
4666
10
            txn->remove(versioned_idx_key);
4667
10
        }
4668
10
    }
4669
4670
11
    err = txn->commit();
4671
11
    if (err != TxnErrorCode::TXN_OK) {
4672
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
4673
0
        ret = -1;
4674
0
    }
4675
4676
11
    if (ret == 0) {
4677
        // All object files under tablet have been deleted
4678
11
        std::lock_guard lock(recycled_tablets_mtx_);
4679
11
        recycled_tablets_.insert(tablet_id);
4680
11
    }
4681
4682
11
    return ret;
4683
11
}
4684
4685
27
int InstanceRecycler::recycle_rowsets() {
4686
27
    if (should_recycle_versioned_keys()) {
4687
5
        return recycle_versioned_rowsets();
4688
5
    }
4689
4690
22
    const std::string task_name = "recycle_rowsets";
4691
22
    int64_t num_scanned = 0;
4692
22
    int64_t num_expired = 0;
4693
22
    int64_t num_prepare = 0;
4694
22
    int64_t num_compacted = 0;
4695
22
    int64_t num_empty_rowset = 0;
4696
22
    size_t total_rowset_key_size = 0;
4697
22
    size_t total_rowset_value_size = 0;
4698
22
    size_t expired_rowset_size = 0;
4699
22
    std::atomic_long num_recycled = 0;
4700
22
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
4701
4702
22
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
4703
22
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
4704
22
    std::string recyc_rs_key0;
4705
22
    std::string recyc_rs_key1;
4706
22
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
4707
22
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
4708
4709
22
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
4710
4711
22
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
4712
22
    register_recycle_task(task_name, start_time);
4713
4714
22
    DORIS_CLOUD_DEFER {
4715
22
        unregister_recycle_task(task_name);
4716
22
        int64_t cost =
4717
22
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4718
22
        metrics_context.finish_report();
4719
22
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
4720
22
                .tag("instance_id", instance_id_)
4721
22
                .tag("num_scanned", num_scanned)
4722
22
                .tag("num_expired", num_expired)
4723
22
                .tag("num_recycled", num_recycled)
4724
22
                .tag("num_recycled.prepare", num_prepare)
4725
22
                .tag("num_recycled.compacted", num_compacted)
4726
22
                .tag("num_recycled.empty_rowset", num_empty_rowset)
4727
22
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
4728
22
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
4729
22
                .tag("expired_rowset_meta_size", expired_rowset_size);
4730
22
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
4714
7
    DORIS_CLOUD_DEFER {
4715
7
        unregister_recycle_task(task_name);
4716
7
        int64_t cost =
4717
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4718
7
        metrics_context.finish_report();
4719
7
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
4720
7
                .tag("instance_id", instance_id_)
4721
7
                .tag("num_scanned", num_scanned)
4722
7
                .tag("num_expired", num_expired)
4723
7
                .tag("num_recycled", num_recycled)
4724
7
                .tag("num_recycled.prepare", num_prepare)
4725
7
                .tag("num_recycled.compacted", num_compacted)
4726
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
4727
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
4728
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
4729
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
4730
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
4714
15
    DORIS_CLOUD_DEFER {
4715
15
        unregister_recycle_task(task_name);
4716
15
        int64_t cost =
4717
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4718
15
        metrics_context.finish_report();
4719
15
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
4720
15
                .tag("instance_id", instance_id_)
4721
15
                .tag("num_scanned", num_scanned)
4722
15
                .tag("num_expired", num_expired)
4723
15
                .tag("num_recycled", num_recycled)
4724
15
                .tag("num_recycled.prepare", num_prepare)
4725
15
                .tag("num_recycled.compacted", num_compacted)
4726
15
                .tag("num_recycled.empty_rowset", num_empty_rowset)
4727
15
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
4728
15
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
4729
15
                .tag("expired_rowset_meta_size", expired_rowset_size);
4730
15
    };
4731
4732
22
    std::vector<std::string> rowset_keys;
4733
    // rowset_id -> rowset_meta
4734
    // store rowset id and meta for statistics rs size when delete
4735
22
    std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
4736
4737
    // Store keys of rowset recycled by background workers
4738
22
    std::mutex async_recycled_rowset_keys_mutex;
4739
22
    std::vector<std::string> async_recycled_rowset_keys;
4740
22
    auto worker_pool = std::make_unique<SimpleThreadPool>(
4741
22
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
4742
22
    worker_pool->start();
4743
    // TODO bacth delete
4744
4.00k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
4745
4.00k
        std::string dbm_start_key =
4746
4.00k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4747
4.00k
        std::string dbm_end_key = dbm_start_key;
4748
4.00k
        encode_int64(INT64_MAX, &dbm_end_key);
4749
4.00k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4750
4.00k
        if (ret != 0) {
4751
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
4752
0
                         << instance_id_;
4753
0
        }
4754
4.00k
        return ret;
4755
4.00k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
4744
2
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
4745
2
        std::string dbm_start_key =
4746
2
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4747
2
        std::string dbm_end_key = dbm_start_key;
4748
2
        encode_int64(INT64_MAX, &dbm_end_key);
4749
2
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4750
2
        if (ret != 0) {
4751
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
4752
0
                         << instance_id_;
4753
0
        }
4754
2
        return ret;
4755
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
4744
4.00k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
4745
4.00k
        std::string dbm_start_key =
4746
4.00k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4747
4.00k
        std::string dbm_end_key = dbm_start_key;
4748
4.00k
        encode_int64(INT64_MAX, &dbm_end_key);
4749
4.00k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4750
4.00k
        if (ret != 0) {
4751
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
4752
0
                         << instance_id_;
4753
0
        }
4754
4.00k
        return ret;
4755
4.00k
    };
4756
22
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
4757
902
                                            int64_t tablet_id, const std::string& rowset_id) {
4758
        // Try to delete rowset data in background thread
4759
902
        int ret = worker_pool->submit_with_timeout(
4760
902
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4761
815
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4762
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4763
0
                        return;
4764
0
                    }
4765
815
                    std::vector<std::string> keys;
4766
815
                    {
4767
815
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4768
815
                        async_recycled_rowset_keys.push_back(std::move(key));
4769
815
                        if (async_recycled_rowset_keys.size() > 100) {
4770
7
                            keys.swap(async_recycled_rowset_keys);
4771
7
                        }
4772
815
                    }
4773
815
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4774
815
                    if (keys.empty()) return;
4775
7
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4776
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4777
0
                                     << instance_id_;
4778
7
                    } else {
4779
7
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4780
7
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4781
7
                                           num_recycled, start_time);
4782
7
                    }
4783
7
                },
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
4760
2
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4761
2
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4762
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4763
0
                        return;
4764
0
                    }
4765
2
                    std::vector<std::string> keys;
4766
2
                    {
4767
2
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4768
2
                        async_recycled_rowset_keys.push_back(std::move(key));
4769
2
                        if (async_recycled_rowset_keys.size() > 100) {
4770
0
                            keys.swap(async_recycled_rowset_keys);
4771
0
                        }
4772
2
                    }
4773
2
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4774
2
                    if (keys.empty()) return;
4775
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4776
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4777
0
                                     << instance_id_;
4778
0
                    } else {
4779
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4780
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4781
0
                                           num_recycled, start_time);
4782
0
                    }
4783
0
                },
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
4760
813
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4761
813
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4762
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4763
0
                        return;
4764
0
                    }
4765
813
                    std::vector<std::string> keys;
4766
813
                    {
4767
813
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4768
813
                        async_recycled_rowset_keys.push_back(std::move(key));
4769
813
                        if (async_recycled_rowset_keys.size() > 100) {
4770
7
                            keys.swap(async_recycled_rowset_keys);
4771
7
                        }
4772
813
                    }
4773
813
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4774
813
                    if (keys.empty()) return;
4775
7
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4776
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4777
0
                                     << instance_id_;
4778
7
                    } else {
4779
7
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4780
7
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4781
7
                                           num_recycled, start_time);
4782
7
                    }
4783
7
                },
4784
902
                0);
4785
902
        if (ret == 0) return 0;
4786
        // Submit task failed, delete rowset data in current thread
4787
87
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4788
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4789
0
            return -1;
4790
0
        }
4791
87
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
4792
0
            return -1;
4793
0
        }
4794
87
        rowset_keys.push_back(std::move(key));
4795
87
        return 0;
4796
87
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
4757
2
                                            int64_t tablet_id, const std::string& rowset_id) {
4758
        // Try to delete rowset data in background thread
4759
2
        int ret = worker_pool->submit_with_timeout(
4760
2
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4761
2
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4762
2
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4763
2
                        return;
4764
2
                    }
4765
2
                    std::vector<std::string> keys;
4766
2
                    {
4767
2
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4768
2
                        async_recycled_rowset_keys.push_back(std::move(key));
4769
2
                        if (async_recycled_rowset_keys.size() > 100) {
4770
2
                            keys.swap(async_recycled_rowset_keys);
4771
2
                        }
4772
2
                    }
4773
2
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4774
2
                    if (keys.empty()) return;
4775
2
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4776
2
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4777
2
                                     << instance_id_;
4778
2
                    } else {
4779
2
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4780
2
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4781
2
                                           num_recycled, start_time);
4782
2
                    }
4783
2
                },
4784
2
                0);
4785
2
        if (ret == 0) return 0;
4786
        // Submit task failed, delete rowset data in current thread
4787
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4788
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4789
0
            return -1;
4790
0
        }
4791
0
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
4792
0
            return -1;
4793
0
        }
4794
0
        rowset_keys.push_back(std::move(key));
4795
0
        return 0;
4796
0
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
4757
900
                                            int64_t tablet_id, const std::string& rowset_id) {
4758
        // Try to delete rowset data in background thread
4759
900
        int ret = worker_pool->submit_with_timeout(
4760
900
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4761
900
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4762
900
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4763
900
                        return;
4764
900
                    }
4765
900
                    std::vector<std::string> keys;
4766
900
                    {
4767
900
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4768
900
                        async_recycled_rowset_keys.push_back(std::move(key));
4769
900
                        if (async_recycled_rowset_keys.size() > 100) {
4770
900
                            keys.swap(async_recycled_rowset_keys);
4771
900
                        }
4772
900
                    }
4773
900
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4774
900
                    if (keys.empty()) return;
4775
900
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4776
900
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4777
900
                                     << instance_id_;
4778
900
                    } else {
4779
900
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4780
900
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4781
900
                                           num_recycled, start_time);
4782
900
                    }
4783
900
                },
4784
900
                0);
4785
900
        if (ret == 0) return 0;
4786
        // Submit task failed, delete rowset data in current thread
4787
87
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4788
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4789
0
            return -1;
4790
0
        }
4791
87
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
4792
0
            return -1;
4793
0
        }
4794
87
        rowset_keys.push_back(std::move(key));
4795
87
        return 0;
4796
87
    };
4797
4798
22
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
4799
4800
7.75k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
4801
7.75k
        ++num_scanned;
4802
7.75k
        total_rowset_key_size += k.size();
4803
7.75k
        total_rowset_value_size += v.size();
4804
7.75k
        RecycleRowsetPB rowset;
4805
7.75k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
4806
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4807
0
            return -1;
4808
0
        }
4809
4810
7.75k
        int64_t current_time = ::time(nullptr);
4811
7.75k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
4812
4813
7.75k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
4814
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
4815
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
4816
7.75k
        if (current_time < expiration) { // not expired
4817
0
            return 0;
4818
0
        }
4819
7.75k
        ++num_expired;
4820
7.75k
        expired_rowset_size += v.size();
4821
4822
7.75k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
4823
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
4824
                // in old version, keep this key-value pair and it needs to be checked manually
4825
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4826
0
                return -1;
4827
0
            }
4828
250
            if (rowset.resource_id().empty()) [[unlikely]] {
4829
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
4830
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
4831
0
                          << hex(k) << " value=" << proto_to_json(rowset);
4832
0
                rowset_keys.emplace_back(k);
4833
0
                return -1;
4834
0
            }
4835
            // decode rowset_id
4836
250
            auto k1 = k;
4837
250
            k1.remove_prefix(1);
4838
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
4839
250
            decode_key(&k1, &out);
4840
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
4841
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
4842
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
4843
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
4844
250
                      << " task_type=" << metrics_context.operation_type;
4845
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
4846
250
                                             rowset.tablet_id(), rowset_id) != 0) {
4847
0
                return -1;
4848
0
            }
4849
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
4850
250
            metrics_context.total_recycled_num++;
4851
250
            segment_metrics_context_.total_recycled_data_size +=
4852
250
                    rowset.rowset_meta().total_disk_size();
4853
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
4854
250
            return 0;
4855
250
        }
4856
4857
7.50k
        auto* rowset_meta = rowset.mutable_rowset_meta();
4858
7.50k
        if (config::enable_mark_delete_rowset_before_recycle) {
4859
7.50k
            int mark_ret = mark_rowset_as_recycled(txn_kv_.get(), instance_id_, k, rowset);
4860
7.50k
            if (mark_ret == -1) {
4861
0
                LOG(WARNING) << "failed to mark rowset as recycled, instance_id=" << instance_id_
4862
0
                             << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4863
0
                             << rowset_meta->start_version() << '-' << rowset_meta->end_version()
4864
0
                             << "]";
4865
0
                return -1;
4866
7.50k
            } else if (mark_ret == 1) {
4867
3.75k
                LOG(INFO)
4868
3.75k
                        << "rowset already marked as recycled, recycler will delete data and kv at "
4869
3.75k
                           "next turn, instance_id="
4870
3.75k
                        << instance_id_ << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4871
3.75k
                        << rowset_meta->start_version() << '-' << rowset_meta->end_version() << "]";
4872
3.75k
                return 0;
4873
3.75k
            }
4874
7.50k
        }
4875
4876
3.75k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
4877
3.75k
            LOG(INFO) << "begin to abort txn or job for related rowset, instance_id="
4878
3.75k
                      << instance_id_ << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4879
3.75k
                      << rowset_meta->start_version() << '-' << rowset_meta->end_version() << "]";
4880
4881
3.75k
            if (rowset_meta->end_version() != 1) {
4882
3.75k
                int ret = abort_txn_or_job_for_recycle(rowset);
4883
4884
3.75k
                if (ret != 0) {
4885
0
                    LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
4886
0
                                 << instance_id_ << " tablet_id=" << rowset.tablet_id()
4887
0
                                 << " version=[" << rowset_meta->start_version() << '-'
4888
0
                                 << rowset_meta->end_version() << "]";
4889
0
                    return ret;
4890
0
                }
4891
3.75k
            }
4892
3.75k
        }
4893
4894
        // TODO(plat1ko): check rowset not referenced
4895
3.75k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
4896
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
4897
0
                LOG_INFO("recycle rowset that has empty resource id");
4898
0
            } else {
4899
                // other situations, keep this key-value pair and it needs to be checked manually
4900
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4901
0
                return -1;
4902
0
            }
4903
0
        }
4904
3.75k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
4905
3.75k
                  << " tablet_id=" << rowset_meta->tablet_id()
4906
3.75k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
4907
3.75k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
4908
3.75k
                  << "] txn_id=" << rowset_meta->txn_id()
4909
3.75k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
4910
3.75k
                  << " rowset_meta_size=" << v.size()
4911
3.75k
                  << " creation_time=" << rowset_meta->creation_time()
4912
3.75k
                  << " task_type=" << metrics_context.operation_type;
4913
3.75k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
4914
            // unable to calculate file path, can only be deleted by rowset id prefix
4915
652
            num_prepare += 1;
4916
652
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
4917
652
                                             rowset_meta->tablet_id(),
4918
652
                                             rowset_meta->rowset_id_v2()) != 0) {
4919
0
                return -1;
4920
0
            }
4921
3.10k
        } else {
4922
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
4923
3.10k
            rowset_keys.emplace_back(k);
4924
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
4925
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
4926
3.10k
                ++num_empty_rowset;
4927
3.10k
            }
4928
3.10k
        }
4929
3.75k
        return 0;
4930
3.75k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
4800
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
4801
7
        ++num_scanned;
4802
7
        total_rowset_key_size += k.size();
4803
7
        total_rowset_value_size += v.size();
4804
7
        RecycleRowsetPB rowset;
4805
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
4806
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4807
0
            return -1;
4808
0
        }
4809
4810
7
        int64_t current_time = ::time(nullptr);
4811
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
4812
4813
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
4814
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
4815
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
4816
7
        if (current_time < expiration) { // not expired
4817
0
            return 0;
4818
0
        }
4819
7
        ++num_expired;
4820
7
        expired_rowset_size += v.size();
4821
4822
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
4823
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
4824
                // in old version, keep this key-value pair and it needs to be checked manually
4825
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4826
0
                return -1;
4827
0
            }
4828
0
            if (rowset.resource_id().empty()) [[unlikely]] {
4829
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
4830
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
4831
0
                          << hex(k) << " value=" << proto_to_json(rowset);
4832
0
                rowset_keys.emplace_back(k);
4833
0
                return -1;
4834
0
            }
4835
            // decode rowset_id
4836
0
            auto k1 = k;
4837
0
            k1.remove_prefix(1);
4838
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
4839
0
            decode_key(&k1, &out);
4840
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
4841
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
4842
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
4843
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
4844
0
                      << " task_type=" << metrics_context.operation_type;
4845
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
4846
0
                                             rowset.tablet_id(), rowset_id) != 0) {
4847
0
                return -1;
4848
0
            }
4849
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
4850
0
            metrics_context.total_recycled_num++;
4851
0
            segment_metrics_context_.total_recycled_data_size +=
4852
0
                    rowset.rowset_meta().total_disk_size();
4853
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
4854
0
            return 0;
4855
0
        }
4856
4857
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
4858
7
        if (config::enable_mark_delete_rowset_before_recycle) {
4859
7
            int mark_ret = mark_rowset_as_recycled(txn_kv_.get(), instance_id_, k, rowset);
4860
7
            if (mark_ret == -1) {
4861
0
                LOG(WARNING) << "failed to mark rowset as recycled, instance_id=" << instance_id_
4862
0
                             << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4863
0
                             << rowset_meta->start_version() << '-' << rowset_meta->end_version()
4864
0
                             << "]";
4865
0
                return -1;
4866
7
            } else if (mark_ret == 1) {
4867
5
                LOG(INFO)
4868
5
                        << "rowset already marked as recycled, recycler will delete data and kv at "
4869
5
                           "next turn, instance_id="
4870
5
                        << instance_id_ << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4871
5
                        << rowset_meta->start_version() << '-' << rowset_meta->end_version() << "]";
4872
5
                return 0;
4873
5
            }
4874
7
        }
4875
4876
2
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
4877
2
            LOG(INFO) << "begin to abort txn or job for related rowset, instance_id="
4878
2
                      << instance_id_ << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4879
2
                      << rowset_meta->start_version() << '-' << rowset_meta->end_version() << "]";
4880
4881
2
            if (rowset_meta->end_version() != 1) {
4882
2
                int ret = abort_txn_or_job_for_recycle(rowset);
4883
4884
2
                if (ret != 0) {
4885
0
                    LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
4886
0
                                 << instance_id_ << " tablet_id=" << rowset.tablet_id()
4887
0
                                 << " version=[" << rowset_meta->start_version() << '-'
4888
0
                                 << rowset_meta->end_version() << "]";
4889
0
                    return ret;
4890
0
                }
4891
2
            }
4892
2
        }
4893
4894
        // TODO(plat1ko): check rowset not referenced
4895
2
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
4896
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
4897
0
                LOG_INFO("recycle rowset that has empty resource id");
4898
0
            } else {
4899
                // other situations, keep this key-value pair and it needs to be checked manually
4900
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4901
0
                return -1;
4902
0
            }
4903
0
        }
4904
2
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
4905
2
                  << " tablet_id=" << rowset_meta->tablet_id()
4906
2
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
4907
2
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
4908
2
                  << "] txn_id=" << rowset_meta->txn_id()
4909
2
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
4910
2
                  << " rowset_meta_size=" << v.size()
4911
2
                  << " creation_time=" << rowset_meta->creation_time()
4912
2
                  << " task_type=" << metrics_context.operation_type;
4913
2
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
4914
            // unable to calculate file path, can only be deleted by rowset id prefix
4915
2
            num_prepare += 1;
4916
2
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
4917
2
                                             rowset_meta->tablet_id(),
4918
2
                                             rowset_meta->rowset_id_v2()) != 0) {
4919
0
                return -1;
4920
0
            }
4921
2
        } else {
4922
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
4923
0
            rowset_keys.emplace_back(k);
4924
0
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
4925
0
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
4926
0
                ++num_empty_rowset;
4927
0
            }
4928
0
        }
4929
2
        return 0;
4930
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
4800
7.75k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
4801
7.75k
        ++num_scanned;
4802
7.75k
        total_rowset_key_size += k.size();
4803
7.75k
        total_rowset_value_size += v.size();
4804
7.75k
        RecycleRowsetPB rowset;
4805
7.75k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
4806
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4807
0
            return -1;
4808
0
        }
4809
4810
7.75k
        int64_t current_time = ::time(nullptr);
4811
7.75k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
4812
4813
7.75k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
4814
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
4815
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
4816
7.75k
        if (current_time < expiration) { // not expired
4817
0
            return 0;
4818
0
        }
4819
7.75k
        ++num_expired;
4820
7.75k
        expired_rowset_size += v.size();
4821
4822
7.75k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
4823
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
4824
                // in old version, keep this key-value pair and it needs to be checked manually
4825
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4826
0
                return -1;
4827
0
            }
4828
250
            if (rowset.resource_id().empty()) [[unlikely]] {
4829
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
4830
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
4831
0
                          << hex(k) << " value=" << proto_to_json(rowset);
4832
0
                rowset_keys.emplace_back(k);
4833
0
                return -1;
4834
0
            }
4835
            // decode rowset_id
4836
250
            auto k1 = k;
4837
250
            k1.remove_prefix(1);
4838
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
4839
250
            decode_key(&k1, &out);
4840
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
4841
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
4842
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
4843
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
4844
250
                      << " task_type=" << metrics_context.operation_type;
4845
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
4846
250
                                             rowset.tablet_id(), rowset_id) != 0) {
4847
0
                return -1;
4848
0
            }
4849
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
4850
250
            metrics_context.total_recycled_num++;
4851
250
            segment_metrics_context_.total_recycled_data_size +=
4852
250
                    rowset.rowset_meta().total_disk_size();
4853
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
4854
250
            return 0;
4855
250
        }
4856
4857
7.50k
        auto* rowset_meta = rowset.mutable_rowset_meta();
4858
7.50k
        if (config::enable_mark_delete_rowset_before_recycle) {
4859
7.50k
            int mark_ret = mark_rowset_as_recycled(txn_kv_.get(), instance_id_, k, rowset);
4860
7.50k
            if (mark_ret == -1) {
4861
0
                LOG(WARNING) << "failed to mark rowset as recycled, instance_id=" << instance_id_
4862
0
                             << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4863
0
                             << rowset_meta->start_version() << '-' << rowset_meta->end_version()
4864
0
                             << "]";
4865
0
                return -1;
4866
7.50k
            } else if (mark_ret == 1) {
4867
3.75k
                LOG(INFO)
4868
3.75k
                        << "rowset already marked as recycled, recycler will delete data and kv at "
4869
3.75k
                           "next turn, instance_id="
4870
3.75k
                        << instance_id_ << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4871
3.75k
                        << rowset_meta->start_version() << '-' << rowset_meta->end_version() << "]";
4872
3.75k
                return 0;
4873
3.75k
            }
4874
7.50k
        }
4875
4876
3.75k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
4877
3.75k
            LOG(INFO) << "begin to abort txn or job for related rowset, instance_id="
4878
3.75k
                      << instance_id_ << " tablet_id=" << rowset_meta->tablet_id() << " version=["
4879
3.75k
                      << rowset_meta->start_version() << '-' << rowset_meta->end_version() << "]";
4880
4881
3.75k
            if (rowset_meta->end_version() != 1) {
4882
3.75k
                int ret = abort_txn_or_job_for_recycle(rowset);
4883
4884
3.75k
                if (ret != 0) {
4885
0
                    LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
4886
0
                                 << instance_id_ << " tablet_id=" << rowset.tablet_id()
4887
0
                                 << " version=[" << rowset_meta->start_version() << '-'
4888
0
                                 << rowset_meta->end_version() << "]";
4889
0
                    return ret;
4890
0
                }
4891
3.75k
            }
4892
3.75k
        }
4893
4894
        // TODO(plat1ko): check rowset not referenced
4895
3.75k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
4896
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
4897
0
                LOG_INFO("recycle rowset that has empty resource id");
4898
0
            } else {
4899
                // other situations, keep this key-value pair and it needs to be checked manually
4900
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4901
0
                return -1;
4902
0
            }
4903
0
        }
4904
3.75k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
4905
3.75k
                  << " tablet_id=" << rowset_meta->tablet_id()
4906
3.75k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
4907
3.75k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
4908
3.75k
                  << "] txn_id=" << rowset_meta->txn_id()
4909
3.75k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
4910
3.75k
                  << " rowset_meta_size=" << v.size()
4911
3.75k
                  << " creation_time=" << rowset_meta->creation_time()
4912
3.75k
                  << " task_type=" << metrics_context.operation_type;
4913
3.75k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
4914
            // unable to calculate file path, can only be deleted by rowset id prefix
4915
650
            num_prepare += 1;
4916
650
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
4917
650
                                             rowset_meta->tablet_id(),
4918
650
                                             rowset_meta->rowset_id_v2()) != 0) {
4919
0
                return -1;
4920
0
            }
4921
3.10k
        } else {
4922
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
4923
3.10k
            rowset_keys.emplace_back(k);
4924
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
4925
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
4926
3.10k
                ++num_empty_rowset;
4927
3.10k
            }
4928
3.10k
        }
4929
3.75k
        return 0;
4930
3.75k
    };
4931
4932
49
    auto loop_done = [&]() -> int {
4933
49
        std::vector<std::string> rowset_keys_to_delete;
4934
        // rowset_id -> rowset_meta
4935
        // store rowset id and meta for statistics rs size when delete
4936
49
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
4937
49
        rowset_keys_to_delete.swap(rowset_keys);
4938
49
        rowsets_to_delete.swap(rowsets);
4939
49
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
4940
49
                             rowsets_to_delete = std::move(rowsets_to_delete)]() {
4941
49
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
4942
49
                                   metrics_context) != 0) {
4943
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
4944
0
                return;
4945
0
            }
4946
3.10k
            for (const auto& [_, rs] : rowsets_to_delete) {
4947
3.10k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
4948
0
                    return;
4949
0
                }
4950
3.10k
            }
4951
49
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
4952
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
4953
0
                return;
4954
0
            }
4955
49
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
4956
49
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
4940
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() {
4941
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
4942
7
                                   metrics_context) != 0) {
4943
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
4944
0
                return;
4945
0
            }
4946
7
            for (const auto& [_, rs] : rowsets_to_delete) {
4947
0
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
4948
0
                    return;
4949
0
                }
4950
0
            }
4951
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
4952
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
4953
0
                return;
4954
0
            }
4955
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
4956
7
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
4940
42
                             rowsets_to_delete = std::move(rowsets_to_delete)]() {
4941
42
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
4942
42
                                   metrics_context) != 0) {
4943
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
4944
0
                return;
4945
0
            }
4946
3.10k
            for (const auto& [_, rs] : rowsets_to_delete) {
4947
3.10k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
4948
0
                    return;
4949
0
                }
4950
3.10k
            }
4951
42
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
4952
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
4953
0
                return;
4954
0
            }
4955
42
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
4956
42
        });
4957
49
        return 0;
4958
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
4932
7
    auto loop_done = [&]() -> int {
4933
7
        std::vector<std::string> rowset_keys_to_delete;
4934
        // rowset_id -> rowset_meta
4935
        // store rowset id and meta for statistics rs size when delete
4936
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
4937
7
        rowset_keys_to_delete.swap(rowset_keys);
4938
7
        rowsets_to_delete.swap(rowsets);
4939
7
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
4940
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() {
4941
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
4942
7
                                   metrics_context) != 0) {
4943
7
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
4944
7
                return;
4945
7
            }
4946
7
            for (const auto& [_, rs] : rowsets_to_delete) {
4947
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
4948
7
                    return;
4949
7
                }
4950
7
            }
4951
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
4952
7
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
4953
7
                return;
4954
7
            }
4955
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
4956
7
        });
4957
7
        return 0;
4958
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
4932
42
    auto loop_done = [&]() -> int {
4933
42
        std::vector<std::string> rowset_keys_to_delete;
4934
        // rowset_id -> rowset_meta
4935
        // store rowset id and meta for statistics rs size when delete
4936
42
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
4937
42
        rowset_keys_to_delete.swap(rowset_keys);
4938
42
        rowsets_to_delete.swap(rowsets);
4939
42
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
4940
42
                             rowsets_to_delete = std::move(rowsets_to_delete)]() {
4941
42
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
4942
42
                                   metrics_context) != 0) {
4943
42
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
4944
42
                return;
4945
42
            }
4946
42
            for (const auto& [_, rs] : rowsets_to_delete) {
4947
42
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
4948
42
                    return;
4949
42
                }
4950
42
            }
4951
42
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
4952
42
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
4953
42
                return;
4954
42
            }
4955
42
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
4956
42
        });
4957
42
        return 0;
4958
42
    };
4959
4960
22
    if (config::enable_recycler_stats_metrics) {
4961
0
        scan_and_statistics_rowsets();
4962
0
    }
4963
    // recycle_func and loop_done for scan and recycle
4964
22
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
4965
22
                               std::move(loop_done));
4966
4967
22
    worker_pool->stop();
4968
4969
22
    if (!async_recycled_rowset_keys.empty()) {
4970
5
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
4971
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
4972
0
            return -1;
4973
5
        } else {
4974
5
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
4975
5
        }
4976
5
    }
4977
4978
    // Report final metrics after all concurrent tasks completed
4979
22
    segment_metrics_context_.report();
4980
22
    metrics_context.report();
4981
4982
22
    return ret;
4983
22
}
4984
4985
13
int InstanceRecycler::recycle_restore_jobs() {
4986
13
    const std::string task_name = "recycle_restore_jobs";
4987
13
    int64_t num_scanned = 0;
4988
13
    int64_t num_expired = 0;
4989
13
    int64_t num_recycled = 0;
4990
13
    int64_t num_aborted = 0;
4991
4992
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
4993
4994
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
4995
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
4996
13
    std::string restore_job_key0;
4997
13
    std::string restore_job_key1;
4998
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
4999
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
5000
5001
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
5002
5003
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5004
13
    register_recycle_task(task_name, start_time);
5005
5006
13
    DORIS_CLOUD_DEFER {
5007
13
        unregister_recycle_task(task_name);
5008
13
        int64_t cost =
5009
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5010
13
        metrics_context.finish_report();
5011
5012
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5013
13
                .tag("instance_id", instance_id_)
5014
13
                .tag("num_scanned", num_scanned)
5015
13
                .tag("num_expired", num_expired)
5016
13
                .tag("num_recycled", num_recycled)
5017
13
                .tag("num_aborted", num_aborted);
5018
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
5006
13
    DORIS_CLOUD_DEFER {
5007
13
        unregister_recycle_task(task_name);
5008
13
        int64_t cost =
5009
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5010
13
        metrics_context.finish_report();
5011
5012
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5013
13
                .tag("instance_id", instance_id_)
5014
13
                .tag("num_scanned", num_scanned)
5015
13
                .tag("num_expired", num_expired)
5016
13
                .tag("num_recycled", num_recycled)
5017
13
                .tag("num_aborted", num_aborted);
5018
13
    };
5019
5020
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5021
5022
13
    std::vector<std::string_view> restore_job_keys;
5023
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5024
41
        ++num_scanned;
5025
41
        RestoreJobCloudPB restore_job_pb;
5026
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5027
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5028
0
            return -1;
5029
0
        }
5030
41
        int64_t expiration =
5031
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5032
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5033
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5034
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5035
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5036
0
                   << " state=" << restore_job_pb.state();
5037
41
        int64_t current_time = ::time(nullptr);
5038
41
        if (current_time < expiration) { // not expired
5039
0
            return 0;
5040
0
        }
5041
41
        ++num_expired;
5042
5043
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5044
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5045
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5046
5047
41
        std::unique_ptr<Transaction> txn;
5048
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5049
41
        if (err != TxnErrorCode::TXN_OK) {
5050
0
            LOG_WARNING("failed to recycle restore job")
5051
0
                    .tag("err", err)
5052
0
                    .tag("tablet id", tablet_id)
5053
0
                    .tag("instance_id", instance_id_)
5054
0
                    .tag("reason", "failed to create txn");
5055
0
            return -1;
5056
0
        }
5057
5058
41
        std::string val;
5059
41
        err = txn->get(k, &val);
5060
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5061
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5062
0
            return 0;
5063
0
        }
5064
41
        if (err != TxnErrorCode::TXN_OK) {
5065
0
            LOG_WARNING("failed to get kv");
5066
0
            return -1;
5067
0
        }
5068
41
        restore_job_pb.Clear();
5069
41
        if (!restore_job_pb.ParseFromString(val)) {
5070
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5071
0
            return -1;
5072
0
        }
5073
5074
        // PREPARED or COMMITTED, change state to DROPPED and return
5075
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5076
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5077
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5078
0
            restore_job_pb.set_need_recycle_data(true);
5079
0
            txn->put(k, restore_job_pb.SerializeAsString());
5080
0
            err = txn->commit();
5081
0
            if (err != TxnErrorCode::TXN_OK) {
5082
0
                LOG_WARNING("failed to commit txn: {}", err);
5083
0
                return -1;
5084
0
            }
5085
0
            num_aborted++;
5086
0
            return 0;
5087
0
        }
5088
5089
        // Change state to RECYCLING
5090
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5091
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5092
21
            txn->put(k, restore_job_pb.SerializeAsString());
5093
21
            err = txn->commit();
5094
21
            if (err != TxnErrorCode::TXN_OK) {
5095
0
                LOG_WARNING("failed to commit txn: {}", err);
5096
0
                return -1;
5097
0
            }
5098
21
            return 0;
5099
21
        }
5100
5101
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5102
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5103
5104
        // Recycle all data associated with the restore job.
5105
        // This includes rowsets, segments, and related resources.
5106
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5107
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5108
0
            LOG_WARNING("failed to recycle tablet")
5109
0
                    .tag("tablet_id", tablet_id)
5110
0
                    .tag("instance_id", instance_id_);
5111
0
            return -1;
5112
0
        }
5113
5114
        // delete all restore job rowset kv
5115
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5116
5117
20
        err = txn->commit();
5118
20
        if (err != TxnErrorCode::TXN_OK) {
5119
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5120
0
                    .tag("err", err)
5121
0
                    .tag("tablet id", tablet_id)
5122
0
                    .tag("instance_id", instance_id_)
5123
0
                    .tag("reason", "failed to commit txn");
5124
0
            return -1;
5125
0
        }
5126
5127
20
        metrics_context.total_recycled_num = ++num_recycled;
5128
20
        metrics_context.report();
5129
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5130
20
        restore_job_keys.push_back(k);
5131
5132
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5133
20
                  << " tablet_id=" << tablet_id;
5134
20
        return 0;
5135
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
5023
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5024
41
        ++num_scanned;
5025
41
        RestoreJobCloudPB restore_job_pb;
5026
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5027
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5028
0
            return -1;
5029
0
        }
5030
41
        int64_t expiration =
5031
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5032
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5033
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5034
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5035
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5036
0
                   << " state=" << restore_job_pb.state();
5037
41
        int64_t current_time = ::time(nullptr);
5038
41
        if (current_time < expiration) { // not expired
5039
0
            return 0;
5040
0
        }
5041
41
        ++num_expired;
5042
5043
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5044
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5045
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5046
5047
41
        std::unique_ptr<Transaction> txn;
5048
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5049
41
        if (err != TxnErrorCode::TXN_OK) {
5050
0
            LOG_WARNING("failed to recycle restore job")
5051
0
                    .tag("err", err)
5052
0
                    .tag("tablet id", tablet_id)
5053
0
                    .tag("instance_id", instance_id_)
5054
0
                    .tag("reason", "failed to create txn");
5055
0
            return -1;
5056
0
        }
5057
5058
41
        std::string val;
5059
41
        err = txn->get(k, &val);
5060
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5061
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5062
0
            return 0;
5063
0
        }
5064
41
        if (err != TxnErrorCode::TXN_OK) {
5065
0
            LOG_WARNING("failed to get kv");
5066
0
            return -1;
5067
0
        }
5068
41
        restore_job_pb.Clear();
5069
41
        if (!restore_job_pb.ParseFromString(val)) {
5070
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5071
0
            return -1;
5072
0
        }
5073
5074
        // PREPARED or COMMITTED, change state to DROPPED and return
5075
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5076
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5077
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5078
0
            restore_job_pb.set_need_recycle_data(true);
5079
0
            txn->put(k, restore_job_pb.SerializeAsString());
5080
0
            err = txn->commit();
5081
0
            if (err != TxnErrorCode::TXN_OK) {
5082
0
                LOG_WARNING("failed to commit txn: {}", err);
5083
0
                return -1;
5084
0
            }
5085
0
            num_aborted++;
5086
0
            return 0;
5087
0
        }
5088
5089
        // Change state to RECYCLING
5090
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5091
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5092
21
            txn->put(k, restore_job_pb.SerializeAsString());
5093
21
            err = txn->commit();
5094
21
            if (err != TxnErrorCode::TXN_OK) {
5095
0
                LOG_WARNING("failed to commit txn: {}", err);
5096
0
                return -1;
5097
0
            }
5098
21
            return 0;
5099
21
        }
5100
5101
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5102
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5103
5104
        // Recycle all data associated with the restore job.
5105
        // This includes rowsets, segments, and related resources.
5106
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5107
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5108
0
            LOG_WARNING("failed to recycle tablet")
5109
0
                    .tag("tablet_id", tablet_id)
5110
0
                    .tag("instance_id", instance_id_);
5111
0
            return -1;
5112
0
        }
5113
5114
        // delete all restore job rowset kv
5115
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5116
5117
20
        err = txn->commit();
5118
20
        if (err != TxnErrorCode::TXN_OK) {
5119
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5120
0
                    .tag("err", err)
5121
0
                    .tag("tablet id", tablet_id)
5122
0
                    .tag("instance_id", instance_id_)
5123
0
                    .tag("reason", "failed to commit txn");
5124
0
            return -1;
5125
0
        }
5126
5127
20
        metrics_context.total_recycled_num = ++num_recycled;
5128
20
        metrics_context.report();
5129
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5130
20
        restore_job_keys.push_back(k);
5131
5132
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5133
20
                  << " tablet_id=" << tablet_id;
5134
20
        return 0;
5135
20
    };
5136
5137
13
    auto loop_done = [&restore_job_keys, this]() -> int {
5138
3
        if (restore_job_keys.empty()) return 0;
5139
1
        DORIS_CLOUD_DEFER {
5140
1
            restore_job_keys.clear();
5141
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5139
1
        DORIS_CLOUD_DEFER {
5140
1
            restore_job_keys.clear();
5141
1
        };
5142
5143
1
        std::unique_ptr<Transaction> txn;
5144
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5145
1
        if (err != TxnErrorCode::TXN_OK) {
5146
0
            LOG_WARNING("failed to recycle restore job")
5147
0
                    .tag("err", err)
5148
0
                    .tag("instance_id", instance_id_)
5149
0
                    .tag("reason", "failed to create txn");
5150
0
            return -1;
5151
0
        }
5152
20
        for (auto& k : restore_job_keys) {
5153
20
            txn->remove(k);
5154
20
        }
5155
1
        err = txn->commit();
5156
1
        if (err != TxnErrorCode::TXN_OK) {
5157
0
            LOG_WARNING("failed to recycle restore job")
5158
0
                    .tag("err", err)
5159
0
                    .tag("instance_id", instance_id_)
5160
0
                    .tag("reason", "failed to commit txn");
5161
0
            return -1;
5162
0
        }
5163
1
        return 0;
5164
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
5137
3
    auto loop_done = [&restore_job_keys, this]() -> int {
5138
3
        if (restore_job_keys.empty()) return 0;
5139
1
        DORIS_CLOUD_DEFER {
5140
1
            restore_job_keys.clear();
5141
1
        };
5142
5143
1
        std::unique_ptr<Transaction> txn;
5144
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5145
1
        if (err != TxnErrorCode::TXN_OK) {
5146
0
            LOG_WARNING("failed to recycle restore job")
5147
0
                    .tag("err", err)
5148
0
                    .tag("instance_id", instance_id_)
5149
0
                    .tag("reason", "failed to create txn");
5150
0
            return -1;
5151
0
        }
5152
20
        for (auto& k : restore_job_keys) {
5153
20
            txn->remove(k);
5154
20
        }
5155
1
        err = txn->commit();
5156
1
        if (err != TxnErrorCode::TXN_OK) {
5157
0
            LOG_WARNING("failed to recycle restore job")
5158
0
                    .tag("err", err)
5159
0
                    .tag("instance_id", instance_id_)
5160
0
                    .tag("reason", "failed to commit txn");
5161
0
            return -1;
5162
0
        }
5163
1
        return 0;
5164
1
    };
5165
5166
13
    if (config::enable_recycler_stats_metrics) {
5167
0
        scan_and_statistics_restore_jobs();
5168
0
    }
5169
5170
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
5171
13
                            std::move(loop_done));
5172
13
}
5173
5174
10
int InstanceRecycler::recycle_versioned_rowsets() {
5175
10
    const std::string task_name = "recycle_rowsets";
5176
10
    int64_t num_scanned = 0;
5177
10
    int64_t num_expired = 0;
5178
10
    int64_t num_prepare = 0;
5179
10
    int64_t num_compacted = 0;
5180
10
    int64_t num_empty_rowset = 0;
5181
10
    size_t total_rowset_key_size = 0;
5182
10
    size_t total_rowset_value_size = 0;
5183
10
    size_t expired_rowset_size = 0;
5184
10
    std::atomic_long num_recycled = 0;
5185
10
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5186
5187
10
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5188
10
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5189
10
    std::string recyc_rs_key0;
5190
10
    std::string recyc_rs_key1;
5191
10
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5192
10
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5193
5194
10
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5195
5196
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5197
10
    register_recycle_task(task_name, start_time);
5198
5199
10
    DORIS_CLOUD_DEFER {
5200
10
        unregister_recycle_task(task_name);
5201
10
        int64_t cost =
5202
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5203
10
        metrics_context.finish_report();
5204
10
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5205
10
                .tag("instance_id", instance_id_)
5206
10
                .tag("num_scanned", num_scanned)
5207
10
                .tag("num_expired", num_expired)
5208
10
                .tag("num_recycled", num_recycled)
5209
10
                .tag("num_recycled.prepare", num_prepare)
5210
10
                .tag("num_recycled.compacted", num_compacted)
5211
10
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5212
10
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5213
10
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5214
10
                .tag("expired_rowset_meta_size", expired_rowset_size);
5215
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
5199
10
    DORIS_CLOUD_DEFER {
5200
10
        unregister_recycle_task(task_name);
5201
10
        int64_t cost =
5202
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5203
10
        metrics_context.finish_report();
5204
10
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5205
10
                .tag("instance_id", instance_id_)
5206
10
                .tag("num_scanned", num_scanned)
5207
10
                .tag("num_expired", num_expired)
5208
10
                .tag("num_recycled", num_recycled)
5209
10
                .tag("num_recycled.prepare", num_prepare)
5210
10
                .tag("num_recycled.compacted", num_compacted)
5211
10
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5212
10
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5213
10
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5214
10
                .tag("expired_rowset_meta_size", expired_rowset_size);
5215
10
    };
5216
5217
10
    std::vector<std::string> orphan_rowset_keys;
5218
5219
    // Store keys of rowset recycled by background workers
5220
10
    std::mutex async_recycled_rowset_keys_mutex;
5221
10
    std::vector<std::string> async_recycled_rowset_keys;
5222
10
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5223
10
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5224
10
    worker_pool->start();
5225
10
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5226
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5227
        // Try to delete rowset data in background thread
5228
400
        int ret = worker_pool->submit_with_timeout(
5229
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5230
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5231
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5232
400
                        return;
5233
400
                    }
5234
                    // The async recycled rowsets are staled format or has not been used,
5235
                    // so we don't need to check the rowset ref count key.
5236
0
                    std::vector<std::string> keys;
5237
0
                    {
5238
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5239
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5240
0
                        if (async_recycled_rowset_keys.size() > 100) {
5241
0
                            keys.swap(async_recycled_rowset_keys);
5242
0
                        }
5243
0
                    }
5244
0
                    if (keys.empty()) return;
5245
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5246
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5247
0
                                     << instance_id_;
5248
0
                    } else {
5249
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5250
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5251
0
                                           num_recycled, start_time);
5252
0
                    }
5253
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
5229
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5230
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5231
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5232
400
                        return;
5233
400
                    }
5234
                    // The async recycled rowsets are staled format or has not been used,
5235
                    // so we don't need to check the rowset ref count key.
5236
0
                    std::vector<std::string> keys;
5237
0
                    {
5238
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5239
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5240
0
                        if (async_recycled_rowset_keys.size() > 100) {
5241
0
                            keys.swap(async_recycled_rowset_keys);
5242
0
                        }
5243
0
                    }
5244
0
                    if (keys.empty()) return;
5245
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5246
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5247
0
                                     << instance_id_;
5248
0
                    } else {
5249
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5250
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5251
0
                                           num_recycled, start_time);
5252
0
                    }
5253
0
                },
5254
400
                0);
5255
400
        if (ret == 0) return 0;
5256
        // Submit task failed, delete rowset data in current thread
5257
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5258
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5259
0
            return -1;
5260
0
        }
5261
0
        orphan_rowset_keys.push_back(std::move(key));
5262
0
        return 0;
5263
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
5226
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5227
        // Try to delete rowset data in background thread
5228
400
        int ret = worker_pool->submit_with_timeout(
5229
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5230
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5231
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5232
400
                        return;
5233
400
                    }
5234
                    // The async recycled rowsets are staled format or has not been used,
5235
                    // so we don't need to check the rowset ref count key.
5236
400
                    std::vector<std::string> keys;
5237
400
                    {
5238
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5239
400
                        async_recycled_rowset_keys.push_back(std::move(key));
5240
400
                        if (async_recycled_rowset_keys.size() > 100) {
5241
400
                            keys.swap(async_recycled_rowset_keys);
5242
400
                        }
5243
400
                    }
5244
400
                    if (keys.empty()) return;
5245
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5246
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5247
400
                                     << instance_id_;
5248
400
                    } else {
5249
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5250
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5251
400
                                           num_recycled, start_time);
5252
400
                    }
5253
400
                },
5254
400
                0);
5255
400
        if (ret == 0) return 0;
5256
        // Submit task failed, delete rowset data in current thread
5257
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5258
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5259
0
            return -1;
5260
0
        }
5261
0
        orphan_rowset_keys.push_back(std::move(key));
5262
0
        return 0;
5263
0
    };
5264
5265
10
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5266
5267
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
5268
2.01k
        ++num_scanned;
5269
2.01k
        total_rowset_key_size += k.size();
5270
2.01k
        total_rowset_value_size += v.size();
5271
2.01k
        RecycleRowsetPB rowset;
5272
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5273
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5274
0
            return -1;
5275
0
        }
5276
5277
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5278
5279
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5280
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
5281
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5282
2.01k
        int64_t current_time = ::time(nullptr);
5283
2.01k
        if (current_time < final_expiration) { // not expired
5284
0
            return 0;
5285
0
        }
5286
2.01k
        ++num_expired;
5287
2.01k
        expired_rowset_size += v.size();
5288
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5289
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5290
                // in old version, keep this key-value pair and it needs to be checked manually
5291
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5292
0
                return -1;
5293
0
            }
5294
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5295
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5296
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5297
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5298
0
                orphan_rowset_keys.emplace_back(k);
5299
0
                return -1;
5300
0
            }
5301
            // decode rowset_id
5302
0
            auto k1 = k;
5303
0
            k1.remove_prefix(1);
5304
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5305
0
            decode_key(&k1, &out);
5306
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5307
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5308
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5309
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
5310
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5311
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5312
0
                return -1;
5313
0
            }
5314
0
            return 0;
5315
0
        }
5316
        // TODO(plat1ko): check rowset not referenced
5317
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
5318
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5319
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5320
0
                LOG_INFO("recycle rowset that has empty resource id");
5321
0
            } else {
5322
                // other situations, keep this key-value pair and it needs to be checked manually
5323
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5324
0
                return -1;
5325
0
            }
5326
0
        }
5327
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5328
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
5329
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5330
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5331
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
5332
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5333
2.01k
                  << " rowset_meta_size=" << v.size()
5334
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
5335
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5336
            // unable to calculate file path, can only be deleted by rowset id prefix
5337
400
            num_prepare += 1;
5338
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5339
400
                                             rowset_meta->tablet_id(),
5340
400
                                             rowset_meta->rowset_id_v2()) != 0) {
5341
0
                return -1;
5342
0
            }
5343
1.61k
        } else {
5344
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
5345
1.61k
            worker_pool->submit(
5346
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5347
                        // The load & compact rowset keys are recycled during recycling operation logs.
5348
1.61k
                        RowsetDeleteTask task;
5349
1.61k
                        task.rowset_meta = rowset_meta;
5350
1.61k
                        task.recycle_rowset_key = k;
5351
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
5352
1.60k
                            return;
5353
1.60k
                        }
5354
13
                        num_compacted += is_compacted;
5355
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5356
13
                        if (rowset_meta.num_segments() == 0) {
5357
0
                            ++num_empty_rowset;
5358
0
                        }
5359
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
5346
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5347
                        // The load & compact rowset keys are recycled during recycling operation logs.
5348
1.61k
                        RowsetDeleteTask task;
5349
1.61k
                        task.rowset_meta = rowset_meta;
5350
1.61k
                        task.recycle_rowset_key = k;
5351
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
5352
1.60k
                            return;
5353
1.60k
                        }
5354
13
                        num_compacted += is_compacted;
5355
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5356
13
                        if (rowset_meta.num_segments() == 0) {
5357
0
                            ++num_empty_rowset;
5358
0
                        }
5359
13
                    });
5360
1.61k
        }
5361
2.01k
        return 0;
5362
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
5267
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
5268
2.01k
        ++num_scanned;
5269
2.01k
        total_rowset_key_size += k.size();
5270
2.01k
        total_rowset_value_size += v.size();
5271
2.01k
        RecycleRowsetPB rowset;
5272
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5273
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5274
0
            return -1;
5275
0
        }
5276
5277
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5278
5279
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5280
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
5281
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5282
2.01k
        int64_t current_time = ::time(nullptr);
5283
2.01k
        if (current_time < final_expiration) { // not expired
5284
0
            return 0;
5285
0
        }
5286
2.01k
        ++num_expired;
5287
2.01k
        expired_rowset_size += v.size();
5288
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5289
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5290
                // in old version, keep this key-value pair and it needs to be checked manually
5291
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5292
0
                return -1;
5293
0
            }
5294
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5295
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5296
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5297
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5298
0
                orphan_rowset_keys.emplace_back(k);
5299
0
                return -1;
5300
0
            }
5301
            // decode rowset_id
5302
0
            auto k1 = k;
5303
0
            k1.remove_prefix(1);
5304
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5305
0
            decode_key(&k1, &out);
5306
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5307
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5308
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5309
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
5310
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5311
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5312
0
                return -1;
5313
0
            }
5314
0
            return 0;
5315
0
        }
5316
        // TODO(plat1ko): check rowset not referenced
5317
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
5318
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5319
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5320
0
                LOG_INFO("recycle rowset that has empty resource id");
5321
0
            } else {
5322
                // other situations, keep this key-value pair and it needs to be checked manually
5323
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5324
0
                return -1;
5325
0
            }
5326
0
        }
5327
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5328
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
5329
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5330
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5331
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
5332
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5333
2.01k
                  << " rowset_meta_size=" << v.size()
5334
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
5335
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5336
            // unable to calculate file path, can only be deleted by rowset id prefix
5337
400
            num_prepare += 1;
5338
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5339
400
                                             rowset_meta->tablet_id(),
5340
400
                                             rowset_meta->rowset_id_v2()) != 0) {
5341
0
                return -1;
5342
0
            }
5343
1.61k
        } else {
5344
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
5345
1.61k
            worker_pool->submit(
5346
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5347
                        // The load & compact rowset keys are recycled during recycling operation logs.
5348
1.61k
                        RowsetDeleteTask task;
5349
1.61k
                        task.rowset_meta = rowset_meta;
5350
1.61k
                        task.recycle_rowset_key = k;
5351
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
5352
1.61k
                            return;
5353
1.61k
                        }
5354
1.61k
                        num_compacted += is_compacted;
5355
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5356
1.61k
                        if (rowset_meta.num_segments() == 0) {
5357
1.61k
                            ++num_empty_rowset;
5358
1.61k
                        }
5359
1.61k
                    });
5360
1.61k
        }
5361
2.01k
        return 0;
5362
2.01k
    };
5363
5364
10
    if (config::enable_recycler_stats_metrics) {
5365
0
        scan_and_statistics_rowsets();
5366
0
    }
5367
5368
10
    auto loop_done = [&]() -> int {
5369
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
5370
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5371
0
        }
5372
6
        orphan_rowset_keys.clear();
5373
6
        return 0;
5374
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
Line
Count
Source
5368
6
    auto loop_done = [&]() -> int {
5369
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
5370
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5371
0
        }
5372
6
        orphan_rowset_keys.clear();
5373
6
        return 0;
5374
6
    };
5375
5376
    // recycle_func and loop_done for scan and recycle
5377
10
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
5378
10
                               std::move(loop_done));
5379
5380
10
    worker_pool->stop();
5381
5382
10
    if (!async_recycled_rowset_keys.empty()) {
5383
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5384
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5385
0
            return -1;
5386
0
        } else {
5387
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5388
0
        }
5389
0
    }
5390
5391
    // Report final metrics after all concurrent tasks completed
5392
10
    segment_metrics_context_.report();
5393
10
    metrics_context.report();
5394
5395
10
    return ret;
5396
10
}
5397
5398
1.61k
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task) {
5399
1.61k
    constexpr int MAX_RETRY = 10;
5400
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
5401
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
5402
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
5403
1.61k
    std::string_view reference_instance_id = instance_id_;
5404
1.61k
    if (rowset_meta.has_reference_instance_id()) {
5405
8
        reference_instance_id = rowset_meta.reference_instance_id();
5406
8
    }
5407
5408
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
5409
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
5410
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
5411
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
5412
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
5413
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
5414
1.61k
        std::unique_ptr<Transaction> txn;
5415
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5416
1.61k
        if (err != TxnErrorCode::TXN_OK) {
5417
0
            LOG_WARNING("failed to create txn").tag("err", err);
5418
0
            return -1;
5419
0
        }
5420
5421
1.61k
        std::string rowset_ref_count_key =
5422
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
5423
1.61k
        int64_t ref_count = 0;
5424
1.61k
        {
5425
1.61k
            std::string value;
5426
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
5427
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
5428
                // This is the old version rowset, we could recycle it directly.
5429
1.60k
                ref_count = 1;
5430
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
5431
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
5432
0
                return -1;
5433
11
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
5434
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
5435
0
                return -1;
5436
0
            }
5437
1.61k
        }
5438
5439
1.61k
        if (ref_count == 1) {
5440
            // It would not be added since it is recycling.
5441
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
5442
1.60k
                LOG_WARNING("failed to delete rowset data");
5443
1.60k
                return -1;
5444
1.60k
            }
5445
5446
            // Reset the transaction to avoid timeout.
5447
10
            err = txn_kv_->create_txn(&txn);
5448
10
            if (err != TxnErrorCode::TXN_OK) {
5449
0
                LOG_WARNING("failed to create txn").tag("err", err);
5450
0
                return -1;
5451
0
            }
5452
10
            txn->remove(rowset_ref_count_key);
5453
10
            LOG_INFO("delete rowset data ref count key")
5454
10
                    .tag("txn_id", rowset_meta.txn_id())
5455
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
5456
5457
10
            std::string dbm_start_key =
5458
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
5459
10
            std::string dbm_end_key = meta_delete_bitmap_key(
5460
10
                    {reference_instance_id, tablet_id, rowset_id,
5461
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
5462
10
            txn->remove(dbm_start_key, dbm_end_key);
5463
10
            LOG_INFO("remove delete bitmap kv")
5464
10
                    .tag("begin", hex(dbm_start_key))
5465
10
                    .tag("end", hex(dbm_end_key));
5466
5467
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
5468
10
                    {reference_instance_id, tablet_id, rowset_id});
5469
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
5470
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
5471
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
5472
10
            LOG_INFO("remove versioned delete bitmap kv")
5473
10
                    .tag("begin", hex(versioned_dbm_start_key))
5474
10
                    .tag("end", hex(versioned_dbm_end_key));
5475
10
        } else {
5476
            // Decrease the rowset ref count.
5477
            //
5478
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
5479
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
5480
3
            txn->atomic_add(rowset_ref_count_key, -1);
5481
3
            LOG_INFO("decrease rowset data ref count")
5482
3
                    .tag("txn_id", rowset_meta.txn_id())
5483
3
                    .tag("ref_count", ref_count - 1)
5484
3
                    .tag("ref_count_key", hex(rowset_ref_count_key));
5485
3
        }
5486
5487
13
        if (!task.versioned_rowset_key.empty()) {
5488
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
5489
0
                                                          task.versionstamp);
5490
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
5491
0
        }
5492
5493
13
        if (!task.non_versioned_rowset_key.empty()) {
5494
0
            txn->remove(task.non_versioned_rowset_key);
5495
0
            LOG_INFO("remove non versioned rowset key")
5496
0
                    .tag("key", hex(task.non_versioned_rowset_key));
5497
0
        }
5498
5499
        // empty when recycle ref rowsets for deleted instance
5500
13
        if (!task.recycle_rowset_key.empty()) {
5501
13
            txn->remove(task.recycle_rowset_key);
5502
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
5503
13
        }
5504
5505
13
        err = txn->commit();
5506
13
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
5507
            // The rowset ref count key has been changed, we need to retry.
5508
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
5509
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
5510
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
5511
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
5512
0
            continue;
5513
13
        } else if (err != TxnErrorCode::TXN_OK) {
5514
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
5515
0
            return -1;
5516
0
        }
5517
13
        LOG_INFO("recycle rowset meta and data success");
5518
13
        return 0;
5519
13
    }
5520
0
    LOG_WARNING("failed to recycle rowset meta and data after retry")
5521
0
            .tag("tablet_id", tablet_id)
5522
0
            .tag("rowset_id", rowset_id)
5523
0
            .tag("retry", MAX_RETRY);
5524
0
    return -1;
5525
1.61k
}
5526
5527
39
int InstanceRecycler::recycle_tmp_rowsets() {
5528
39
    const std::string task_name = "recycle_tmp_rowsets";
5529
39
    int64_t num_scanned = 0;
5530
39
    int64_t num_expired = 0;
5531
39
    std::atomic_long num_recycled = 0;
5532
39
    size_t expired_rowset_size = 0;
5533
39
    size_t total_rowset_key_size = 0;
5534
39
    size_t total_rowset_value_size = 0;
5535
39
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5536
5537
39
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
5538
39
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
5539
39
    std::string tmp_rs_key0;
5540
39
    std::string tmp_rs_key1;
5541
39
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
5542
39
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
5543
5544
39
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
5545
5546
39
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5547
39
    register_recycle_task(task_name, start_time);
5548
5549
39
    DORIS_CLOUD_DEFER {
5550
39
        unregister_recycle_task(task_name);
5551
39
        int64_t cost =
5552
39
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5553
39
        metrics_context.finish_report();
5554
39
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5555
39
                .tag("instance_id", instance_id_)
5556
39
                .tag("num_scanned", num_scanned)
5557
39
                .tag("num_expired", num_expired)
5558
39
                .tag("num_recycled", num_recycled)
5559
39
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5560
39
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5561
39
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5562
39
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
5549
12
    DORIS_CLOUD_DEFER {
5550
12
        unregister_recycle_task(task_name);
5551
12
        int64_t cost =
5552
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5553
12
        metrics_context.finish_report();
5554
12
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5555
12
                .tag("instance_id", instance_id_)
5556
12
                .tag("num_scanned", num_scanned)
5557
12
                .tag("num_expired", num_expired)
5558
12
                .tag("num_recycled", num_recycled)
5559
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5560
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5561
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5562
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
5549
27
    DORIS_CLOUD_DEFER {
5550
27
        unregister_recycle_task(task_name);
5551
27
        int64_t cost =
5552
27
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5553
27
        metrics_context.finish_report();
5554
27
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5555
27
                .tag("instance_id", instance_id_)
5556
27
                .tag("num_scanned", num_scanned)
5557
27
                .tag("num_expired", num_expired)
5558
27
                .tag("num_recycled", num_recycled)
5559
27
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5560
27
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5561
27
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5562
27
    };
5563
5564
    // Elements in `tmp_rowset_keys` has the same lifetime as `it`
5565
5566
39
    std::vector<std::string> tmp_rowset_keys;
5567
39
    std::vector<std::string> tmp_rowset_ref_count_keys;
5568
5569
    // rowset_id -> rowset_meta
5570
    // store tmp_rowset id and meta for statistics rs size when delete
5571
39
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
5572
39
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5573
39
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
5574
39
    worker_pool->start();
5575
5576
39
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5577
5578
39
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &tmp_rowsets,
5579
39
                             &expired_rowset_size, &total_rowset_key_size, &total_rowset_value_size,
5580
39
                             &earlest_ts, &tmp_rowset_ref_count_keys, this,
5581
106k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5582
106k
        ++num_scanned;
5583
106k
        total_rowset_key_size += k.size();
5584
106k
        total_rowset_value_size += v.size();
5585
106k
        doris::RowsetMetaCloudPB rowset;
5586
106k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5587
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5588
0
            return -1;
5589
0
        }
5590
106k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5591
106k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5592
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5593
0
                   << " txn_expiration=" << rowset.txn_expiration()
5594
0
                   << " rowset_creation_time=" << rowset.creation_time();
5595
106k
        int64_t current_time = ::time(nullptr);
5596
106k
        if (current_time < expiration) { // not expired
5597
0
            return 0;
5598
0
        }
5599
5600
106k
        if (config::enable_mark_delete_rowset_before_recycle) {
5601
106k
            int mark_ret = mark_rowset_as_recycled(txn_kv_.get(), instance_id_, k, rowset);
5602
106k
            if (mark_ret == -1) {
5603
0
                LOG(WARNING) << "failed to mark rowset as recycled, instance_id=" << instance_id_
5604
0
                             << " tablet_id=" << rowset.tablet_id() << " version=["
5605
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5606
0
                return -1;
5607
106k
            } else if (mark_ret == 1) {
5608
52.0k
                LOG(INFO)
5609
52.0k
                        << "rowset already marked as recycled, recycler will delete data and kv at "
5610
52.0k
                           "next turn, instance_id="
5611
52.0k
                        << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5612
52.0k
                        << rowset.start_version() << '-' << rowset.end_version() << "]";
5613
52.0k
                return 0;
5614
52.0k
            }
5615
106k
        }
5616
5617
54.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
5618
54.0k
            LOG(INFO) << "begin to abort txn or job for related rowset, instance_id="
5619
54.0k
                      << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5620
54.0k
                      << rowset.start_version() << '-' << rowset.end_version() << "]";
5621
5622
54.0k
            int ret = abort_txn_or_job_for_recycle(rowset);
5623
54.0k
            if (ret != 0) {
5624
0
                LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
5625
0
                             << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5626
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5627
0
                return ret;
5628
0
            }
5629
54.0k
        }
5630
5631
54.0k
        ++num_expired;
5632
54.0k
        expired_rowset_size += v.size();
5633
54.0k
        if (!rowset.has_resource_id()) {
5634
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
5635
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
5636
0
                return -1;
5637
0
            }
5638
            // might be a delete pred rowset
5639
0
            tmp_rowset_keys.emplace_back(k);
5640
0
            return 0;
5641
0
        }
5642
        // TODO(plat1ko): check rowset not referenced
5643
54.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5644
54.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
5645
54.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
5646
54.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
5647
54.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
5648
54.0k
                  << " num_expired=" << num_expired
5649
54.0k
                  << " task_type=" << metrics_context.operation_type;
5650
5651
54.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
5652
        // Remove the rowset ref count key directly since it has not been used.
5653
54.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
5654
54.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
5655
54.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
5656
54.0k
                  << "key=" << hex(rowset_ref_count_key);
5657
54.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
5658
5659
54.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
5660
54.0k
        return 0;
5661
54.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5581
16
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5582
16
        ++num_scanned;
5583
16
        total_rowset_key_size += k.size();
5584
16
        total_rowset_value_size += v.size();
5585
16
        doris::RowsetMetaCloudPB rowset;
5586
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5587
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5588
0
            return -1;
5589
0
        }
5590
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5591
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5592
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5593
0
                   << " txn_expiration=" << rowset.txn_expiration()
5594
0
                   << " rowset_creation_time=" << rowset.creation_time();
5595
16
        int64_t current_time = ::time(nullptr);
5596
16
        if (current_time < expiration) { // not expired
5597
0
            return 0;
5598
0
        }
5599
5600
16
        if (config::enable_mark_delete_rowset_before_recycle) {
5601
16
            int mark_ret = mark_rowset_as_recycled(txn_kv_.get(), instance_id_, k, rowset);
5602
16
            if (mark_ret == -1) {
5603
0
                LOG(WARNING) << "failed to mark rowset as recycled, instance_id=" << instance_id_
5604
0
                             << " tablet_id=" << rowset.tablet_id() << " version=["
5605
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5606
0
                return -1;
5607
16
            } else if (mark_ret == 1) {
5608
9
                LOG(INFO)
5609
9
                        << "rowset already marked as recycled, recycler will delete data and kv at "
5610
9
                           "next turn, instance_id="
5611
9
                        << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5612
9
                        << rowset.start_version() << '-' << rowset.end_version() << "]";
5613
9
                return 0;
5614
9
            }
5615
16
        }
5616
5617
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
5618
7
            LOG(INFO) << "begin to abort txn or job for related rowset, instance_id="
5619
7
                      << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5620
7
                      << rowset.start_version() << '-' << rowset.end_version() << "]";
5621
5622
7
            int ret = abort_txn_or_job_for_recycle(rowset);
5623
7
            if (ret != 0) {
5624
0
                LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
5625
0
                             << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5626
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5627
0
                return ret;
5628
0
            }
5629
7
        }
5630
5631
7
        ++num_expired;
5632
7
        expired_rowset_size += v.size();
5633
7
        if (!rowset.has_resource_id()) {
5634
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
5635
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
5636
0
                return -1;
5637
0
            }
5638
            // might be a delete pred rowset
5639
0
            tmp_rowset_keys.emplace_back(k);
5640
0
            return 0;
5641
0
        }
5642
        // TODO(plat1ko): check rowset not referenced
5643
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5644
7
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
5645
7
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
5646
7
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
5647
7
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
5648
7
                  << " num_expired=" << num_expired
5649
7
                  << " task_type=" << metrics_context.operation_type;
5650
5651
7
        tmp_rowset_keys.emplace_back(k.data(), k.size());
5652
        // Remove the rowset ref count key directly since it has not been used.
5653
7
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
5654
7
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
5655
7
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
5656
7
                  << "key=" << hex(rowset_ref_count_key);
5657
7
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
5658
5659
7
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
5660
7
        return 0;
5661
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5581
106k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5582
106k
        ++num_scanned;
5583
106k
        total_rowset_key_size += k.size();
5584
106k
        total_rowset_value_size += v.size();
5585
106k
        doris::RowsetMetaCloudPB rowset;
5586
106k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5587
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5588
0
            return -1;
5589
0
        }
5590
106k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5591
106k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5592
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5593
0
                   << " txn_expiration=" << rowset.txn_expiration()
5594
0
                   << " rowset_creation_time=" << rowset.creation_time();
5595
106k
        int64_t current_time = ::time(nullptr);
5596
106k
        if (current_time < expiration) { // not expired
5597
0
            return 0;
5598
0
        }
5599
5600
106k
        if (config::enable_mark_delete_rowset_before_recycle) {
5601
106k
            int mark_ret = mark_rowset_as_recycled(txn_kv_.get(), instance_id_, k, rowset);
5602
106k
            if (mark_ret == -1) {
5603
0
                LOG(WARNING) << "failed to mark rowset as recycled, instance_id=" << instance_id_
5604
0
                             << " tablet_id=" << rowset.tablet_id() << " version=["
5605
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5606
0
                return -1;
5607
106k
            } else if (mark_ret == 1) {
5608
52.0k
                LOG(INFO)
5609
52.0k
                        << "rowset already marked as recycled, recycler will delete data and kv at "
5610
52.0k
                           "next turn, instance_id="
5611
52.0k
                        << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5612
52.0k
                        << rowset.start_version() << '-' << rowset.end_version() << "]";
5613
52.0k
                return 0;
5614
52.0k
            }
5615
106k
        }
5616
5617
54.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
5618
54.0k
            LOG(INFO) << "begin to abort txn or job for related rowset, instance_id="
5619
54.0k
                      << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5620
54.0k
                      << rowset.start_version() << '-' << rowset.end_version() << "]";
5621
5622
54.0k
            int ret = abort_txn_or_job_for_recycle(rowset);
5623
54.0k
            if (ret != 0) {
5624
0
                LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
5625
0
                             << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5626
0
                             << rowset.start_version() << '-' << rowset.end_version() << "]";
5627
0
                return ret;
5628
0
            }
5629
54.0k
        }
5630
5631
54.0k
        ++num_expired;
5632
54.0k
        expired_rowset_size += v.size();
5633
54.0k
        if (!rowset.has_resource_id()) {
5634
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
5635
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
5636
0
                return -1;
5637
0
            }
5638
            // might be a delete pred rowset
5639
0
            tmp_rowset_keys.emplace_back(k);
5640
0
            return 0;
5641
0
        }
5642
        // TODO(plat1ko): check rowset not referenced
5643
54.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5644
54.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
5645
54.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
5646
54.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
5647
54.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
5648
54.0k
                  << " num_expired=" << num_expired
5649
54.0k
                  << " task_type=" << metrics_context.operation_type;
5650
5651
54.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
5652
        // Remove the rowset ref count key directly since it has not been used.
5653
54.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
5654
54.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
5655
54.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
5656
54.0k
                  << "key=" << hex(rowset_ref_count_key);
5657
54.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
5658
5659
54.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
5660
54.0k
        return 0;
5661
54.0k
    };
5662
5663
    // TODO bacth delete
5664
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5665
51.0k
        std::string dbm_start_key =
5666
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5667
51.0k
        std::string dbm_end_key = dbm_start_key;
5668
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
5669
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5670
51.0k
        if (ret != 0) {
5671
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5672
0
                         << instance_id_ << ", tablet_id=" << tablet_id
5673
0
                         << ", rowset_id=" << rowset_id;
5674
0
        }
5675
51.0k
        return ret;
5676
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5664
7
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5665
7
        std::string dbm_start_key =
5666
7
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5667
7
        std::string dbm_end_key = dbm_start_key;
5668
7
        encode_int64(INT64_MAX, &dbm_end_key);
5669
7
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5670
7
        if (ret != 0) {
5671
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5672
0
                         << instance_id_ << ", tablet_id=" << tablet_id
5673
0
                         << ", rowset_id=" << rowset_id;
5674
0
        }
5675
7
        return ret;
5676
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5664
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5665
51.0k
        std::string dbm_start_key =
5666
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5667
51.0k
        std::string dbm_end_key = dbm_start_key;
5668
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
5669
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5670
51.0k
        if (ret != 0) {
5671
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5672
0
                         << instance_id_ << ", tablet_id=" << tablet_id
5673
0
                         << ", rowset_id=" << rowset_id;
5674
0
        }
5675
51.0k
        return ret;
5676
51.0k
    };
5677
5678
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5679
51.0k
        auto delete_bitmap_start =
5680
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
5681
51.0k
        auto delete_bitmap_end =
5682
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
5683
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
5684
51.0k
        if (ret != 0) {
5685
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
5686
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
5687
0
        }
5688
51.0k
        return ret;
5689
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5678
7
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5679
7
        auto delete_bitmap_start =
5680
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
5681
7
        auto delete_bitmap_end =
5682
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
5683
7
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
5684
7
        if (ret != 0) {
5685
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
5686
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
5687
0
        }
5688
7
        return ret;
5689
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5678
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5679
51.0k
        auto delete_bitmap_start =
5680
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
5681
51.0k
        auto delete_bitmap_end =
5682
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
5683
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
5684
51.0k
        if (ret != 0) {
5685
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
5686
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
5687
0
        }
5688
51.0k
        return ret;
5689
51.0k
    };
5690
5691
39
    auto loop_done = [&]() -> int {
5692
32
        DORIS_CLOUD_DEFER {
5693
32
            tmp_rowset_keys.clear();
5694
32
            tmp_rowsets.clear();
5695
32
            tmp_rowset_ref_count_keys.clear();
5696
32
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5692
12
        DORIS_CLOUD_DEFER {
5693
12
            tmp_rowset_keys.clear();
5694
12
            tmp_rowsets.clear();
5695
12
            tmp_rowset_ref_count_keys.clear();
5696
12
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5692
20
        DORIS_CLOUD_DEFER {
5693
20
            tmp_rowset_keys.clear();
5694
20
            tmp_rowsets.clear();
5695
20
            tmp_rowset_ref_count_keys.clear();
5696
20
        };
5697
32
        worker_pool->submit([&, tmp_rowset_keys_to_delete = tmp_rowset_keys,
5698
32
                             tmp_rowsets_to_delete = tmp_rowsets,
5699
32
                             tmp_rowset_ref_count_keys_to_delete = tmp_rowset_ref_count_keys]() {
5700
32
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5701
32
                                   metrics_context) != 0) {
5702
3
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5703
3
                return;
5704
3
            }
5705
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5706
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5707
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5708
0
                                 << rs.ShortDebugString();
5709
0
                    return;
5710
0
                }
5711
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5712
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5713
0
                                 << rs.ShortDebugString();
5714
0
                    return;
5715
0
                }
5716
51.0k
            }
5717
29
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5718
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5719
0
                return;
5720
0
            }
5721
29
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5722
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5723
0
                return;
5724
0
            }
5725
29
            num_recycled += tmp_rowset_keys.size();
5726
29
            return;
5727
29
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
5699
12
                             tmp_rowset_ref_count_keys_to_delete = tmp_rowset_ref_count_keys]() {
5700
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5701
12
                                   metrics_context) != 0) {
5702
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5703
0
                return;
5704
0
            }
5705
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5706
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5707
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5708
0
                                 << rs.ShortDebugString();
5709
0
                    return;
5710
0
                }
5711
7
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5712
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5713
0
                                 << rs.ShortDebugString();
5714
0
                    return;
5715
0
                }
5716
7
            }
5717
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5718
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5719
0
                return;
5720
0
            }
5721
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5722
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5723
0
                return;
5724
0
            }
5725
12
            num_recycled += tmp_rowset_keys.size();
5726
12
            return;
5727
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
5699
20
                             tmp_rowset_ref_count_keys_to_delete = tmp_rowset_ref_count_keys]() {
5700
20
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5701
20
                                   metrics_context) != 0) {
5702
3
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5703
3
                return;
5704
3
            }
5705
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5706
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5707
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5708
0
                                 << rs.ShortDebugString();
5709
0
                    return;
5710
0
                }
5711
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5712
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5713
0
                                 << rs.ShortDebugString();
5714
0
                    return;
5715
0
                }
5716
51.0k
            }
5717
17
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5718
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5719
0
                return;
5720
0
            }
5721
17
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5722
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5723
0
                return;
5724
0
            }
5725
17
            num_recycled += tmp_rowset_keys.size();
5726
17
            return;
5727
17
        });
5728
32
        return 0;
5729
32
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
5691
12
    auto loop_done = [&]() -> int {
5692
12
        DORIS_CLOUD_DEFER {
5693
12
            tmp_rowset_keys.clear();
5694
12
            tmp_rowsets.clear();
5695
12
            tmp_rowset_ref_count_keys.clear();
5696
12
        };
5697
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = tmp_rowset_keys,
5698
12
                             tmp_rowsets_to_delete = tmp_rowsets,
5699
12
                             tmp_rowset_ref_count_keys_to_delete = tmp_rowset_ref_count_keys]() {
5700
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5701
12
                                   metrics_context) != 0) {
5702
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5703
12
                return;
5704
12
            }
5705
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5706
12
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5707
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5708
12
                                 << rs.ShortDebugString();
5709
12
                    return;
5710
12
                }
5711
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5712
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5713
12
                                 << rs.ShortDebugString();
5714
12
                    return;
5715
12
                }
5716
12
            }
5717
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5718
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5719
12
                return;
5720
12
            }
5721
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5722
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5723
12
                return;
5724
12
            }
5725
12
            num_recycled += tmp_rowset_keys.size();
5726
12
            return;
5727
12
        });
5728
12
        return 0;
5729
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
5691
20
    auto loop_done = [&]() -> int {
5692
20
        DORIS_CLOUD_DEFER {
5693
20
            tmp_rowset_keys.clear();
5694
20
            tmp_rowsets.clear();
5695
20
            tmp_rowset_ref_count_keys.clear();
5696
20
        };
5697
20
        worker_pool->submit([&, tmp_rowset_keys_to_delete = tmp_rowset_keys,
5698
20
                             tmp_rowsets_to_delete = tmp_rowsets,
5699
20
                             tmp_rowset_ref_count_keys_to_delete = tmp_rowset_ref_count_keys]() {
5700
20
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5701
20
                                   metrics_context) != 0) {
5702
20
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5703
20
                return;
5704
20
            }
5705
20
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5706
20
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5707
20
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5708
20
                                 << rs.ShortDebugString();
5709
20
                    return;
5710
20
                }
5711
20
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5712
20
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5713
20
                                 << rs.ShortDebugString();
5714
20
                    return;
5715
20
                }
5716
20
            }
5717
20
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5718
20
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5719
20
                return;
5720
20
            }
5721
20
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5722
20
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5723
20
                return;
5724
20
            }
5725
20
            num_recycled += tmp_rowset_keys.size();
5726
20
            return;
5727
20
        });
5728
20
        return 0;
5729
20
    };
5730
5731
39
    if (config::enable_recycler_stats_metrics) {
5732
0
        scan_and_statistics_tmp_rowsets();
5733
0
    }
5734
    // recycle_func and loop_done for scan and recycle
5735
39
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
5736
39
                               std::move(loop_done));
5737
5738
39
    worker_pool->stop();
5739
5740
    // Report final metrics after all concurrent tasks completed
5741
39
    segment_metrics_context_.report();
5742
39
    metrics_context.report();
5743
5744
39
    return ret;
5745
39
}
5746
5747
int InstanceRecycler::scan_and_recycle(
5748
        std::string begin, std::string_view end,
5749
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
5750
268
        std::function<int()> loop_done) {
5751
268
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
5752
268
    int ret = 0;
5753
268
    int64_t cnt = 0;
5754
268
    int get_range_retried = 0;
5755
268
    std::string err;
5756
268
    DORIS_CLOUD_DEFER_COPY(begin, end) {
5757
268
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
5758
268
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
5759
268
                  << " ret=" << ret << " err=" << err;
5760
268
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
5756
31
    DORIS_CLOUD_DEFER_COPY(begin, end) {
5757
31
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
5758
31
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
5759
31
                  << " ret=" << ret << " err=" << err;
5760
31
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
5756
237
    DORIS_CLOUD_DEFER_COPY(begin, end) {
5757
237
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
5758
237
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
5759
237
                  << " ret=" << ret << " err=" << err;
5760
237
    };
5761
5762
268
    std::unique_ptr<RangeGetIterator> it;
5763
449
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
5764
321
        if (get_range_retried > 1000) {
5765
0
            err = "txn_get exceeds max retry(1000), may not scan all keys";
5766
0
            ret = -3;
5767
0
            return ret;
5768
0
        }
5769
321
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
5770
321
        if (get_ret != 0) { // txn kv may complain "Request for future version"
5771
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
5772
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
5773
0
                         << " get_range_retried=" << get_range_retried;
5774
0
            ++get_range_retried;
5775
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
5776
0
            continue; // try again
5777
0
        }
5778
321
        if (!it->has_next()) {
5779
140
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
5780
140
            break; // scan finished
5781
140
        }
5782
154k
        while (it->has_next()) {
5783
154k
            ++cnt;
5784
            // recycle corresponding resources
5785
154k
            auto [k, v] = it->next();
5786
154k
            if (!it->has_next()) {
5787
181
                begin = k;
5788
181
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
5789
181
            }
5790
            // FIXME(gavin): if we want to continue scanning, the recycle_func should not return non-zero
5791
154k
            if (recycle_func(k, v) != 0) {
5792
4.00k
                err = "recycle_func error";
5793
4.00k
                ret = -1;
5794
4.00k
            }
5795
154k
        }
5796
181
        begin.push_back('\x00'); // Update to next smallest key for iteration
5797
        // FIXME(gavin): if we want to continue scanning, the loop_done should not return non-zero
5798
181
        if (loop_done && loop_done() != 0) {
5799
4
            err = "loop_done error";
5800
4
            ret = -1;
5801
4
        }
5802
181
    }
5803
268
    return ret;
5804
268
}
5805
5806
19
int InstanceRecycler::abort_timeout_txn() {
5807
19
    const std::string task_name = "abort_timeout_txn";
5808
19
    int64_t num_scanned = 0;
5809
19
    int64_t num_timeout = 0;
5810
19
    int64_t num_abort = 0;
5811
19
    int64_t num_advance = 0;
5812
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5813
5814
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
5815
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
5816
19
    std::string begin_txn_running_key;
5817
19
    std::string end_txn_running_key;
5818
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
5819
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
5820
5821
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
5822
5823
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5824
19
    register_recycle_task(task_name, start_time);
5825
5826
19
    DORIS_CLOUD_DEFER {
5827
19
        unregister_recycle_task(task_name);
5828
19
        int64_t cost =
5829
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5830
19
        metrics_context.finish_report();
5831
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
5832
19
                .tag("instance_id", instance_id_)
5833
19
                .tag("num_scanned", num_scanned)
5834
19
                .tag("num_timeout", num_timeout)
5835
19
                .tag("num_abort", num_abort)
5836
19
                .tag("num_advance", num_advance);
5837
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
5826
3
    DORIS_CLOUD_DEFER {
5827
3
        unregister_recycle_task(task_name);
5828
3
        int64_t cost =
5829
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5830
3
        metrics_context.finish_report();
5831
3
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
5832
3
                .tag("instance_id", instance_id_)
5833
3
                .tag("num_scanned", num_scanned)
5834
3
                .tag("num_timeout", num_timeout)
5835
3
                .tag("num_abort", num_abort)
5836
3
                .tag("num_advance", num_advance);
5837
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
5826
16
    DORIS_CLOUD_DEFER {
5827
16
        unregister_recycle_task(task_name);
5828
16
        int64_t cost =
5829
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5830
16
        metrics_context.finish_report();
5831
16
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
5832
16
                .tag("instance_id", instance_id_)
5833
16
                .tag("num_scanned", num_scanned)
5834
16
                .tag("num_timeout", num_timeout)
5835
16
                .tag("num_abort", num_abort)
5836
16
                .tag("num_advance", num_advance);
5837
16
    };
5838
5839
19
    int64_t current_time =
5840
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
5841
5842
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
5843
19
                                  &current_time, &metrics_context,
5844
19
                                  this](std::string_view k, std::string_view v) -> int {
5845
9
        ++num_scanned;
5846
5847
9
        std::unique_ptr<Transaction> txn;
5848
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5849
9
        if (err != TxnErrorCode::TXN_OK) {
5850
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
5851
0
            return -1;
5852
0
        }
5853
9
        std::string_view k1 = k;
5854
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
5855
9
        k1.remove_prefix(1); // Remove key space
5856
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5857
9
        if (decode_key(&k1, &out) != 0) {
5858
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
5859
0
            return -1;
5860
0
        }
5861
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
5862
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
5863
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
5864
        // Update txn_info
5865
9
        std::string txn_inf_key, txn_inf_val;
5866
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
5867
9
        err = txn->get(txn_inf_key, &txn_inf_val);
5868
9
        if (err != TxnErrorCode::TXN_OK) {
5869
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
5870
0
            return -1;
5871
0
        }
5872
9
        TxnInfoPB txn_info;
5873
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
5874
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
5875
0
            return -1;
5876
0
        }
5877
5878
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
5879
3
            txn.reset();
5880
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
5881
3
            std::shared_ptr<TxnLazyCommitTask> task =
5882
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
5883
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
5884
3
            if (ret.first != MetaServiceCode::OK) {
5885
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
5886
0
                             << "msg=" << ret.second;
5887
0
                return -1;
5888
0
            }
5889
3
            ++num_advance;
5890
3
            return 0;
5891
6
        } else {
5892
6
            TxnRunningPB txn_running_pb;
5893
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
5894
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
5895
0
                return -1;
5896
0
            }
5897
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
5898
4
                return 0;
5899
4
            }
5900
2
            ++num_timeout;
5901
5902
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
5903
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
5904
2
            txn_info.set_finish_time(current_time);
5905
2
            txn_info.set_reason("timeout");
5906
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
5907
2
            txn_inf_val.clear();
5908
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
5909
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
5910
0
                return -1;
5911
0
            }
5912
2
            txn->put(txn_inf_key, txn_inf_val);
5913
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
5914
            // Put recycle txn key
5915
2
            std::string recyc_txn_key, recyc_txn_val;
5916
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
5917
2
            RecycleTxnPB recycle_txn_pb;
5918
2
            recycle_txn_pb.set_creation_time(current_time);
5919
2
            recycle_txn_pb.set_label(txn_info.label());
5920
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
5921
0
                LOG_WARNING("failed to serialize txn recycle info")
5922
0
                        .tag("key", hex(k))
5923
0
                        .tag("db_id", db_id)
5924
0
                        .tag("txn_id", txn_id);
5925
0
                return -1;
5926
0
            }
5927
2
            txn->put(recyc_txn_key, recyc_txn_val);
5928
            // Remove txn running key
5929
2
            txn->remove(k);
5930
2
            err = txn->commit();
5931
2
            if (err != TxnErrorCode::TXN_OK) {
5932
0
                LOG_WARNING("failed to commit txn err={}", err)
5933
0
                        .tag("key", hex(k))
5934
0
                        .tag("db_id", db_id)
5935
0
                        .tag("txn_id", txn_id);
5936
0
                return -1;
5937
0
            }
5938
2
            metrics_context.total_recycled_num = ++num_abort;
5939
2
            metrics_context.report();
5940
2
        }
5941
5942
2
        return 0;
5943
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5844
3
                                  this](std::string_view k, std::string_view v) -> int {
5845
3
        ++num_scanned;
5846
5847
3
        std::unique_ptr<Transaction> txn;
5848
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5849
3
        if (err != TxnErrorCode::TXN_OK) {
5850
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
5851
0
            return -1;
5852
0
        }
5853
3
        std::string_view k1 = k;
5854
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
5855
3
        k1.remove_prefix(1); // Remove key space
5856
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5857
3
        if (decode_key(&k1, &out) != 0) {
5858
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
5859
0
            return -1;
5860
0
        }
5861
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
5862
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
5863
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
5864
        // Update txn_info
5865
3
        std::string txn_inf_key, txn_inf_val;
5866
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
5867
3
        err = txn->get(txn_inf_key, &txn_inf_val);
5868
3
        if (err != TxnErrorCode::TXN_OK) {
5869
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
5870
0
            return -1;
5871
0
        }
5872
3
        TxnInfoPB txn_info;
5873
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
5874
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
5875
0
            return -1;
5876
0
        }
5877
5878
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
5879
3
            txn.reset();
5880
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
5881
3
            std::shared_ptr<TxnLazyCommitTask> task =
5882
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
5883
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
5884
3
            if (ret.first != MetaServiceCode::OK) {
5885
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
5886
0
                             << "msg=" << ret.second;
5887
0
                return -1;
5888
0
            }
5889
3
            ++num_advance;
5890
3
            return 0;
5891
3
        } else {
5892
0
            TxnRunningPB txn_running_pb;
5893
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
5894
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
5895
0
                return -1;
5896
0
            }
5897
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
5898
0
                return 0;
5899
0
            }
5900
0
            ++num_timeout;
5901
5902
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
5903
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
5904
0
            txn_info.set_finish_time(current_time);
5905
0
            txn_info.set_reason("timeout");
5906
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
5907
0
            txn_inf_val.clear();
5908
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
5909
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
5910
0
                return -1;
5911
0
            }
5912
0
            txn->put(txn_inf_key, txn_inf_val);
5913
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
5914
            // Put recycle txn key
5915
0
            std::string recyc_txn_key, recyc_txn_val;
5916
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
5917
0
            RecycleTxnPB recycle_txn_pb;
5918
0
            recycle_txn_pb.set_creation_time(current_time);
5919
0
            recycle_txn_pb.set_label(txn_info.label());
5920
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
5921
0
                LOG_WARNING("failed to serialize txn recycle info")
5922
0
                        .tag("key", hex(k))
5923
0
                        .tag("db_id", db_id)
5924
0
                        .tag("txn_id", txn_id);
5925
0
                return -1;
5926
0
            }
5927
0
            txn->put(recyc_txn_key, recyc_txn_val);
5928
            // Remove txn running key
5929
0
            txn->remove(k);
5930
0
            err = txn->commit();
5931
0
            if (err != TxnErrorCode::TXN_OK) {
5932
0
                LOG_WARNING("failed to commit txn err={}", err)
5933
0
                        .tag("key", hex(k))
5934
0
                        .tag("db_id", db_id)
5935
0
                        .tag("txn_id", txn_id);
5936
0
                return -1;
5937
0
            }
5938
0
            metrics_context.total_recycled_num = ++num_abort;
5939
0
            metrics_context.report();
5940
0
        }
5941
5942
0
        return 0;
5943
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5844
6
                                  this](std::string_view k, std::string_view v) -> int {
5845
6
        ++num_scanned;
5846
5847
6
        std::unique_ptr<Transaction> txn;
5848
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5849
6
        if (err != TxnErrorCode::TXN_OK) {
5850
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
5851
0
            return -1;
5852
0
        }
5853
6
        std::string_view k1 = k;
5854
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
5855
6
        k1.remove_prefix(1); // Remove key space
5856
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5857
6
        if (decode_key(&k1, &out) != 0) {
5858
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
5859
0
            return -1;
5860
0
        }
5861
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
5862
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
5863
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
5864
        // Update txn_info
5865
6
        std::string txn_inf_key, txn_inf_val;
5866
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
5867
6
        err = txn->get(txn_inf_key, &txn_inf_val);
5868
6
        if (err != TxnErrorCode::TXN_OK) {
5869
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
5870
0
            return -1;
5871
0
        }
5872
6
        TxnInfoPB txn_info;
5873
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
5874
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
5875
0
            return -1;
5876
0
        }
5877
5878
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
5879
0
            txn.reset();
5880
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
5881
0
            std::shared_ptr<TxnLazyCommitTask> task =
5882
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
5883
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
5884
0
            if (ret.first != MetaServiceCode::OK) {
5885
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
5886
0
                             << "msg=" << ret.second;
5887
0
                return -1;
5888
0
            }
5889
0
            ++num_advance;
5890
0
            return 0;
5891
6
        } else {
5892
6
            TxnRunningPB txn_running_pb;
5893
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
5894
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
5895
0
                return -1;
5896
0
            }
5897
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
5898
4
                return 0;
5899
4
            }
5900
2
            ++num_timeout;
5901
5902
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
5903
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
5904
2
            txn_info.set_finish_time(current_time);
5905
2
            txn_info.set_reason("timeout");
5906
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
5907
2
            txn_inf_val.clear();
5908
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
5909
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
5910
0
                return -1;
5911
0
            }
5912
2
            txn->put(txn_inf_key, txn_inf_val);
5913
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
5914
            // Put recycle txn key
5915
2
            std::string recyc_txn_key, recyc_txn_val;
5916
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
5917
2
            RecycleTxnPB recycle_txn_pb;
5918
2
            recycle_txn_pb.set_creation_time(current_time);
5919
2
            recycle_txn_pb.set_label(txn_info.label());
5920
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
5921
0
                LOG_WARNING("failed to serialize txn recycle info")
5922
0
                        .tag("key", hex(k))
5923
0
                        .tag("db_id", db_id)
5924
0
                        .tag("txn_id", txn_id);
5925
0
                return -1;
5926
0
            }
5927
2
            txn->put(recyc_txn_key, recyc_txn_val);
5928
            // Remove txn running key
5929
2
            txn->remove(k);
5930
2
            err = txn->commit();
5931
2
            if (err != TxnErrorCode::TXN_OK) {
5932
0
                LOG_WARNING("failed to commit txn err={}", err)
5933
0
                        .tag("key", hex(k))
5934
0
                        .tag("db_id", db_id)
5935
0
                        .tag("txn_id", txn_id);
5936
0
                return -1;
5937
0
            }
5938
2
            metrics_context.total_recycled_num = ++num_abort;
5939
2
            metrics_context.report();
5940
2
        }
5941
5942
2
        return 0;
5943
6
    };
5944
5945
19
    if (config::enable_recycler_stats_metrics) {
5946
0
        scan_and_statistics_abort_timeout_txn();
5947
0
    }
5948
    // recycle_func and loop_done for scan and recycle
5949
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
5950
19
                            std::move(handle_txn_running_kv));
5951
19
}
5952
5953
19
int InstanceRecycler::recycle_expired_txn_label() {
5954
19
    const std::string task_name = "recycle_expired_txn_label";
5955
19
    int64_t num_scanned = 0;
5956
19
    int64_t num_expired = 0;
5957
19
    std::atomic_long num_recycled = 0;
5958
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5959
19
    int ret = 0;
5960
5961
19
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
5962
19
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
5963
19
    std::string begin_recycle_txn_key;
5964
19
    std::string end_recycle_txn_key;
5965
19
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
5966
19
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
5967
19
    std::vector<std::string> recycle_txn_info_keys;
5968
5969
19
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
5970
5971
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5972
19
    register_recycle_task(task_name, start_time);
5973
19
    DORIS_CLOUD_DEFER {
5974
19
        unregister_recycle_task(task_name);
5975
19
        int64_t cost =
5976
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5977
19
        metrics_context.finish_report();
5978
19
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
5979
19
                .tag("instance_id", instance_id_)
5980
19
                .tag("num_scanned", num_scanned)
5981
19
                .tag("num_expired", num_expired)
5982
19
                .tag("num_recycled", num_recycled);
5983
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
5973
1
    DORIS_CLOUD_DEFER {
5974
1
        unregister_recycle_task(task_name);
5975
1
        int64_t cost =
5976
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5977
1
        metrics_context.finish_report();
5978
1
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
5979
1
                .tag("instance_id", instance_id_)
5980
1
                .tag("num_scanned", num_scanned)
5981
1
                .tag("num_expired", num_expired)
5982
1
                .tag("num_recycled", num_recycled);
5983
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
5973
18
    DORIS_CLOUD_DEFER {
5974
18
        unregister_recycle_task(task_name);
5975
18
        int64_t cost =
5976
18
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5977
18
        metrics_context.finish_report();
5978
18
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
5979
18
                .tag("instance_id", instance_id_)
5980
18
                .tag("num_scanned", num_scanned)
5981
18
                .tag("num_expired", num_expired)
5982
18
                .tag("num_recycled", num_recycled);
5983
18
    };
5984
5985
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5986
5987
19
    SyncExecutor<int> concurrent_delete_executor(
5988
19
            _thread_pool_group.s3_producer_pool,
5989
19
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
5990
23.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
5990
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
5990
23.0k
            [](const int& ret) { return ret != 0; });
5991
5992
19
    int64_t current_time_ms =
5993
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
5994
5995
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
5996
30.0k
        ++num_scanned;
5997
30.0k
        RecycleTxnPB recycle_txn_pb;
5998
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
5999
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6000
0
            return -1;
6001
0
        }
6002
30.0k
        if ((config::force_immediate_recycle) ||
6003
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6004
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6005
30.0k
             current_time_ms)) {
6006
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6007
23.0k
            num_expired++;
6008
23.0k
            recycle_txn_info_keys.emplace_back(k);
6009
23.0k
        }
6010
30.0k
        return 0;
6011
30.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5995
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
5996
1
        ++num_scanned;
5997
1
        RecycleTxnPB recycle_txn_pb;
5998
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
5999
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6000
0
            return -1;
6001
0
        }
6002
1
        if ((config::force_immediate_recycle) ||
6003
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6004
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6005
1
             current_time_ms)) {
6006
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6007
1
            num_expired++;
6008
1
            recycle_txn_info_keys.emplace_back(k);
6009
1
        }
6010
1
        return 0;
6011
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5995
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
5996
30.0k
        ++num_scanned;
5997
30.0k
        RecycleTxnPB recycle_txn_pb;
5998
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
5999
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6000
0
            return -1;
6001
0
        }
6002
30.0k
        if ((config::force_immediate_recycle) ||
6003
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6004
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6005
30.0k
             current_time_ms)) {
6006
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6007
23.0k
            num_expired++;
6008
23.0k
            recycle_txn_info_keys.emplace_back(k);
6009
23.0k
        }
6010
30.0k
        return 0;
6011
30.0k
    };
6012
6013
    // int 0 for success, 1 for conflict, -1 for error
6014
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6015
23.0k
        std::string_view k1 = k;
6016
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6017
23.0k
        k1.remove_prefix(1); // Remove key space
6018
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6019
23.0k
        int ret = decode_key(&k1, &out);
6020
23.0k
        if (ret != 0) {
6021
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6022
0
            return -1;
6023
0
        }
6024
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6025
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6026
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6027
23.0k
        std::unique_ptr<Transaction> txn;
6028
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6029
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6030
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6031
0
            return -1;
6032
0
        }
6033
        // Remove txn index kv
6034
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6035
23.0k
        txn->remove(index_key);
6036
        // Remove txn info kv
6037
23.0k
        std::string info_key, info_val;
6038
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6039
23.0k
        err = txn->get(info_key, &info_val);
6040
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6041
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6042
0
            return -1;
6043
0
        }
6044
23.0k
        TxnInfoPB txn_info;
6045
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6046
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6047
0
            return -1;
6048
0
        }
6049
23.0k
        txn->remove(info_key);
6050
        // Remove sub txn index kvs
6051
23.0k
        std::vector<std::string> sub_txn_index_keys;
6052
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6053
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6054
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6055
22.9k
        }
6056
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6057
22.9k
            txn->remove(sub_txn_index_key);
6058
22.9k
        }
6059
        // Update txn label
6060
23.0k
        std::string label_key, label_val;
6061
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6062
23.0k
        err = txn->get(label_key, &label_val);
6063
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6064
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6065
0
                         << " err=" << err;
6066
0
            return -1;
6067
0
        }
6068
23.0k
        TxnLabelPB txn_label;
6069
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6070
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6071
0
            return -1;
6072
0
        }
6073
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6074
23.0k
        if (it != txn_label.txn_ids().end()) {
6075
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6076
23.0k
        }
6077
23.0k
        if (txn_label.txn_ids().empty()) {
6078
23.0k
            txn->remove(label_key);
6079
23.0k
            TEST_SYNC_POINT_CALLBACK(
6080
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6081
23.0k
        } else {
6082
73
            if (!txn_label.SerializeToString(&label_val)) {
6083
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6084
0
                return -1;
6085
0
            }
6086
73
            TEST_SYNC_POINT_CALLBACK(
6087
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6088
73
            txn->atomic_set_ver_value(label_key, label_val);
6089
73
            TEST_SYNC_POINT_CALLBACK(
6090
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6091
73
        }
6092
        // Remove recycle txn kv
6093
23.0k
        txn->remove(k);
6094
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6095
23.0k
        err = txn->commit();
6096
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6097
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6098
62
                TEST_SYNC_POINT_CALLBACK(
6099
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6100
                // log the txn_id and label
6101
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6102
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6103
62
                             << " txn_label=" << txn_info.label();
6104
62
                return 1;
6105
62
            }
6106
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6107
0
            return -1;
6108
62
        }
6109
23.0k
        ++num_recycled;
6110
6111
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6112
23.0k
        return 0;
6113
23.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6014
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6015
1
        std::string_view k1 = k;
6016
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6017
1
        k1.remove_prefix(1); // Remove key space
6018
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6019
1
        int ret = decode_key(&k1, &out);
6020
1
        if (ret != 0) {
6021
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6022
0
            return -1;
6023
0
        }
6024
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6025
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6026
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6027
1
        std::unique_ptr<Transaction> txn;
6028
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6029
1
        if (err != TxnErrorCode::TXN_OK) {
6030
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6031
0
            return -1;
6032
0
        }
6033
        // Remove txn index kv
6034
1
        auto index_key = txn_index_key({instance_id_, txn_id});
6035
1
        txn->remove(index_key);
6036
        // Remove txn info kv
6037
1
        std::string info_key, info_val;
6038
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6039
1
        err = txn->get(info_key, &info_val);
6040
1
        if (err != TxnErrorCode::TXN_OK) {
6041
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6042
0
            return -1;
6043
0
        }
6044
1
        TxnInfoPB txn_info;
6045
1
        if (!txn_info.ParseFromString(info_val)) {
6046
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6047
0
            return -1;
6048
0
        }
6049
1
        txn->remove(info_key);
6050
        // Remove sub txn index kvs
6051
1
        std::vector<std::string> sub_txn_index_keys;
6052
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6053
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6054
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
6055
0
        }
6056
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6057
0
            txn->remove(sub_txn_index_key);
6058
0
        }
6059
        // Update txn label
6060
1
        std::string label_key, label_val;
6061
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6062
1
        err = txn->get(label_key, &label_val);
6063
1
        if (err != TxnErrorCode::TXN_OK) {
6064
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6065
0
                         << " err=" << err;
6066
0
            return -1;
6067
0
        }
6068
1
        TxnLabelPB txn_label;
6069
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6070
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6071
0
            return -1;
6072
0
        }
6073
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6074
1
        if (it != txn_label.txn_ids().end()) {
6075
1
            txn_label.mutable_txn_ids()->erase(it);
6076
1
        }
6077
1
        if (txn_label.txn_ids().empty()) {
6078
1
            txn->remove(label_key);
6079
1
            TEST_SYNC_POINT_CALLBACK(
6080
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6081
1
        } else {
6082
0
            if (!txn_label.SerializeToString(&label_val)) {
6083
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6084
0
                return -1;
6085
0
            }
6086
0
            TEST_SYNC_POINT_CALLBACK(
6087
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6088
0
            txn->atomic_set_ver_value(label_key, label_val);
6089
0
            TEST_SYNC_POINT_CALLBACK(
6090
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6091
0
        }
6092
        // Remove recycle txn kv
6093
1
        txn->remove(k);
6094
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6095
1
        err = txn->commit();
6096
1
        if (err != TxnErrorCode::TXN_OK) {
6097
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
6098
0
                TEST_SYNC_POINT_CALLBACK(
6099
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6100
                // log the txn_id and label
6101
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6102
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6103
0
                             << " txn_label=" << txn_info.label();
6104
0
                return 1;
6105
0
            }
6106
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6107
0
            return -1;
6108
0
        }
6109
1
        ++num_recycled;
6110
6111
1
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6112
1
        return 0;
6113
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6014
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6015
23.0k
        std::string_view k1 = k;
6016
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6017
23.0k
        k1.remove_prefix(1); // Remove key space
6018
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6019
23.0k
        int ret = decode_key(&k1, &out);
6020
23.0k
        if (ret != 0) {
6021
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6022
0
            return -1;
6023
0
        }
6024
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6025
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6026
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6027
23.0k
        std::unique_ptr<Transaction> txn;
6028
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6029
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6030
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6031
0
            return -1;
6032
0
        }
6033
        // Remove txn index kv
6034
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6035
23.0k
        txn->remove(index_key);
6036
        // Remove txn info kv
6037
23.0k
        std::string info_key, info_val;
6038
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6039
23.0k
        err = txn->get(info_key, &info_val);
6040
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6041
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6042
0
            return -1;
6043
0
        }
6044
23.0k
        TxnInfoPB txn_info;
6045
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6046
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6047
0
            return -1;
6048
0
        }
6049
23.0k
        txn->remove(info_key);
6050
        // Remove sub txn index kvs
6051
23.0k
        std::vector<std::string> sub_txn_index_keys;
6052
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6053
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6054
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6055
22.9k
        }
6056
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6057
22.9k
            txn->remove(sub_txn_index_key);
6058
22.9k
        }
6059
        // Update txn label
6060
23.0k
        std::string label_key, label_val;
6061
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6062
23.0k
        err = txn->get(label_key, &label_val);
6063
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6064
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6065
0
                         << " err=" << err;
6066
0
            return -1;
6067
0
        }
6068
23.0k
        TxnLabelPB txn_label;
6069
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6070
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6071
0
            return -1;
6072
0
        }
6073
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6074
23.0k
        if (it != txn_label.txn_ids().end()) {
6075
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6076
23.0k
        }
6077
23.0k
        if (txn_label.txn_ids().empty()) {
6078
23.0k
            txn->remove(label_key);
6079
23.0k
            TEST_SYNC_POINT_CALLBACK(
6080
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6081
23.0k
        } else {
6082
73
            if (!txn_label.SerializeToString(&label_val)) {
6083
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6084
0
                return -1;
6085
0
            }
6086
73
            TEST_SYNC_POINT_CALLBACK(
6087
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6088
73
            txn->atomic_set_ver_value(label_key, label_val);
6089
73
            TEST_SYNC_POINT_CALLBACK(
6090
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6091
73
        }
6092
        // Remove recycle txn kv
6093
23.0k
        txn->remove(k);
6094
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6095
23.0k
        err = txn->commit();
6096
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6097
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6098
62
                TEST_SYNC_POINT_CALLBACK(
6099
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6100
                // log the txn_id and label
6101
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6102
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6103
62
                             << " txn_label=" << txn_info.label();
6104
62
                return 1;
6105
62
            }
6106
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6107
0
            return -1;
6108
62
        }
6109
23.0k
        ++num_recycled;
6110
6111
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6112
23.0k
        return 0;
6113
23.0k
    };
6114
6115
19
    auto loop_done = [&]() -> int {
6116
10
        DORIS_CLOUD_DEFER {
6117
10
            recycle_txn_info_keys.clear();
6118
10
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6116
1
        DORIS_CLOUD_DEFER {
6117
1
            recycle_txn_info_keys.clear();
6118
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6116
9
        DORIS_CLOUD_DEFER {
6117
9
            recycle_txn_info_keys.clear();
6118
9
        };
6119
10
        TEST_SYNC_POINT_CALLBACK(
6120
10
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6121
10
                &recycle_txn_info_keys);
6122
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6123
23.0k
            concurrent_delete_executor.add([&]() {
6124
23.0k
                int ret = delete_recycle_txn_kv(k);
6125
23.0k
                if (ret == 1) {
6126
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6127
54
                    for (int i = 1; i <= max_retry; ++i) {
6128
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6129
54
                        ret = delete_recycle_txn_kv(k);
6130
                        // clang-format off
6131
54
                        TEST_SYNC_POINT_CALLBACK(
6132
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6133
                        // clang-format off
6134
54
                        if (ret != 1) {
6135
18
                            break;
6136
18
                        }
6137
                        // random sleep 0-100 ms to retry
6138
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6139
36
                    }
6140
18
                }
6141
23.0k
                if (ret != 0) {
6142
9
                    LOG_WARNING("failed to delete recycle txn kv")
6143
9
                            .tag("instance id", instance_id_)
6144
9
                            .tag("key", hex(k));
6145
9
                    return -1;
6146
9
                }
6147
23.0k
                return 0;
6148
23.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6123
1
            concurrent_delete_executor.add([&]() {
6124
1
                int ret = delete_recycle_txn_kv(k);
6125
1
                if (ret == 1) {
6126
0
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6127
0
                    for (int i = 1; i <= max_retry; ++i) {
6128
0
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6129
0
                        ret = delete_recycle_txn_kv(k);
6130
                        // clang-format off
6131
0
                        TEST_SYNC_POINT_CALLBACK(
6132
0
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6133
                        // clang-format off
6134
0
                        if (ret != 1) {
6135
0
                            break;
6136
0
                        }
6137
                        // random sleep 0-100 ms to retry
6138
0
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6139
0
                    }
6140
0
                }
6141
1
                if (ret != 0) {
6142
0
                    LOG_WARNING("failed to delete recycle txn kv")
6143
0
                            .tag("instance id", instance_id_)
6144
0
                            .tag("key", hex(k));
6145
0
                    return -1;
6146
0
                }
6147
1
                return 0;
6148
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6123
23.0k
            concurrent_delete_executor.add([&]() {
6124
23.0k
                int ret = delete_recycle_txn_kv(k);
6125
23.0k
                if (ret == 1) {
6126
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6127
54
                    for (int i = 1; i <= max_retry; ++i) {
6128
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6129
54
                        ret = delete_recycle_txn_kv(k);
6130
                        // clang-format off
6131
54
                        TEST_SYNC_POINT_CALLBACK(
6132
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6133
                        // clang-format off
6134
54
                        if (ret != 1) {
6135
18
                            break;
6136
18
                        }
6137
                        // random sleep 0-100 ms to retry
6138
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6139
36
                    }
6140
18
                }
6141
23.0k
                if (ret != 0) {
6142
9
                    LOG_WARNING("failed to delete recycle txn kv")
6143
9
                            .tag("instance id", instance_id_)
6144
9
                            .tag("key", hex(k));
6145
9
                    return -1;
6146
9
                }
6147
23.0k
                return 0;
6148
23.0k
            });
6149
23.0k
        }
6150
10
        bool finished = true;
6151
10
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6152
23.0k
        for (int r : rets) {
6153
23.0k
            if (r != 0) {
6154
9
                ret = -1;
6155
9
            }
6156
23.0k
        }
6157
6158
10
        ret = finished ? ret : -1;
6159
6160
        // Update metrics after all concurrent tasks completed
6161
10
        metrics_context.total_recycled_num = num_recycled.load();
6162
10
        metrics_context.report();
6163
6164
10
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6165
6166
10
        if (ret != 0) {
6167
3
            LOG_WARNING("recycle txn kv ret!=0")
6168
3
                    .tag("finished", finished)
6169
3
                    .tag("ret", ret)
6170
3
                    .tag("instance_id", instance_id_);
6171
3
            return ret;
6172
3
        }
6173
7
        return ret;
6174
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6115
1
    auto loop_done = [&]() -> int {
6116
1
        DORIS_CLOUD_DEFER {
6117
1
            recycle_txn_info_keys.clear();
6118
1
        };
6119
1
        TEST_SYNC_POINT_CALLBACK(
6120
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6121
1
                &recycle_txn_info_keys);
6122
1
        for (const auto& k : recycle_txn_info_keys) {
6123
1
            concurrent_delete_executor.add([&]() {
6124
1
                int ret = delete_recycle_txn_kv(k);
6125
1
                if (ret == 1) {
6126
1
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6127
1
                    for (int i = 1; i <= max_retry; ++i) {
6128
1
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6129
1
                        ret = delete_recycle_txn_kv(k);
6130
                        // clang-format off
6131
1
                        TEST_SYNC_POINT_CALLBACK(
6132
1
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6133
                        // clang-format off
6134
1
                        if (ret != 1) {
6135
1
                            break;
6136
1
                        }
6137
                        // random sleep 0-100 ms to retry
6138
1
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6139
1
                    }
6140
1
                }
6141
1
                if (ret != 0) {
6142
1
                    LOG_WARNING("failed to delete recycle txn kv")
6143
1
                            .tag("instance id", instance_id_)
6144
1
                            .tag("key", hex(k));
6145
1
                    return -1;
6146
1
                }
6147
1
                return 0;
6148
1
            });
6149
1
        }
6150
1
        bool finished = true;
6151
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6152
1
        for (int r : rets) {
6153
1
            if (r != 0) {
6154
0
                ret = -1;
6155
0
            }
6156
1
        }
6157
6158
1
        ret = finished ? ret : -1;
6159
6160
        // Update metrics after all concurrent tasks completed
6161
1
        metrics_context.total_recycled_num = num_recycled.load();
6162
1
        metrics_context.report();
6163
6164
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6165
6166
1
        if (ret != 0) {
6167
0
            LOG_WARNING("recycle txn kv ret!=0")
6168
0
                    .tag("finished", finished)
6169
0
                    .tag("ret", ret)
6170
0
                    .tag("instance_id", instance_id_);
6171
0
            return ret;
6172
0
        }
6173
1
        return ret;
6174
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6115
9
    auto loop_done = [&]() -> int {
6116
9
        DORIS_CLOUD_DEFER {
6117
9
            recycle_txn_info_keys.clear();
6118
9
        };
6119
9
        TEST_SYNC_POINT_CALLBACK(
6120
9
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6121
9
                &recycle_txn_info_keys);
6122
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6123
23.0k
            concurrent_delete_executor.add([&]() {
6124
23.0k
                int ret = delete_recycle_txn_kv(k);
6125
23.0k
                if (ret == 1) {
6126
23.0k
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6127
23.0k
                    for (int i = 1; i <= max_retry; ++i) {
6128
23.0k
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6129
23.0k
                        ret = delete_recycle_txn_kv(k);
6130
                        // clang-format off
6131
23.0k
                        TEST_SYNC_POINT_CALLBACK(
6132
23.0k
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6133
                        // clang-format off
6134
23.0k
                        if (ret != 1) {
6135
23.0k
                            break;
6136
23.0k
                        }
6137
                        // random sleep 0-100 ms to retry
6138
23.0k
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6139
23.0k
                    }
6140
23.0k
                }
6141
23.0k
                if (ret != 0) {
6142
23.0k
                    LOG_WARNING("failed to delete recycle txn kv")
6143
23.0k
                            .tag("instance id", instance_id_)
6144
23.0k
                            .tag("key", hex(k));
6145
23.0k
                    return -1;
6146
23.0k
                }
6147
23.0k
                return 0;
6148
23.0k
            });
6149
23.0k
        }
6150
9
        bool finished = true;
6151
9
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6152
23.0k
        for (int r : rets) {
6153
23.0k
            if (r != 0) {
6154
9
                ret = -1;
6155
9
            }
6156
23.0k
        }
6157
6158
9
        ret = finished ? ret : -1;
6159
6160
        // Update metrics after all concurrent tasks completed
6161
9
        metrics_context.total_recycled_num = num_recycled.load();
6162
9
        metrics_context.report();
6163
6164
9
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6165
6166
9
        if (ret != 0) {
6167
3
            LOG_WARNING("recycle txn kv ret!=0")
6168
3
                    .tag("finished", finished)
6169
3
                    .tag("ret", ret)
6170
3
                    .tag("instance_id", instance_id_);
6171
3
            return ret;
6172
3
        }
6173
6
        return ret;
6174
9
    };
6175
6176
19
    if (config::enable_recycler_stats_metrics) {
6177
0
        scan_and_statistics_expired_txn_label();
6178
0
    }
6179
    // recycle_func and loop_done for scan and recycle
6180
19
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
6181
19
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
6182
19
}
6183
6184
struct CopyJobIdTuple {
6185
    std::string instance_id;
6186
    std::string stage_id;
6187
    long table_id;
6188
    std::string copy_id;
6189
    std::string stage_path;
6190
};
6191
struct BatchObjStoreAccessor {
6192
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
6193
                          TxnKv* txn_kv)
6194
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
6195
3
    ~BatchObjStoreAccessor() {
6196
3
        if (!paths_.empty()) {
6197
3
            consume();
6198
3
        }
6199
3
    }
6200
6201
    /**
6202
    * To implicitely do batch work and submit the batch delete task to s3
6203
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
6204
    *
6205
    * @param copy_job The protubuf struct consists of the copy job files.
6206
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
6207
    *            it would last until we finish the delete task, here we need pass one string value
6208
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
6209
    */
6210
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
6211
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
6212
5
        auto& file_keys = copy_file_keys_[key];
6213
5
        file_keys.log_trace =
6214
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
6215
5
                            instance_id, stage_id, table_id, copy_id, path);
6216
5
        std::string_view log_trace = file_keys.log_trace;
6217
2.03k
        for (const auto& file : copy_job.object_files()) {
6218
2.03k
            auto relative_path = file.relative_path();
6219
2.03k
            paths_.push_back(relative_path);
6220
2.03k
            file_keys.keys.push_back(copy_file_key(
6221
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
6222
2.03k
            LOG_INFO(log_trace)
6223
2.03k
                    .tag("relative_path", relative_path)
6224
2.03k
                    .tag("batch_count", batch_count_);
6225
2.03k
        }
6226
5
        LOG_INFO(log_trace)
6227
5
                .tag("objects_num", copy_job.object_files().size())
6228
5
                .tag("batch_count", batch_count_);
6229
        // 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
6230
        // recommend using delete objects when objects num is less than 10)
6231
5
        if (paths_.size() < 1000) {
6232
3
            return;
6233
3
        }
6234
2
        consume();
6235
2
    }
6236
6237
private:
6238
5
    void consume() {
6239
5
        DORIS_CLOUD_DEFER {
6240
5
            paths_.clear();
6241
5
            copy_file_keys_.clear();
6242
5
            batch_count_++;
6243
6244
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
6245
5
                        batch_count_);
6246
5
        };
6247
6248
5
        StopWatch sw;
6249
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
6250
5
        if (0 != accessor_->delete_files(paths_)) {
6251
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
6252
2
                        paths_.size(), batch_count_, sw.elapsed_us());
6253
2
            return;
6254
2
        }
6255
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
6256
3
                    paths_.size(), batch_count_, sw.elapsed_us());
6257
        // delete fdb's keys
6258
3
        for (auto& file_keys : copy_file_keys_) {
6259
3
            auto& [log_trace, keys] = file_keys.second;
6260
3
            std::unique_ptr<Transaction> txn;
6261
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
6262
0
                LOG(WARNING) << "failed to create txn";
6263
0
                continue;
6264
0
            }
6265
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6266
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6267
            // limited, should not cause the txn commit failed.
6268
1.02k
            for (const auto& key : keys) {
6269
1.02k
                txn->remove(key);
6270
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
6271
1.02k
            }
6272
3
            txn->remove(file_keys.first);
6273
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
6274
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
6275
0
                continue;
6276
0
            }
6277
3
        }
6278
3
    }
6279
    std::shared_ptr<StorageVaultAccessor> accessor_;
6280
    // the path of the s3 files to be deleted
6281
    std::vector<std::string> paths_;
6282
    struct CopyFiles {
6283
        std::string log_trace;
6284
        std::vector<std::string> keys;
6285
    };
6286
    // pair<std::string, std::vector<std::string>>
6287
    // first: instance_id_ stage_id table_id query_id
6288
    // second: keys to be deleted
6289
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
6290
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
6291
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
6292
    // which can together uniquely identifies different tasks for tracing log
6293
    uint64_t& batch_count_;
6294
    TxnKv* txn_kv_;
6295
};
6296
6297
13
int InstanceRecycler::recycle_copy_jobs() {
6298
13
    int64_t num_scanned = 0;
6299
13
    int64_t num_finished = 0;
6300
13
    int64_t num_expired = 0;
6301
13
    int64_t num_recycled = 0;
6302
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
6303
13
    uint64_t batch_count = 0;
6304
13
    const std::string task_name = "recycle_copy_jobs";
6305
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6306
6307
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
6308
6309
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6310
13
    register_recycle_task(task_name, start_time);
6311
6312
13
    DORIS_CLOUD_DEFER {
6313
13
        unregister_recycle_task(task_name);
6314
13
        int64_t cost =
6315
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6316
13
        metrics_context.finish_report();
6317
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
6318
13
                .tag("instance_id", instance_id_)
6319
13
                .tag("num_scanned", num_scanned)
6320
13
                .tag("num_finished", num_finished)
6321
13
                .tag("num_expired", num_expired)
6322
13
                .tag("num_recycled", num_recycled);
6323
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
6312
13
    DORIS_CLOUD_DEFER {
6313
13
        unregister_recycle_task(task_name);
6314
13
        int64_t cost =
6315
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6316
13
        metrics_context.finish_report();
6317
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
6318
13
                .tag("instance_id", instance_id_)
6319
13
                .tag("num_scanned", num_scanned)
6320
13
                .tag("num_finished", num_finished)
6321
13
                .tag("num_expired", num_expired)
6322
13
                .tag("num_recycled", num_recycled);
6323
13
    };
6324
6325
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
6326
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
6327
13
    std::string key0;
6328
13
    std::string key1;
6329
13
    copy_job_key(key_info0, &key0);
6330
13
    copy_job_key(key_info1, &key1);
6331
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
6332
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
6333
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
6334
16
                         this](std::string_view k, std::string_view v) -> int {
6335
16
        ++num_scanned;
6336
16
        CopyJobPB copy_job;
6337
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
6338
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
6339
0
            return -1;
6340
0
        }
6341
6342
        // decode copy job key
6343
16
        auto k1 = k;
6344
16
        k1.remove_prefix(1);
6345
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6346
16
        decode_key(&k1, &out);
6347
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
6348
        // -> CopyJobPB
6349
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
6350
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
6351
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
6352
6353
16
        bool check_storage = true;
6354
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
6355
12
            ++num_finished;
6356
6357
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
6358
7
                auto it = stage_accessor_map.find(stage_id);
6359
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
6360
7
                std::string_view path;
6361
7
                if (it != stage_accessor_map.end()) {
6362
2
                    accessor = it->second;
6363
5
                } else {
6364
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
6365
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
6366
5
                                                      &inner_accessor);
6367
5
                    if (ret < 0) { // error
6368
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
6369
0
                        return -1;
6370
5
                    } else if (ret == 0) {
6371
3
                        path = inner_accessor->uri();
6372
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
6373
3
                                inner_accessor, batch_count, txn_kv_.get());
6374
3
                        stage_accessor_map.emplace(stage_id, accessor);
6375
3
                    } else { // stage not found, skip check storage
6376
2
                        check_storage = false;
6377
2
                    }
6378
5
                }
6379
7
                if (check_storage) {
6380
                    // TODO delete objects with key and etag is not supported
6381
5
                    accessor->add(std::move(copy_job), std::string(k),
6382
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
6383
5
                    return 0;
6384
5
                }
6385
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
6386
5
                int64_t current_time =
6387
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6388
5
                if (copy_job.finish_time_ms() > 0) {
6389
2
                    if (!config::force_immediate_recycle &&
6390
2
                        current_time < copy_job.finish_time_ms() +
6391
2
                                               config::copy_job_max_retention_second * 1000) {
6392
1
                        return 0;
6393
1
                    }
6394
3
                } else {
6395
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
6396
3
                    if (!config::force_immediate_recycle &&
6397
3
                        current_time < copy_job.start_time_ms() +
6398
3
                                               config::copy_job_max_retention_second * 1000) {
6399
1
                        return 0;
6400
1
                    }
6401
3
                }
6402
5
            }
6403
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
6404
4
            int64_t current_time =
6405
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6406
            // if copy job is timeout: delete all copy file kvs and copy job kv
6407
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
6408
2
                return 0;
6409
2
            }
6410
2
            ++num_expired;
6411
2
        }
6412
6413
        // delete all copy files
6414
7
        std::vector<std::string> copy_file_keys;
6415
70
        for (auto& file : copy_job.object_files()) {
6416
70
            copy_file_keys.push_back(copy_file_key(
6417
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
6418
70
        }
6419
7
        std::unique_ptr<Transaction> txn;
6420
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
6421
0
            LOG(WARNING) << "failed to create txn";
6422
0
            return -1;
6423
0
        }
6424
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6425
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6426
        // limited, should not cause the txn commit failed.
6427
70
        for (const auto& key : copy_file_keys) {
6428
70
            txn->remove(key);
6429
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
6430
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
6431
70
                      << ", query_id=" << copy_id;
6432
70
        }
6433
7
        txn->remove(k);
6434
7
        TxnErrorCode err = txn->commit();
6435
7
        if (err != TxnErrorCode::TXN_OK) {
6436
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
6437
0
            return -1;
6438
0
        }
6439
6440
7
        metrics_context.total_recycled_num = ++num_recycled;
6441
7
        metrics_context.report();
6442
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6443
7
        return 0;
6444
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
6334
16
                         this](std::string_view k, std::string_view v) -> int {
6335
16
        ++num_scanned;
6336
16
        CopyJobPB copy_job;
6337
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
6338
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
6339
0
            return -1;
6340
0
        }
6341
6342
        // decode copy job key
6343
16
        auto k1 = k;
6344
16
        k1.remove_prefix(1);
6345
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6346
16
        decode_key(&k1, &out);
6347
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
6348
        // -> CopyJobPB
6349
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
6350
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
6351
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
6352
6353
16
        bool check_storage = true;
6354
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
6355
12
            ++num_finished;
6356
6357
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
6358
7
                auto it = stage_accessor_map.find(stage_id);
6359
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
6360
7
                std::string_view path;
6361
7
                if (it != stage_accessor_map.end()) {
6362
2
                    accessor = it->second;
6363
5
                } else {
6364
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
6365
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
6366
5
                                                      &inner_accessor);
6367
5
                    if (ret < 0) { // error
6368
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
6369
0
                        return -1;
6370
5
                    } else if (ret == 0) {
6371
3
                        path = inner_accessor->uri();
6372
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
6373
3
                                inner_accessor, batch_count, txn_kv_.get());
6374
3
                        stage_accessor_map.emplace(stage_id, accessor);
6375
3
                    } else { // stage not found, skip check storage
6376
2
                        check_storage = false;
6377
2
                    }
6378
5
                }
6379
7
                if (check_storage) {
6380
                    // TODO delete objects with key and etag is not supported
6381
5
                    accessor->add(std::move(copy_job), std::string(k),
6382
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
6383
5
                    return 0;
6384
5
                }
6385
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
6386
5
                int64_t current_time =
6387
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6388
5
                if (copy_job.finish_time_ms() > 0) {
6389
2
                    if (!config::force_immediate_recycle &&
6390
2
                        current_time < copy_job.finish_time_ms() +
6391
2
                                               config::copy_job_max_retention_second * 1000) {
6392
1
                        return 0;
6393
1
                    }
6394
3
                } else {
6395
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
6396
3
                    if (!config::force_immediate_recycle &&
6397
3
                        current_time < copy_job.start_time_ms() +
6398
3
                                               config::copy_job_max_retention_second * 1000) {
6399
1
                        return 0;
6400
1
                    }
6401
3
                }
6402
5
            }
6403
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
6404
4
            int64_t current_time =
6405
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6406
            // if copy job is timeout: delete all copy file kvs and copy job kv
6407
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
6408
2
                return 0;
6409
2
            }
6410
2
            ++num_expired;
6411
2
        }
6412
6413
        // delete all copy files
6414
7
        std::vector<std::string> copy_file_keys;
6415
70
        for (auto& file : copy_job.object_files()) {
6416
70
            copy_file_keys.push_back(copy_file_key(
6417
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
6418
70
        }
6419
7
        std::unique_ptr<Transaction> txn;
6420
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
6421
0
            LOG(WARNING) << "failed to create txn";
6422
0
            return -1;
6423
0
        }
6424
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6425
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6426
        // limited, should not cause the txn commit failed.
6427
70
        for (const auto& key : copy_file_keys) {
6428
70
            txn->remove(key);
6429
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
6430
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
6431
70
                      << ", query_id=" << copy_id;
6432
70
        }
6433
7
        txn->remove(k);
6434
7
        TxnErrorCode err = txn->commit();
6435
7
        if (err != TxnErrorCode::TXN_OK) {
6436
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
6437
0
            return -1;
6438
0
        }
6439
6440
7
        metrics_context.total_recycled_num = ++num_recycled;
6441
7
        metrics_context.report();
6442
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6443
7
        return 0;
6444
7
    };
6445
6446
13
    if (config::enable_recycler_stats_metrics) {
6447
0
        scan_and_statistics_copy_jobs();
6448
0
    }
6449
    // recycle_func and loop_done for scan and recycle
6450
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
6451
13
}
6452
6453
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
6454
                                             const StagePB::StageType& stage_type,
6455
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
6456
5
#ifdef UNIT_TEST
6457
    // In unit test, external use the same accessor as the internal stage
6458
5
    auto it = accessor_map_.find(stage_id);
6459
5
    if (it != accessor_map_.end()) {
6460
3
        *accessor = it->second;
6461
3
    } else {
6462
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
6463
2
        return 1;
6464
2
    }
6465
#else
6466
    // init s3 accessor and add to accessor map
6467
    auto stage_it =
6468
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
6469
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
6470
6471
    if (stage_it == instance_info_.stages().end()) {
6472
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
6473
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
6474
        return 1;
6475
    }
6476
6477
    const auto& object_store_info = stage_it->obj_info();
6478
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
6479
6480
    S3Conf s3_conf;
6481
    if (stage_type == StagePB::EXTERNAL) {
6482
        if (stage_access_type == StagePB::AKSK) {
6483
            auto conf = S3Conf::from_obj_store_info(object_store_info);
6484
            if (!conf) {
6485
                return -1;
6486
            }
6487
6488
            s3_conf = std::move(*conf);
6489
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
6490
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
6491
            if (!conf) {
6492
                return -1;
6493
            }
6494
6495
            s3_conf = std::move(*conf);
6496
            if (instance_info_.ram_user().has_encryption_info()) {
6497
                AkSkPair plain_ak_sk_pair;
6498
                int ret = decrypt_ak_sk_helper(
6499
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
6500
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
6501
                if (ret != 0) {
6502
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
6503
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
6504
                    return -1;
6505
                }
6506
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
6507
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
6508
            } else {
6509
                s3_conf.ak = instance_info_.ram_user().ak();
6510
                s3_conf.sk = instance_info_.ram_user().sk();
6511
            }
6512
        } else {
6513
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
6514
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
6515
            return -1;
6516
        }
6517
    } else if (stage_type == StagePB::INTERNAL) {
6518
        int idx = stoi(object_store_info.id());
6519
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6520
            LOG(WARNING) << "invalid idx: " << idx;
6521
            return -1;
6522
        }
6523
6524
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
6525
        auto conf = S3Conf::from_obj_store_info(old_obj);
6526
        if (!conf) {
6527
            return -1;
6528
        }
6529
6530
        s3_conf = std::move(*conf);
6531
        s3_conf.prefix = object_store_info.prefix();
6532
    } else {
6533
        LOG(WARNING) << "unknown stage type " << stage_type;
6534
        return -1;
6535
    }
6536
6537
    std::shared_ptr<S3Accessor> s3_accessor;
6538
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
6539
    if (ret != 0) {
6540
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
6541
        return -1;
6542
    }
6543
6544
    *accessor = std::move(s3_accessor);
6545
#endif
6546
3
    return 0;
6547
5
}
6548
6549
11
int InstanceRecycler::recycle_stage() {
6550
11
    int64_t num_scanned = 0;
6551
11
    int64_t num_recycled = 0;
6552
11
    const std::string task_name = "recycle_stage";
6553
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6554
6555
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
6556
6557
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6558
11
    register_recycle_task(task_name, start_time);
6559
6560
11
    DORIS_CLOUD_DEFER {
6561
11
        unregister_recycle_task(task_name);
6562
11
        int64_t cost =
6563
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6564
11
        metrics_context.finish_report();
6565
11
        LOG_WARNING("recycle stage, cost={}s", cost)
6566
11
                .tag("instance_id", instance_id_)
6567
11
                .tag("num_scanned", num_scanned)
6568
11
                .tag("num_recycled", num_recycled);
6569
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
6560
11
    DORIS_CLOUD_DEFER {
6561
11
        unregister_recycle_task(task_name);
6562
11
        int64_t cost =
6563
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6564
11
        metrics_context.finish_report();
6565
11
        LOG_WARNING("recycle stage, cost={}s", cost)
6566
11
                .tag("instance_id", instance_id_)
6567
11
                .tag("num_scanned", num_scanned)
6568
11
                .tag("num_recycled", num_recycled);
6569
11
    };
6570
6571
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
6572
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
6573
11
    std::string key0 = recycle_stage_key(key_info0);
6574
11
    std::string key1 = recycle_stage_key(key_info1);
6575
6576
11
    std::vector<std::string_view> stage_keys;
6577
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
6578
11
                         this](std::string_view k, std::string_view v) -> int {
6579
1
        ++num_scanned;
6580
1
        RecycleStagePB recycle_stage;
6581
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
6582
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
6583
0
            return -1;
6584
0
        }
6585
6586
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
6587
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6588
0
            LOG(WARNING) << "invalid idx: " << idx;
6589
0
            return -1;
6590
0
        }
6591
6592
1
        std::shared_ptr<StorageVaultAccessor> accessor;
6593
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
6594
1
                [&] {
6595
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
6596
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
6597
1
                    if (!s3_conf) {
6598
1
                        return -1;
6599
1
                    }
6600
6601
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
6602
1
                    std::shared_ptr<S3Accessor> s3_accessor;
6603
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
6604
1
                    if (ret != 0) {
6605
1
                        return -1;
6606
1
                    }
6607
6608
1
                    accessor = std::move(s3_accessor);
6609
1
                    return 0;
6610
1
                }(),
6611
1
                "recycle_stage:get_accessor", &accessor);
6612
6613
1
        if (ret != 0) {
6614
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
6615
0
            return ret;
6616
0
        }
6617
6618
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
6619
1
                .tag("instance_id", instance_id_)
6620
1
                .tag("stage_id", recycle_stage.stage().stage_id())
6621
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
6622
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
6623
1
                .tag("obj_info_id", idx)
6624
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
6625
1
        ret = accessor->delete_all();
6626
1
        if (ret != 0) {
6627
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
6628
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
6629
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
6630
0
                         << ", ret=" << ret;
6631
0
            return -1;
6632
0
        }
6633
1
        metrics_context.total_recycled_num = ++num_recycled;
6634
1
        metrics_context.report();
6635
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
6636
1
        stage_keys.push_back(k);
6637
1
        return 0;
6638
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6578
1
                         this](std::string_view k, std::string_view v) -> int {
6579
1
        ++num_scanned;
6580
1
        RecycleStagePB recycle_stage;
6581
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
6582
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
6583
0
            return -1;
6584
0
        }
6585
6586
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
6587
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6588
0
            LOG(WARNING) << "invalid idx: " << idx;
6589
0
            return -1;
6590
0
        }
6591
6592
1
        std::shared_ptr<StorageVaultAccessor> accessor;
6593
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
6594
1
                [&] {
6595
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
6596
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
6597
1
                    if (!s3_conf) {
6598
1
                        return -1;
6599
1
                    }
6600
6601
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
6602
1
                    std::shared_ptr<S3Accessor> s3_accessor;
6603
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
6604
1
                    if (ret != 0) {
6605
1
                        return -1;
6606
1
                    }
6607
6608
1
                    accessor = std::move(s3_accessor);
6609
1
                    return 0;
6610
1
                }(),
6611
1
                "recycle_stage:get_accessor", &accessor);
6612
6613
1
        if (ret != 0) {
6614
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
6615
0
            return ret;
6616
0
        }
6617
6618
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
6619
1
                .tag("instance_id", instance_id_)
6620
1
                .tag("stage_id", recycle_stage.stage().stage_id())
6621
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
6622
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
6623
1
                .tag("obj_info_id", idx)
6624
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
6625
1
        ret = accessor->delete_all();
6626
1
        if (ret != 0) {
6627
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
6628
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
6629
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
6630
0
                         << ", ret=" << ret;
6631
0
            return -1;
6632
0
        }
6633
1
        metrics_context.total_recycled_num = ++num_recycled;
6634
1
        metrics_context.report();
6635
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
6636
1
        stage_keys.push_back(k);
6637
1
        return 0;
6638
1
    };
6639
6640
11
    auto loop_done = [&stage_keys, this]() -> int {
6641
1
        if (stage_keys.empty()) return 0;
6642
1
        DORIS_CLOUD_DEFER {
6643
1
            stage_keys.clear();
6644
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6642
1
        DORIS_CLOUD_DEFER {
6643
1
            stage_keys.clear();
6644
1
        };
6645
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
6646
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
6647
0
            return -1;
6648
0
        }
6649
1
        return 0;
6650
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
6640
1
    auto loop_done = [&stage_keys, this]() -> int {
6641
1
        if (stage_keys.empty()) return 0;
6642
1
        DORIS_CLOUD_DEFER {
6643
1
            stage_keys.clear();
6644
1
        };
6645
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
6646
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
6647
0
            return -1;
6648
0
        }
6649
1
        return 0;
6650
1
    };
6651
11
    if (config::enable_recycler_stats_metrics) {
6652
0
        scan_and_statistics_stage();
6653
0
    }
6654
    // recycle_func and loop_done for scan and recycle
6655
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
6656
11
}
6657
6658
10
int InstanceRecycler::recycle_expired_stage_objects() {
6659
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
6660
6661
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6662
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
6663
6664
10
    DORIS_CLOUD_DEFER {
6665
10
        int64_t cost =
6666
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6667
10
        metrics_context.finish_report();
6668
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
6669
10
                .tag("instance_id", instance_id_);
6670
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
6664
10
    DORIS_CLOUD_DEFER {
6665
10
        int64_t cost =
6666
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6667
10
        metrics_context.finish_report();
6668
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
6669
10
                .tag("instance_id", instance_id_);
6670
10
    };
6671
6672
10
    int ret = 0;
6673
6674
10
    if (config::enable_recycler_stats_metrics) {
6675
0
        scan_and_statistics_expired_stage_objects();
6676
0
    }
6677
6678
10
    for (const auto& stage : instance_info_.stages()) {
6679
0
        std::stringstream ss;
6680
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
6681
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
6682
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
6683
0
           << ", prefix=" << stage.obj_info().prefix();
6684
6685
0
        if (stopped()) {
6686
0
            break;
6687
0
        }
6688
0
        if (stage.type() == StagePB::EXTERNAL) {
6689
0
            continue;
6690
0
        }
6691
0
        int idx = stoi(stage.obj_info().id());
6692
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6693
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
6694
0
            continue;
6695
0
        }
6696
6697
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
6698
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
6699
0
        if (!s3_conf) {
6700
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
6701
0
            continue;
6702
0
        }
6703
6704
0
        s3_conf->prefix = stage.obj_info().prefix();
6705
0
        std::shared_ptr<S3Accessor> accessor;
6706
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
6707
0
        if (ret1 != 0) {
6708
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
6709
0
            ret = -1;
6710
0
            continue;
6711
0
        }
6712
6713
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
6714
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
6715
0
            ret = -1;
6716
0
            continue;
6717
0
        }
6718
6719
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
6720
0
        int64_t expiration_time =
6721
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
6722
0
                config::internal_stage_objects_expire_time_second;
6723
0
        if (config::force_immediate_recycle) {
6724
0
            expiration_time = INT64_MAX;
6725
0
        }
6726
0
        ret1 = accessor->delete_all(expiration_time);
6727
0
        if (ret1 != 0) {
6728
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
6729
0
                         << ss.str();
6730
0
            ret = -1;
6731
0
            continue;
6732
0
        }
6733
0
        metrics_context.total_recycled_num++;
6734
0
        metrics_context.report();
6735
0
    }
6736
10
    return ret;
6737
10
}
6738
6739
193
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
6740
193
    std::lock_guard lock(recycle_tasks_mutex);
6741
193
    running_recycle_tasks[task_name] = start_time;
6742
193
}
6743
6744
193
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
6745
193
    std::lock_guard lock(recycle_tasks_mutex);
6746
193
    DCHECK(running_recycle_tasks[task_name] > 0);
6747
193
    running_recycle_tasks.erase(task_name);
6748
193
}
6749
6750
21
bool InstanceRecycler::check_recycle_tasks() {
6751
21
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
6752
21
    {
6753
21
        std::lock_guard lock(recycle_tasks_mutex);
6754
21
        tmp_running_recycle_tasks = running_recycle_tasks;
6755
21
    }
6756
6757
21
    bool found = false;
6758
21
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6759
21
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
6760
20
        int64_t cost = now - start_time;
6761
20
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
6762
20
            LOG_INFO("recycle task cost too much time cost={}s", cost)
6763
20
                    .tag("instance_id", instance_id_)
6764
20
                    .tag("task", task_name);
6765
20
            found = true;
6766
20
        }
6767
20
    }
6768
6769
21
    return found;
6770
21
}
6771
6772
// Scan and statistics indexes that need to be recycled
6773
0
int InstanceRecycler::scan_and_statistics_indexes() {
6774
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
6775
6776
0
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
6777
0
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
6778
0
    std::string index_key0;
6779
0
    std::string index_key1;
6780
0
    recycle_index_key(index_key_info0, &index_key0);
6781
0
    recycle_index_key(index_key_info1, &index_key1);
6782
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6783
6784
0
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
6785
0
        RecycleIndexPB index_pb;
6786
0
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
6787
0
            return 0;
6788
0
        }
6789
0
        int64_t current_time = ::time(nullptr);
6790
0
        if (current_time <
6791
0
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
6792
0
            return 0;
6793
0
        }
6794
        // decode index_id
6795
0
        auto k1 = k;
6796
0
        k1.remove_prefix(1);
6797
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6798
0
        decode_key(&k1, &out);
6799
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
6800
0
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
6801
0
        std::unique_ptr<Transaction> txn;
6802
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6803
0
        if (err != TxnErrorCode::TXN_OK) {
6804
0
            return 0;
6805
0
        }
6806
0
        std::string val;
6807
0
        err = txn->get(k, &val);
6808
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6809
0
            return 0;
6810
0
        }
6811
0
        if (err != TxnErrorCode::TXN_OK) {
6812
0
            return 0;
6813
0
        }
6814
0
        index_pb.Clear();
6815
0
        if (!index_pb.ParseFromString(val)) {
6816
0
            return 0;
6817
0
        }
6818
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
6819
0
            return 0;
6820
0
        }
6821
0
        metrics_context.total_need_recycle_num++;
6822
0
        return 0;
6823
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_
6824
6825
0
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
6826
0
    metrics_context.report(true);
6827
0
    segment_metrics_context_.report(true);
6828
0
    tablet_metrics_context_.report(true);
6829
0
    return ret;
6830
0
}
6831
6832
// Scan and statistics partitions that need to be recycled
6833
0
int InstanceRecycler::scan_and_statistics_partitions() {
6834
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
6835
6836
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
6837
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
6838
0
    std::string part_key0;
6839
0
    std::string part_key1;
6840
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6841
6842
0
    recycle_partition_key(part_key_info0, &part_key0);
6843
0
    recycle_partition_key(part_key_info1, &part_key1);
6844
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
6845
0
        RecyclePartitionPB part_pb;
6846
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
6847
0
            return 0;
6848
0
        }
6849
0
        int64_t current_time = ::time(nullptr);
6850
0
        if (current_time <
6851
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
6852
0
            return 0;
6853
0
        }
6854
        // decode partition_id
6855
0
        auto k1 = k;
6856
0
        k1.remove_prefix(1);
6857
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6858
0
        decode_key(&k1, &out);
6859
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
6860
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
6861
        // Change state to RECYCLING
6862
0
        std::unique_ptr<Transaction> txn;
6863
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6864
0
        if (err != TxnErrorCode::TXN_OK) {
6865
0
            return 0;
6866
0
        }
6867
0
        std::string val;
6868
0
        err = txn->get(k, &val);
6869
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6870
0
            return 0;
6871
0
        }
6872
0
        if (err != TxnErrorCode::TXN_OK) {
6873
0
            return 0;
6874
0
        }
6875
0
        part_pb.Clear();
6876
0
        if (!part_pb.ParseFromString(val)) {
6877
0
            return 0;
6878
0
        }
6879
        // Partitions with PREPARED state MUST have no data
6880
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
6881
0
        int ret = 0;
6882
0
        for (int64_t index_id : part_pb.index_id()) {
6883
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
6884
0
                                            partition_id, is_empty_tablet) != 0) {
6885
0
                ret = 0;
6886
0
            }
6887
0
        }
6888
0
        metrics_context.total_need_recycle_num++;
6889
0
        return ret;
6890
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_
6891
6892
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
6893
0
    metrics_context.report(true);
6894
0
    segment_metrics_context_.report(true);
6895
0
    tablet_metrics_context_.report(true);
6896
0
    return ret;
6897
0
}
6898
6899
// Scan and statistics rowsets that need to be recycled
6900
0
int InstanceRecycler::scan_and_statistics_rowsets() {
6901
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
6902
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
6903
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
6904
0
    std::string recyc_rs_key0;
6905
0
    std::string recyc_rs_key1;
6906
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
6907
0
                recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
6908
0
       int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6909
6910
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6911
0
        RecycleRowsetPB rowset;
6912
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6913
0
            return 0;
6914
0
        }
6915
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
6916
0
        int64_t current_time = ::time(nullptr);
6917
0
        if (current_time <
6918
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
6919
0
            return 0;
6920
0
        }
6921
6922
0
        if (!rowset.has_type()) {
6923
0
            if (!rowset.has_resource_id()) [[unlikely]] {
6924
0
                return 0;
6925
0
            }
6926
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6927
0
                return 0;
6928
0
            }
6929
0
            metrics_context.total_need_recycle_num++;
6930
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
6931
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
6932
0
            segment_metrics_context_.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
6933
0
            return 0;
6934
0
        }
6935
6936
0
        if(!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled()) {
6937
0
            return 0;
6938
0
        }
6939
6940
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
6941
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
6942
0
                return 0;
6943
0
            }
6944
0
        }
6945
0
        metrics_context.total_need_recycle_num++;
6946
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
6947
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
6948
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
6949
0
        return 0;
6950
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_
6951
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
6952
0
    metrics_context.report(true);
6953
0
    segment_metrics_context_.report(true);
6954
0
    return ret;
6955
0
}
6956
6957
// Scan and statistics tmp_rowsets that need to be recycled
6958
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
6959
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
6960
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
6961
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
6962
0
    std::string tmp_rs_key0;
6963
0
    std::string tmp_rs_key1;
6964
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
6965
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
6966
6967
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6968
6969
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
6970
0
        doris::RowsetMetaCloudPB rowset;
6971
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6972
0
            return 0;
6973
0
        }
6974
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6975
0
        int64_t current_time = ::time(nullptr);
6976
0
        if (current_time < expiration) {
6977
0
            return 0;
6978
0
        }
6979
6980
0
        DCHECK_GT(rowset.txn_id(), 0)
6981
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
6982
6983
0
        if(!rowset.has_is_recycled() || !rowset.is_recycled()) {
6984
0
            return 0;
6985
0
        }
6986
6987
0
        if (!rowset.has_resource_id()) {
6988
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6989
0
                return 0;
6990
0
            }
6991
0
            return 0;
6992
0
        }
6993
6994
0
        metrics_context.total_need_recycle_num++;
6995
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
6996
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
6997
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
6998
0
        return 0;
6999
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_
7000
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
7001
0
    metrics_context.report(true);
7002
0
    segment_metrics_context_.report(true);
7003
0
    return ret;
7004
0
}
7005
7006
// Scan and statistics abort_timeout_txn that need to be recycled
7007
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
7008
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
7009
7010
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
7011
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7012
0
    std::string begin_txn_running_key;
7013
0
    std::string end_txn_running_key;
7014
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
7015
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
7016
7017
0
    int64_t current_time =
7018
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7019
7020
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
7021
0
                                               std::string_view k, std::string_view v) -> int {
7022
0
        std::unique_ptr<Transaction> txn;
7023
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7024
0
        if (err != TxnErrorCode::TXN_OK) {
7025
0
            return 0;
7026
0
        }
7027
0
        std::string_view k1 = k;
7028
0
        k1.remove_prefix(1);
7029
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7030
0
        if (decode_key(&k1, &out) != 0) {
7031
0
            return 0;
7032
0
        }
7033
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7034
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7035
        // Update txn_info
7036
0
        std::string txn_inf_key, txn_inf_val;
7037
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
7038
0
        err = txn->get(txn_inf_key, &txn_inf_val);
7039
0
        if (err != TxnErrorCode::TXN_OK) {
7040
0
            return 0;
7041
0
        }
7042
0
        TxnInfoPB txn_info;
7043
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
7044
0
            return 0;
7045
0
        }
7046
7047
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
7048
0
            TxnRunningPB txn_running_pb;
7049
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7050
0
                return 0;
7051
0
            }
7052
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7053
0
                return 0;
7054
0
            }
7055
0
            metrics_context.total_need_recycle_num++;
7056
0
        }
7057
0
        return 0;
7058
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_
7059
7060
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key, std::move(handle_abort_timeout_txn_kv));
7061
0
    metrics_context.report(true);
7062
0
    return ret;
7063
0
}
7064
7065
// Scan and statistics expired_txn_label that need to be recycled
7066
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
7067
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
7068
7069
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7070
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7071
0
    std::string begin_recycle_txn_key;
7072
0
    std::string end_recycle_txn_key;
7073
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7074
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7075
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7076
0
    int64_t current_time_ms =
7077
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7078
7079
    // for calculate the total num or bytes of recyled objects
7080
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
7081
0
        RecycleTxnPB recycle_txn_pb;
7082
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7083
0
            return 0;
7084
0
        }
7085
0
        if ((config::force_immediate_recycle) ||
7086
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7087
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7088
0
             current_time_ms)) {
7089
0
            metrics_context.total_need_recycle_num++;
7090
0
        }
7091
0
        return 0;
7092
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_
7093
7094
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key, std::move(handle_expired_txn_label_kv));
7095
0
    metrics_context.report(true);
7096
0
    return ret;
7097
0
}
7098
7099
// Scan and statistics copy_jobs that need to be recycled
7100
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
7101
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
7102
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7103
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7104
0
    std::string key0;
7105
0
    std::string key1;
7106
0
    copy_job_key(key_info0, &key0);
7107
0
    copy_job_key(key_info1, &key1);
7108
7109
    // for calculate the total num or bytes of recyled objects
7110
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
7111
0
        CopyJobPB copy_job;
7112
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7113
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7114
0
            return 0;
7115
0
        }
7116
7117
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7118
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
7119
0
                int64_t current_time =
7120
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7121
0
                if (copy_job.finish_time_ms() > 0) {
7122
0
                    if (!config::force_immediate_recycle &&
7123
0
                        current_time < copy_job.finish_time_ms() +
7124
0
                                               config::copy_job_max_retention_second * 1000) {
7125
0
                        return 0;
7126
0
                    }
7127
0
                } else {
7128
0
                    if (!config::force_immediate_recycle &&
7129
0
                        current_time < copy_job.start_time_ms() +
7130
0
                                               config::copy_job_max_retention_second * 1000) {
7131
0
                        return 0;
7132
0
                    }
7133
0
                }
7134
0
            }
7135
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7136
0
            int64_t current_time =
7137
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7138
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7139
0
                return 0;
7140
0
            }
7141
0
        }
7142
0
        metrics_context.total_need_recycle_num++;
7143
0
        return 0;
7144
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_
7145
7146
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7147
0
    metrics_context.report(true);
7148
0
    return ret;
7149
0
}
7150
7151
// Scan and statistics stage that need to be recycled
7152
0
int InstanceRecycler::scan_and_statistics_stage() {
7153
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
7154
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7155
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7156
0
    std::string key0 = recycle_stage_key(key_info0);
7157
0
    std::string key1 = recycle_stage_key(key_info1);
7158
7159
    // for calculate the total num or bytes of recyled objects
7160
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
7161
0
                                                        std::string_view v) -> int {
7162
0
        RecycleStagePB recycle_stage;
7163
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7164
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7165
0
            return 0;
7166
0
        }
7167
7168
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
7169
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7170
0
            LOG(WARNING) << "invalid idx: " << idx;
7171
0
            return 0;
7172
0
        }
7173
7174
0
        std::shared_ptr<StorageVaultAccessor> accessor;
7175
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7176
0
                [&] {
7177
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7178
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7179
0
                    if (!s3_conf) {
7180
0
                        return 0;
7181
0
                    }
7182
7183
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7184
0
                    std::shared_ptr<S3Accessor> s3_accessor;
7185
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7186
0
                    if (ret != 0) {
7187
0
                        return 0;
7188
0
                    }
7189
7190
0
                    accessor = std::move(s3_accessor);
7191
0
                    return 0;
7192
0
                }(),
7193
0
                "recycle_stage:get_accessor", &accessor);
7194
7195
0
        if (ret != 0) {
7196
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7197
0
            return 0;
7198
0
        }
7199
7200
0
        metrics_context.total_need_recycle_num++;
7201
0
        return 0;
7202
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_
7203
7204
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7205
0
    metrics_context.report(true);
7206
0
    return ret;
7207
0
}
7208
7209
// Scan and statistics expired_stage_objects that need to be recycled
7210
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
7211
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7212
7213
    // for calculate the total num or bytes of recyled objects
7214
0
    auto scan_and_statistics = [&metrics_context, this]() {
7215
0
        for (const auto& stage : instance_info_.stages()) {
7216
0
            if (stopped()) {
7217
0
                break;
7218
0
            }
7219
0
            if (stage.type() == StagePB::EXTERNAL) {
7220
0
                continue;
7221
0
            }
7222
0
            int idx = stoi(stage.obj_info().id());
7223
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
7224
0
                continue;
7225
0
            }
7226
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
7227
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7228
0
            if (!s3_conf) {
7229
0
                continue;
7230
0
            }
7231
0
            s3_conf->prefix = stage.obj_info().prefix();
7232
0
            std::shared_ptr<S3Accessor> accessor;
7233
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
7234
0
            if (ret1 != 0) {
7235
0
                continue;
7236
0
            }
7237
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7238
0
                continue;
7239
0
            }
7240
0
            metrics_context.total_need_recycle_num++;
7241
0
        }
7242
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
7243
7244
0
    scan_and_statistics();
7245
0
    metrics_context.report(true);
7246
0
    return 0;
7247
0
}
7248
7249
// Scan and statistics versions that need to be recycled
7250
0
int InstanceRecycler::scan_and_statistics_versions() {
7251
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
7252
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
7253
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
7254
7255
0
    int64_t last_scanned_table_id = 0;
7256
0
    bool is_recycled = false; // Is last scanned kv recycled
7257
    // for calculate the total num or bytes of recyled objects
7258
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
7259
0
                                       std::string_view k, std::string_view) {
7260
0
        auto k1 = k;
7261
0
        k1.remove_prefix(1);
7262
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
7263
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7264
0
        decode_key(&k1, &out);
7265
0
        DCHECK_EQ(out.size(), 6) << k;
7266
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
7267
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
7268
0
            metrics_context.total_need_recycle_num +=
7269
0
                    is_recycled; // Version kv of this table has been recycled
7270
0
            return 0;
7271
0
        }
7272
0
        last_scanned_table_id = table_id;
7273
0
        is_recycled = false;
7274
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
7275
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
7276
0
        std::unique_ptr<Transaction> txn;
7277
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7278
0
        if (err != TxnErrorCode::TXN_OK) {
7279
0
            return 0;
7280
0
        }
7281
0
        std::unique_ptr<RangeGetIterator> iter;
7282
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
7283
0
        if (err != TxnErrorCode::TXN_OK) {
7284
0
            return 0;
7285
0
        }
7286
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
7287
0
            return 0;
7288
0
        }
7289
0
        metrics_context.total_need_recycle_num++;
7290
0
        is_recycled = true;
7291
0
        return 0;
7292
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_
7293
7294
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
7295
0
    metrics_context.report(true);
7296
0
    return ret;
7297
0
}
7298
7299
// Scan and statistics restore jobs that need to be recycled
7300
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
7301
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
7302
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
7303
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
7304
0
    std::string restore_job_key0;
7305
0
    std::string restore_job_key1;
7306
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
7307
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
7308
7309
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7310
7311
    // for calculate the total num or bytes of recyled objects
7312
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
7313
0
        RestoreJobCloudPB restore_job_pb;
7314
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
7315
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
7316
0
            return 0;
7317
0
        }
7318
0
        int64_t expiration =
7319
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
7320
0
        int64_t current_time = ::time(nullptr);
7321
0
        if (current_time < expiration) { // not expired
7322
0
            return 0;
7323
0
        }
7324
0
        metrics_context.total_need_recycle_num++;
7325
0
        if(restore_job_pb.need_recycle_data()) {
7326
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
7327
0
        }
7328
0
        return 0;
7329
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_
7330
7331
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
7332
0
    metrics_context.report(true);
7333
0
    return ret;
7334
0
}
7335
7336
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
7337
3
    if (!should_recycle_versioned_keys()) {
7338
0
        return;
7339
0
    }
7340
7341
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
7342
7343
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
7344
3
    if (recycle_checker.init() != 0) {
7345
0
        return;
7346
0
    }
7347
7348
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
7349
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
7350
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
7351
7352
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
7353
8
    for (; iter->valid(); iter->next()) {
7354
5
        OperationLogPB operation_log;
7355
5
        if (!iter->parse_value(&operation_log)) {
7356
0
            continue;
7357
0
        }
7358
7359
5
        std::string_view key = iter->key();
7360
5
        Versionstamp log_versionstamp;
7361
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
7362
0
            continue;
7363
0
        }
7364
7365
5
        OperationLogReferenceInfo ref_info;
7366
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
7367
5
                                         &ref_info)) {
7368
4
            metrics_context.total_need_recycle_num++;
7369
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
7370
4
        }
7371
5
    }
7372
7373
3
    metrics_context.report(true);
7374
3
}
7375
7376
int InstanceRecycler::classify_rowset_task_by_ref_count(
7377
60
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
7378
60
    constexpr int MAX_RETRY = 10;
7379
60
    const auto& rowset_meta = task.rowset_meta;
7380
60
    int64_t tablet_id = rowset_meta.tablet_id();
7381
60
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
7382
60
    std::string_view reference_instance_id = instance_id_;
7383
60
    if (rowset_meta.has_reference_instance_id()) {
7384
5
        reference_instance_id = rowset_meta.reference_instance_id();
7385
5
    }
7386
7387
61
    for (int i = 0; i < MAX_RETRY; ++i) {
7388
61
        std::unique_ptr<Transaction> txn;
7389
61
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7390
61
        if (err != TxnErrorCode::TXN_OK) {
7391
0
            LOG_WARNING("failed to create txn when classifying rowset task")
7392
0
                    .tag("instance_id", instance_id_)
7393
0
                    .tag("tablet_id", tablet_id)
7394
0
                    .tag("rowset_id", rowset_id)
7395
0
                    .tag("err", err);
7396
0
            return -1;
7397
0
        }
7398
7399
61
        std::string rowset_ref_count_key =
7400
61
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
7401
61
        task.rowset_ref_count_key = rowset_ref_count_key;
7402
7403
61
        int64_t ref_count = 0;
7404
61
        {
7405
61
            std::string value;
7406
61
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
7407
61
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7408
0
                ref_count = 1;
7409
61
            } else if (err != TxnErrorCode::TXN_OK) {
7410
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
7411
0
                        .tag("instance_id", instance_id_)
7412
0
                        .tag("tablet_id", tablet_id)
7413
0
                        .tag("rowset_id", rowset_id)
7414
0
                        .tag("err", err);
7415
0
                return -1;
7416
61
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
7417
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
7418
0
                        .tag("instance_id", instance_id_)
7419
0
                        .tag("tablet_id", tablet_id)
7420
0
                        .tag("rowset_id", rowset_id)
7421
0
                        .tag("value", hex(value));
7422
0
                return -1;
7423
0
            }
7424
61
        }
7425
7426
61
        if (ref_count > 1) {
7427
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
7428
12
            txn->atomic_add(rowset_ref_count_key, -1);
7429
12
            LOG_INFO("decrease rowset data ref count in classification phase")
7430
12
                    .tag("instance_id", instance_id_)
7431
12
                    .tag("tablet_id", tablet_id)
7432
12
                    .tag("rowset_id", rowset_id)
7433
12
                    .tag("ref_count", ref_count - 1)
7434
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
7435
7436
12
            if (!task.recycle_rowset_key.empty()) {
7437
0
                txn->remove(task.recycle_rowset_key);
7438
0
                LOG_INFO("remove recycle rowset key in classification phase")
7439
0
                        .tag("key", hex(task.recycle_rowset_key));
7440
0
            }
7441
12
            if (!task.non_versioned_rowset_key.empty()) {
7442
12
                txn->remove(task.non_versioned_rowset_key);
7443
12
                LOG_INFO("remove non versioned rowset key in classification phase")
7444
12
                        .tag("key", hex(task.non_versioned_rowset_key));
7445
12
            }
7446
7447
12
            err = txn->commit();
7448
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
7449
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
7450
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
7451
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
7452
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
7453
1
                continue;
7454
11
            } else if (err != TxnErrorCode::TXN_OK) {
7455
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
7456
0
                        .tag("instance_id", instance_id_)
7457
0
                        .tag("tablet_id", tablet_id)
7458
0
                        .tag("rowset_id", rowset_id)
7459
0
                        .tag("err", err);
7460
0
                return -1;
7461
0
            }
7462
11
            return 1; // handled, not added to batch delete
7463
49
        } else {
7464
            // ref_count == 1: Add to batch delete plan without modifying any KV.
7465
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
7466
49
            LOG_INFO("add rowset to batch delete plan")
7467
49
                    .tag("instance_id", instance_id_)
7468
49
                    .tag("tablet_id", tablet_id)
7469
49
                    .tag("rowset_id", rowset_id)
7470
49
                    .tag("resource_id", rowset_meta.resource_id())
7471
49
                    .tag("ref_count", ref_count);
7472
7473
49
            batch_delete_tasks.push_back(std::move(task));
7474
49
            return 0; // added to batch delete
7475
49
        }
7476
61
    }
7477
7478
0
    LOG_WARNING("failed to classify rowset task after retry")
7479
0
            .tag("instance_id", instance_id_)
7480
0
            .tag("tablet_id", tablet_id)
7481
0
            .tag("rowset_id", rowset_id)
7482
0
            .tag("retry", MAX_RETRY);
7483
0
    return -1;
7484
60
}
7485
7486
10
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
7487
10
    int ret = 0;
7488
49
    for (const auto& task : tasks) {
7489
49
        int64_t tablet_id = task.rowset_meta.tablet_id();
7490
49
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
7491
7492
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
7493
        // so we don't need to call it again here.
7494
7495
        // Remove all metadata keys in one transaction
7496
49
        std::unique_ptr<Transaction> txn;
7497
49
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7498
49
        if (err != TxnErrorCode::TXN_OK) {
7499
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
7500
0
                    .tag("instance_id", instance_id_)
7501
0
                    .tag("tablet_id", tablet_id)
7502
0
                    .tag("rowset_id", rowset_id)
7503
0
                    .tag("err", err);
7504
0
            ret = -1;
7505
0
            continue;
7506
0
        }
7507
7508
49
        std::string_view reference_instance_id = instance_id_;
7509
49
        if (task.rowset_meta.has_reference_instance_id()) {
7510
5
            reference_instance_id = task.rowset_meta.reference_instance_id();
7511
5
        }
7512
7513
49
        txn->remove(task.rowset_ref_count_key);
7514
49
        LOG_INFO("delete rowset data ref count key in cleanup phase")
7515
49
                .tag("instance_id", instance_id_)
7516
49
                .tag("tablet_id", tablet_id)
7517
49
                .tag("rowset_id", rowset_id)
7518
49
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
7519
7520
49
        std::string dbm_start_key =
7521
49
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
7522
49
        std::string dbm_end_key = meta_delete_bitmap_key(
7523
49
                {reference_instance_id, tablet_id, rowset_id,
7524
49
                 std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
7525
49
        txn->remove(dbm_start_key, dbm_end_key);
7526
49
        LOG_INFO("remove delete bitmap kv in cleanup phase")
7527
49
                .tag("instance_id", instance_id_)
7528
49
                .tag("tablet_id", tablet_id)
7529
49
                .tag("rowset_id", rowset_id)
7530
49
                .tag("begin", hex(dbm_start_key))
7531
49
                .tag("end", hex(dbm_end_key));
7532
7533
49
        std::string versioned_dbm_start_key =
7534
49
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
7535
49
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
7536
49
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
7537
49
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
7538
49
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
7539
49
                .tag("instance_id", instance_id_)
7540
49
                .tag("tablet_id", tablet_id)
7541
49
                .tag("rowset_id", rowset_id)
7542
49
                .tag("begin", hex(versioned_dbm_start_key))
7543
49
                .tag("end", hex(versioned_dbm_end_key));
7544
7545
        // Remove versioned meta rowset key
7546
49
        if (!task.versioned_rowset_key.empty()) {
7547
49
            versioned::document_remove<RowsetMetaCloudPB>(
7548
49
                txn.get(), task.versioned_rowset_key, task.versionstamp);
7549
49
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
7550
49
                    .tag("instance_id", instance_id_)
7551
49
                    .tag("tablet_id", tablet_id)
7552
49
                    .tag("rowset_id", rowset_id)
7553
49
                    .tag("key_prefix", hex(task.versioned_rowset_key));
7554
49
        }
7555
7556
49
        if (!task.non_versioned_rowset_key.empty()) {
7557
49
            txn->remove(task.non_versioned_rowset_key);
7558
49
            LOG_INFO("remove non versioned rowset key in cleanup phase")
7559
49
                    .tag("instance_id", instance_id_)
7560
49
                    .tag("tablet_id", tablet_id)
7561
49
                    .tag("rowset_id", rowset_id)
7562
49
                    .tag("key", hex(task.non_versioned_rowset_key));
7563
49
        }
7564
7565
        // Remove recycle_rowset_key last to ensure retry safety:
7566
        // if cleanup fails, this key remains and triggers next round retry.
7567
49
        if (!task.recycle_rowset_key.empty()) {
7568
0
            txn->remove(task.recycle_rowset_key);
7569
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
7570
0
                    .tag("instance_id", instance_id_)
7571
0
                    .tag("tablet_id", tablet_id)
7572
0
                    .tag("rowset_id", rowset_id)
7573
0
                    .tag("key", hex(task.recycle_rowset_key));
7574
0
        }
7575
7576
49
        err = txn->commit();
7577
49
        if (err != TxnErrorCode::TXN_OK) {
7578
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
7579
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
7580
0
                    .tag("instance_id", instance_id_)
7581
0
                    .tag("tablet_id", tablet_id)
7582
0
                    .tag("rowset_id", rowset_id)
7583
0
                    .tag("err", err);
7584
0
            ret = -1;
7585
0
            continue;
7586
0
        }
7587
7588
49
        LOG_INFO("cleanup rowset metadata success")
7589
49
                .tag("instance_id", instance_id_)
7590
49
                .tag("tablet_id", tablet_id)
7591
49
                .tag("rowset_id", rowset_id);
7592
49
    }
7593
10
    return ret;
7594
10
}
7595
7596
} // namespace doris::cloud