Coverage Report

Created: 2026-08-18 23:08

/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 <optional>
40
#include <random>
41
#include <string>
42
#include <string_view>
43
#include <thread>
44
#include <unordered_map>
45
#include <unordered_set>
46
#include <utility>
47
#include <variant>
48
49
#include "common/defer.h"
50
#include "common/stopwatch.h"
51
#include "meta-service/meta_service.h"
52
#include "meta-service/meta_service_helper.h"
53
#include "meta-service/meta_service_schema.h"
54
#include "meta-store/blob_message.h"
55
#include "meta-store/meta_reader.h"
56
#include "meta-store/txn_kv.h"
57
#include "meta-store/txn_kv_error.h"
58
#include "meta-store/versioned_value.h"
59
#include "recycler/checker.h"
60
#ifdef ENABLE_HDFS_STORAGE_VAULT
61
#include "recycler/hdfs_accessor.h"
62
#endif
63
#include "recycler/s3_accessor.h"
64
#include "recycler/storage_vault_accessor.h"
65
#ifdef UNIT_TEST
66
#include "../test/mock_accessor.h"
67
#endif
68
#include "common/bvars.h"
69
#include "common/config.h"
70
#include "common/encryption_util.h"
71
#include "common/logging.h"
72
#include "common/simple_thread_pool.h"
73
#include "common/util.h"
74
#include "cpp/sync_point.h"
75
#include "meta-store/codec.h"
76
#include "meta-store/document_message.h"
77
#include "meta-store/keys.h"
78
#include "recycler/recycler_service.h"
79
#include "recycler/sync_executor.h"
80
#include "recycler/util.h"
81
#include "snapshot/snapshot_manager_factory.h"
82
83
namespace doris::cloud {
84
85
using namespace std::chrono;
86
87
namespace {
88
89
0
int64_t packed_file_retry_sleep_ms() {
90
0
    const int64_t min_ms = std::max<int64_t>(0, config::packed_file_txn_retry_sleep_min_ms);
91
0
    const int64_t max_ms = std::max<int64_t>(min_ms, config::packed_file_txn_retry_sleep_max_ms);
92
0
    thread_local std::mt19937_64 gen(std::random_device {}());
93
0
    std::uniform_int_distribution<int64_t> dist(min_ms, max_ms);
94
0
    return dist(gen);
95
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
96
97
0
void sleep_for_packed_file_retry() {
98
0
    std::this_thread::sleep_for(std::chrono::milliseconds(packed_file_retry_sleep_ms()));
99
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
100
101
869k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
102
869k
    const auto& locations = rowset.packed_slice_locations();
103
869k
    auto it = locations.find(path);
104
869k
    return it != locations.end() && it->second.has_packed_file_path() &&
105
869k
           !it->second.packed_file_path().empty();
106
869k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
101
7
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
102
7
    const auto& locations = rowset.packed_slice_locations();
103
7
    auto it = locations.find(path);
104
7
    return it != locations.end() && it->second.has_packed_file_path() &&
105
7
           !it->second.packed_file_path().empty();
106
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
101
869k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
102
869k
    const auto& locations = rowset.packed_slice_locations();
103
869k
    auto it = locations.find(path);
104
869k
    return it != locations.end() && it->second.has_packed_file_path() &&
105
869k
           !it->second.packed_file_path().empty();
106
869k
}
107
108
void add_file_to_delete_if_not_packed(const doris::RowsetMetaCloudPB& rowset,
109
                                      const std::string& path,
110
868k
                                      std::vector<std::string>* file_paths) {
111
869k
    if (!is_packed_slice_path(rowset, path)) {
112
869k
        file_paths->push_back(path);
113
869k
    }
114
868k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
110
7
                                      std::vector<std::string>* file_paths) {
111
7
    if (!is_packed_slice_path(rowset, path)) {
112
7
        file_paths->push_back(path);
113
7
    }
114
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
110
868k
                                      std::vector<std::string>* file_paths) {
111
869k
    if (!is_packed_slice_path(rowset, path)) {
112
869k
        file_paths->push_back(path);
113
869k
    }
114
868k
}
115
116
47
bool filter_out_instance(const std::string& instance_id) {
117
47
    if (config::recycle_whitelist.empty()) {
118
45
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
119
45
               config::recycle_blacklist.end();
120
45
    }
121
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
122
2
           config::recycle_whitelist.end();
123
47
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_119filter_out_instanceERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_119filter_out_instanceERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
116
47
bool filter_out_instance(const std::string& instance_id) {
117
47
    if (config::recycle_whitelist.empty()) {
118
45
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
119
45
               config::recycle_blacklist.end();
120
45
    }
121
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
122
2
           config::recycle_whitelist.end();
123
47
}
124
125
} // namespace
126
127
// return 0 for success get a key, 1 for key not found, negative for error
128
0
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
129
0
    std::unique_ptr<Transaction> txn;
130
0
    TxnErrorCode err = txn_kv->create_txn(&txn);
131
0
    if (err != TxnErrorCode::TXN_OK) {
132
0
        return -1;
133
0
    }
134
0
    switch (txn->get(key, &val, true)) {
135
0
    case TxnErrorCode::TXN_OK:
136
0
        return 0;
137
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
138
0
        return 1;
139
0
    default:
140
0
        return -1;
141
0
    };
142
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
143
144
// 0 for success, negative for error
145
static int txn_get(TxnKv* txn_kv, std::string_view begin, std::string_view end,
146
375
                   std::unique_ptr<RangeGetIterator>& it) {
147
375
    std::unique_ptr<Transaction> txn;
148
375
    TxnErrorCode err = txn_kv->create_txn(&txn);
149
375
    if (err != TxnErrorCode::TXN_OK) {
150
0
        return -1;
151
0
    }
152
375
    switch (txn->get(begin, end, &it, true)) {
153
375
    case TxnErrorCode::TXN_OK:
154
375
        return 0;
155
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
156
0
        return 1;
157
0
    default:
158
0
        return -1;
159
375
    };
160
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
146
36
                   std::unique_ptr<RangeGetIterator>& it) {
147
36
    std::unique_ptr<Transaction> txn;
148
36
    TxnErrorCode err = txn_kv->create_txn(&txn);
149
36
    if (err != TxnErrorCode::TXN_OK) {
150
0
        return -1;
151
0
    }
152
36
    switch (txn->get(begin, end, &it, true)) {
153
36
    case TxnErrorCode::TXN_OK:
154
36
        return 0;
155
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
156
0
        return 1;
157
0
    default:
158
0
        return -1;
159
36
    };
160
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
146
339
                   std::unique_ptr<RangeGetIterator>& it) {
147
339
    std::unique_ptr<Transaction> txn;
148
339
    TxnErrorCode err = txn_kv->create_txn(&txn);
149
339
    if (err != TxnErrorCode::TXN_OK) {
150
0
        return -1;
151
0
    }
152
339
    switch (txn->get(begin, end, &it, true)) {
153
339
    case TxnErrorCode::TXN_OK:
154
339
        return 0;
155
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
156
0
        return 1;
157
0
    default:
158
0
        return -1;
159
339
    };
160
0
}
161
162
// return 0 for success otherwise error
163
10
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
164
10
    std::unique_ptr<Transaction> txn;
165
10
    TxnErrorCode err = txn_kv->create_txn(&txn);
166
10
    if (err != TxnErrorCode::TXN_OK) {
167
0
        return -1;
168
0
    }
169
18
    for (auto k : keys) {
170
18
        txn->remove(k);
171
18
    }
172
10
    switch (txn->commit()) {
173
10
    case TxnErrorCode::TXN_OK:
174
10
        return 0;
175
0
    case TxnErrorCode::TXN_CONFLICT:
176
0
        return -1;
177
0
    default:
178
0
        return -1;
179
10
    }
180
10
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
163
3
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
164
3
    std::unique_ptr<Transaction> txn;
165
3
    TxnErrorCode err = txn_kv->create_txn(&txn);
166
3
    if (err != TxnErrorCode::TXN_OK) {
167
0
        return -1;
168
0
    }
169
3
    for (auto k : keys) {
170
3
        txn->remove(k);
171
3
    }
172
3
    switch (txn->commit()) {
173
3
    case TxnErrorCode::TXN_OK:
174
3
        return 0;
175
0
    case TxnErrorCode::TXN_CONFLICT:
176
0
        return -1;
177
0
    default:
178
0
        return -1;
179
3
    }
180
3
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
163
7
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
164
7
    std::unique_ptr<Transaction> txn;
165
7
    TxnErrorCode err = txn_kv->create_txn(&txn);
166
7
    if (err != TxnErrorCode::TXN_OK) {
167
0
        return -1;
168
0
    }
169
15
    for (auto k : keys) {
170
15
        txn->remove(k);
171
15
    }
172
7
    switch (txn->commit()) {
173
7
    case TxnErrorCode::TXN_OK:
174
7
        return 0;
175
0
    case TxnErrorCode::TXN_CONFLICT:
176
0
        return -1;
177
0
    default:
178
0
        return -1;
179
7
    }
180
7
}
181
182
// return 0 for success otherwise error
183
80
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
184
80
    std::unique_ptr<Transaction> txn;
185
80
    TxnErrorCode err = txn_kv->create_txn(&txn);
186
80
    if (err != TxnErrorCode::TXN_OK) {
187
0
        return -1;
188
0
    }
189
106k
    for (auto& k : keys) {
190
106k
        txn->remove(k);
191
106k
    }
192
80
    switch (txn->commit()) {
193
80
    case TxnErrorCode::TXN_OK:
194
80
        return 0;
195
0
    case TxnErrorCode::TXN_CONFLICT:
196
0
        return -1;
197
0
    default:
198
0
        return -1;
199
80
    }
200
80
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
183
27
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
184
27
    std::unique_ptr<Transaction> txn;
185
27
    TxnErrorCode err = txn_kv->create_txn(&txn);
186
27
    if (err != TxnErrorCode::TXN_OK) {
187
0
        return -1;
188
0
    }
189
27
    for (auto& k : keys) {
190
17
        txn->remove(k);
191
17
    }
192
27
    switch (txn->commit()) {
193
27
    case TxnErrorCode::TXN_OK:
194
27
        return 0;
195
0
    case TxnErrorCode::TXN_CONFLICT:
196
0
        return -1;
197
0
    default:
198
0
        return -1;
199
27
    }
200
27
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
183
53
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
184
53
    std::unique_ptr<Transaction> txn;
185
53
    TxnErrorCode err = txn_kv->create_txn(&txn);
186
53
    if (err != TxnErrorCode::TXN_OK) {
187
0
        return -1;
188
0
    }
189
106k
    for (auto& k : keys) {
190
106k
        txn->remove(k);
191
106k
    }
192
53
    switch (txn->commit()) {
193
53
    case TxnErrorCode::TXN_OK:
194
53
        return 0;
195
0
    case TxnErrorCode::TXN_CONFLICT:
196
0
        return -1;
197
0
    default:
198
0
        return -1;
199
53
    }
200
53
}
201
202
// return 0 for success otherwise error
203
[[maybe_unused]] static int txn_remove(TxnKv* txn_kv, std::string_view begin,
204
106k
                                       std::string_view end) {
205
106k
    std::unique_ptr<Transaction> txn;
206
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
207
106k
    if (err != TxnErrorCode::TXN_OK) {
208
0
        return -1;
209
0
    }
210
106k
    txn->remove(begin, end);
211
106k
    switch (txn->commit()) {
212
106k
    case TxnErrorCode::TXN_OK:
213
106k
        return 0;
214
0
    case TxnErrorCode::TXN_CONFLICT:
215
0
        return -1;
216
0
    default:
217
0
        return -1;
218
106k
    }
219
106k
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
204
17
                                       std::string_view end) {
205
17
    std::unique_ptr<Transaction> txn;
206
17
    TxnErrorCode err = txn_kv->create_txn(&txn);
207
17
    if (err != TxnErrorCode::TXN_OK) {
208
0
        return -1;
209
0
    }
210
17
    txn->remove(begin, end);
211
17
    switch (txn->commit()) {
212
17
    case TxnErrorCode::TXN_OK:
213
17
        return 0;
214
0
    case TxnErrorCode::TXN_CONFLICT:
215
0
        return -1;
216
0
    default:
217
0
        return -1;
218
17
    }
219
17
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
204
106k
                                       std::string_view end) {
205
106k
    std::unique_ptr<Transaction> txn;
206
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
207
106k
    if (err != TxnErrorCode::TXN_OK) {
208
0
        return -1;
209
0
    }
210
106k
    txn->remove(begin, end);
211
106k
    switch (txn->commit()) {
212
106k
    case TxnErrorCode::TXN_OK:
213
106k
        return 0;
214
0
    case TxnErrorCode::TXN_CONFLICT:
215
0
        return -1;
216
0
    default:
217
0
        return -1;
218
106k
    }
219
106k
}
220
221
void scan_restore_job_rowset(
222
        Transaction* txn, const std::string& instance_id, int64_t tablet_id, MetaServiceCode& code,
223
        std::string& msg,
224
        std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>* restore_job_rs_metas);
225
226
static inline void check_recycle_task(const std::string& instance_id, const std::string& task_name,
227
                                      int64_t num_scanned, int64_t num_recycled,
228
55
                                      int64_t start_time) {
229
55
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
230
0
        int64_t cost =
231
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
232
0
        if (cost > config::recycle_task_threshold_seconds) {
233
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
234
0
                    .tag("instance_id", instance_id)
235
0
                    .tag("task", task_name)
236
0
                    .tag("num_scanned", num_scanned)
237
0
                    .tag("num_recycled", num_recycled);
238
0
        }
239
0
    }
240
55
    return;
241
55
}
recycler.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
228
4
                                      int64_t start_time) {
229
4
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
230
0
        int64_t cost =
231
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
232
0
        if (cost > config::recycle_task_threshold_seconds) {
233
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
234
0
                    .tag("instance_id", instance_id)
235
0
                    .tag("task", task_name)
236
0
                    .tag("num_scanned", num_scanned)
237
0
                    .tag("num_recycled", num_recycled);
238
0
        }
239
0
    }
240
4
    return;
241
4
}
recycler_test.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
228
51
                                      int64_t start_time) {
229
51
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
230
0
        int64_t cost =
231
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
232
0
        if (cost > config::recycle_task_threshold_seconds) {
233
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
234
0
                    .tag("instance_id", instance_id)
235
0
                    .tag("task", task_name)
236
0
                    .tag("num_scanned", num_scanned)
237
0
                    .tag("num_recycled", num_recycled);
238
0
        }
239
0
    }
240
51
    return;
241
51
}
242
243
7
Recycler::Recycler(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
244
7
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
245
246
7
    auto s3_producer_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
247
7
                                                               "s3_producer_pool");
248
7
    s3_producer_pool->start();
249
7
    auto recycle_tablet_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
250
7
                                                                  "recycle_tablet_pool");
251
7
    recycle_tablet_pool->start();
252
7
    auto group_recycle_function_pool = std::make_shared<SimpleThreadPool>(
253
7
            config::recycle_pool_parallelism, "group_recycle_function_pool");
254
7
    group_recycle_function_pool->start();
255
7
    _thread_pool_group =
256
7
            RecyclerThreadPoolGroup(std::move(s3_producer_pool), std::move(recycle_tablet_pool),
257
7
                                    std::move(group_recycle_function_pool));
258
259
7
    auto resource_mgr = std::make_shared<ResourceManager>(txn_kv_);
260
7
    txn_lazy_committer_ = std::make_shared<TxnLazyCommitter>(txn_kv_, std::move(resource_mgr));
261
7
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
262
7
}
263
264
7
Recycler::~Recycler() {
265
7
    if (!stopped()) {
266
0
        stop();
267
0
    }
268
7
}
269
270
6
void Recycler::instance_scanner_callback() {
271
    // sleep 60 seconds before scheduling for the launch procedure to complete:
272
    // some bad hdfs connection may cause some log to stdout stderr
273
    // which may pollute .out file and affect the script to check success
274
6
    std::this_thread::sleep_for(
275
6
            std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
276
1.37k
    while (!stopped()) {
277
1.36k
        if (config::enable_recycler) {
278
9
            std::vector<InstanceInfoPB> instances;
279
9
            get_all_instances(txn_kv_.get(), instances);
280
            // TODO(plat1ko): delete job recycle kv of non-existent instances
281
9
            LOG(INFO) << "Recycler get instances: " << [&instances] {
282
9
                std::stringstream ss;
283
40
                for (auto& i : instances) ss << ' ' << i.instance_id();
284
9
                return ss.str();
285
9
            }();
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
Line
Count
Source
281
9
            LOG(INFO) << "Recycler get instances: " << [&instances] {
282
9
                std::stringstream ss;
283
40
                for (auto& i : instances) ss << ' ' << i.instance_id();
284
9
                return ss.str();
285
9
            }();
286
9
            if (!instances.empty()) {
287
                // enqueue instances
288
8
                std::lock_guard lock(mtx_);
289
40
                for (auto& instance : instances) {
290
40
                    if (filter_out_instance(instance.instance_id()) ||
291
40
                        (instance.status() == InstanceInfoPB::DELETED &&
292
40
                         instance.recycle_state() ==
293
10
                                 InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED)) {
294
5
                        continue;
295
5
                    }
296
35
                    auto [_, success] = pending_instance_set_.insert(instance.instance_id());
297
                    // skip instance already in pending queue
298
35
                    if (success) {
299
31
                        pending_instance_queue_.push_back(std::move(instance));
300
31
                    }
301
35
                }
302
8
                pending_instance_cond_.notify_all();
303
8
            }
304
1.36k
        } else {
305
1.36k
            LOG(WARNING) << "Skip recycler since enable_recycler is false";
306
1.36k
        }
307
1.36k
        {
308
1.36k
            std::unique_lock lock(mtx_);
309
1.36k
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
310
2.73k
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
310
2.73k
                               [&]() { return stopped(); });
311
1.36k
        }
312
1.36k
    }
313
6
}
314
315
9
void Recycler::recycle_callback() {
316
40
    while (!stopped()) {
317
38
        InstanceInfoPB instance;
318
38
        {
319
38
            std::unique_lock lock(mtx_);
320
38
            pending_instance_cond_.wait(
321
51
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
321
51
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
322
38
            if (stopped()) {
323
7
                return;
324
7
            }
325
31
            instance = std::move(pending_instance_queue_.front());
326
31
            pending_instance_queue_.pop_front();
327
31
            pending_instance_set_.erase(instance.instance_id());
328
31
        }
329
0
        auto& instance_id = instance.instance_id();
330
31
        {
331
31
            std::lock_guard lock(mtx_);
332
            // skip instance in recycling
333
31
            if (recycling_instance_map_.count(instance_id)) continue;
334
31
        }
335
31
        if (!config::enable_recycler) {
336
1
            LOG(WARNING) << "Skip recycle instance_id=" << instance_id
337
1
                         << " since enable_recycler is false";
338
1
            continue;
339
1
        }
340
30
        auto instance_recycler = std::make_shared<InstanceRecycler>(
341
30
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
342
343
30
        if (int r = instance_recycler->init(); r != 0) {
344
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
345
0
                         << " ret=" << r;
346
0
            continue;
347
0
        }
348
30
        std::string recycle_job_key;
349
30
        job_recycle_key({instance_id}, &recycle_job_key);
350
30
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
351
30
                                               ip_port_, config::recycle_interval_seconds * 1000);
352
30
        if (ret != 0) { // Prepare failed
353
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
354
20
                         << " ret=" << ret;
355
20
            continue;
356
20
        } else {
357
10
            std::lock_guard lock(mtx_);
358
10
            recycling_instance_map_.emplace(instance_id, instance_recycler);
359
10
        }
360
10
        if (stopped()) return;
361
10
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
362
10
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
363
10
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
364
10
        g_bvar_recycler_instance_recycle_task_status.put({"submitted"}, 1);
365
10
        ret = instance_recycler->do_recycle();
366
        // If instance recycler has been aborted, don't finish this job
367
368
10
        if (!instance_recycler->stopped()) {
369
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
370
10
                                        ret == 0, ctime_ms);
371
10
        }
372
10
        if (instance_recycler->stopped() || ret != 0) {
373
0
            g_bvar_recycler_instance_recycle_task_status.put({"error"}, 1);
374
0
        }
375
10
        {
376
10
            std::lock_guard lock(mtx_);
377
10
            recycling_instance_map_.erase(instance_id);
378
10
        }
379
380
10
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
381
10
        auto elpased_ms = now - ctime_ms;
382
10
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
383
10
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
384
10
        g_bvar_recycler_instance_next_ts.put({instance_id},
385
10
                                             now + config::recycle_interval_seconds * 1000);
386
10
        g_bvar_recycler_instance_recycle_task_status.put({"completed"}, 1);
387
10
        LOG(INFO) << "recycle instance done, "
388
10
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
389
10
                  << " now: " << now;
390
391
10
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
392
393
10
        LOG_WARNING("finish recycle instance")
394
10
                .tag("instance_id", instance_id)
395
10
                .tag("cost_ms", elpased_ms);
396
10
    }
397
9
}
398
399
4
void Recycler::lease_recycle_jobs() {
400
54
    while (!stopped()) {
401
50
        std::vector<std::string> instances;
402
50
        instances.reserve(recycling_instance_map_.size());
403
50
        {
404
50
            std::lock_guard lock(mtx_);
405
50
            for (auto& [id, _] : recycling_instance_map_) {
406
30
                instances.push_back(id);
407
30
            }
408
50
        }
409
50
        for (auto& i : instances) {
410
30
            std::string recycle_job_key;
411
30
            job_recycle_key({i}, &recycle_job_key);
412
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
413
30
            if (ret == 1) {
414
0
                std::lock_guard lock(mtx_);
415
0
                if (auto it = recycling_instance_map_.find(i);
416
0
                    it != recycling_instance_map_.end()) {
417
0
                    it->second->stop();
418
0
                }
419
0
            }
420
30
        }
421
50
        {
422
50
            std::unique_lock lock(mtx_);
423
50
            notifier_.wait_for(lock,
424
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
425
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
425
100
                               [&]() { return stopped(); });
426
50
        }
427
50
    }
428
4
}
429
430
4
void Recycler::check_recycle_tasks() {
431
7
    while (!stopped()) {
432
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
433
3
        {
434
3
            std::lock_guard lock(mtx_);
435
3
            recycling_instance_map = recycling_instance_map_;
436
3
        }
437
3
        for (auto& entry : recycling_instance_map) {
438
0
            entry.second->check_recycle_tasks();
439
0
        }
440
441
3
        std::unique_lock lock(mtx_);
442
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
443
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
443
6
                           [&]() { return stopped(); });
444
3
    }
445
4
}
446
447
4
int Recycler::start(brpc::Server* server) {
448
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
449
4
    S3Environment::getInstance();
450
451
4
    if (config::enable_checker) {
452
0
        checker_ = std::make_unique<Checker>(txn_kv_);
453
0
        int ret = checker_->start();
454
0
        std::string msg;
455
0
        if (ret != 0) {
456
0
            msg = "failed to start checker";
457
0
            LOG(ERROR) << msg;
458
0
            std::cerr << msg << std::endl;
459
0
            return ret;
460
0
        }
461
0
        msg = "checker started";
462
0
        LOG(INFO) << msg;
463
0
        std::cout << msg << std::endl;
464
0
    }
465
466
4
    if (server) {
467
        // Add service
468
1
        auto recycler_service =
469
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
470
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
471
1
    }
472
473
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
473
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
474
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
475
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
475
8
        workers_.emplace_back([this] { recycle_callback(); });
476
8
    }
477
478
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
479
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
480
481
4
    if (config::enable_snapshot_data_migrator) {
482
0
        snapshot_data_migrator_ = std::make_shared<SnapshotDataMigrator>(txn_kv_);
483
0
        int ret = snapshot_data_migrator_->start();
484
0
        if (ret != 0) {
485
0
            LOG(ERROR) << "failed to start snapshot data migrator";
486
0
            return ret;
487
0
        }
488
0
        LOG(INFO) << "snapshot data migrator started";
489
0
    }
490
491
4
    if (config::enable_snapshot_chain_compactor) {
492
0
        snapshot_chain_compactor_ = std::make_shared<SnapshotChainCompactor>(txn_kv_);
493
0
        int ret = snapshot_chain_compactor_->start();
494
0
        if (ret != 0) {
495
0
            LOG(ERROR) << "failed to start snapshot chain compactor";
496
0
            return ret;
497
0
        }
498
0
        LOG(INFO) << "snapshot chain compactor started";
499
0
    }
500
501
4
    return 0;
502
4
}
503
504
4
void Recycler::stop() {
505
4
    stopped_ = true;
506
4
    notifier_.notify_all();
507
4
    pending_instance_cond_.notify_all();
508
4
    {
509
4
        std::lock_guard lock(mtx_);
510
4
        for (auto& [_, recycler] : recycling_instance_map_) {
511
0
            recycler->stop();
512
0
        }
513
4
    }
514
20
    for (auto& w : workers_) {
515
20
        if (w.joinable()) w.join();
516
20
    }
517
4
    if (checker_) {
518
0
        checker_->stop();
519
0
    }
520
4
    if (snapshot_data_migrator_) {
521
0
        snapshot_data_migrator_->stop();
522
0
    }
523
4
    if (snapshot_chain_compactor_) {
524
0
        snapshot_chain_compactor_->stop();
525
0
    }
526
4
}
527
528
class InstanceRecycler::InvertedIndexIdCache {
529
public:
530
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
531
154
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
532
533
    // Return 0 if success, 1 if schema kv not found, negative for error
534
    // For the same index_id, schema_version, res, since `get` is not completely atomic
535
    // one thread has not finished inserting, and another thread has not get the index_id and schema_version,
536
    // resulting in repeated addition and inaccuracy.
537
    // however, this approach can reduce the lock range and sacrifice a bit of meta repeated get to improve concurrency performance.
538
    // repeated addition does not affect correctness.
539
28.4k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
540
28.4k
        {
541
28.4k
            std::lock_guard lock(mtx_);
542
28.4k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
543
4.70k
                return 0;
544
4.70k
            }
545
23.7k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
546
23.7k
                it != inverted_index_id_map_.end()) {
547
18.1k
                res = it->second;
548
18.1k
                return 0;
549
18.1k
            }
550
23.7k
        }
551
        // Get schema from kv
552
        // TODO(plat1ko): Single flight
553
5.54k
        std::unique_ptr<Transaction> txn;
554
5.54k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
555
5.54k
        if (err != TxnErrorCode::TXN_OK) {
556
0
            LOG(WARNING) << "failed to create txn, err=" << err;
557
0
            return -1;
558
0
        }
559
5.54k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
560
5.54k
        ValueBuf val_buf;
561
5.54k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
562
5.54k
        if (err != TxnErrorCode::TXN_OK) {
563
504
            LOG(WARNING) << "failed to get schema, err=" << err;
564
504
            return static_cast<int>(err);
565
504
        }
566
5.04k
        doris::TabletSchemaCloudPB schema;
567
5.04k
        if (!parse_schema_value(val_buf, &schema)) {
568
0
            LOG(WARNING) << "malformed schema value, key=" << hex(schema_key);
569
0
            return -1;
570
0
        }
571
5.04k
        if (schema.index_size() > 0) {
572
4.01k
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
573
4.01k
            if (schema.has_inverted_index_storage_format()) {
574
4.00k
                index_format = schema.inverted_index_storage_format();
575
4.00k
            }
576
4.01k
            res.first = index_format;
577
4.01k
            res.second.reserve(schema.index_size());
578
10.0k
            for (auto& i : schema.index()) {
579
10.0k
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
580
10.0k
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
581
10.0k
                }
582
10.0k
            }
583
4.01k
        }
584
5.04k
        insert(index_id, schema_version, res);
585
5.04k
        return 0;
586
5.04k
    }
587
588
    // Empty `ids` means this schema has no inverted index
589
5.04k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
590
5.04k
        if (index_info.second.empty()) {
591
1.03k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
592
1.03k
            std::lock_guard lock(mtx_);
593
1.03k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
594
4.01k
        } else {
595
4.01k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
596
4.01k
            std::lock_guard lock(mtx_);
597
4.01k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
598
4.01k
        }
599
5.04k
    }
600
601
private:
602
    std::string instance_id_;
603
    std::shared_ptr<TxnKv> txn_kv_;
604
605
    std::mutex mtx_;
606
    using Key = std::pair<int64_t, int32_t>; // <index_id, schema_version>
607
    struct HashOfKey {
608
57.2k
        size_t operator()(const Key& key) const {
609
57.2k
            size_t seed = 0;
610
57.2k
            seed = std::hash<int64_t> {}(key.first);
611
57.2k
            seed = std::hash<int32_t> {}(key.second);
612
57.2k
            return seed;
613
57.2k
        }
614
    };
615
    // <index_id, schema_version> -> inverted_index_ids
616
    std::unordered_map<Key, InvertedIndexInfo, HashOfKey> inverted_index_id_map_;
617
    // Store <index_id, schema_version> of schema which doesn't have inverted index
618
    std::unordered_set<Key, HashOfKey> schemas_without_inverted_index_;
619
};
620
621
InstanceRecycler::InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
622
                                   RecyclerThreadPoolGroup thread_pool_group,
623
                                   std::shared_ptr<TxnLazyCommitter> txn_lazy_committer)
624
        : txn_kv_(std::move(txn_kv)),
625
          instance_id_(instance.instance_id()),
626
          instance_info_(instance),
627
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
628
          _thread_pool_group(std::move(thread_pool_group)),
629
          txn_lazy_committer_(std::move(txn_lazy_committer)),
630
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
631
154
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
632
154
    delete_bitmap_lock_white_list_->init();
633
154
    resource_mgr_->init();
634
635
154
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
636
637
    // Since the recycler's resource manager could not be notified when instance info changes,
638
    // we need to refresh the instance info here to ensure the resource manager has the latest info.
639
154
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
640
154
};
641
642
154
InstanceRecycler::~InstanceRecycler() = default;
643
644
129
int InstanceRecycler::init_obj_store_accessors() {
645
129
    for (const auto& obj_info : instance_info_.obj_info()) {
646
86
#ifdef UNIT_TEST
647
86
        auto accessor = std::make_shared<MockAccessor>();
648
#else
649
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
650
        if (!s3_conf) {
651
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
652
            return -1;
653
        }
654
655
        std::shared_ptr<S3Accessor> accessor;
656
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
657
        if (ret != 0) {
658
            LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
659
                         << " resource_id=" << obj_info.id();
660
            return ret;
661
        }
662
#endif
663
86
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
664
86
    }
665
666
129
    return 0;
667
129
}
668
669
129
int InstanceRecycler::init_storage_vault_accessors() {
670
129
    if (instance_info_.resource_ids().empty()) {
671
122
        return 0;
672
122
    }
673
674
7
    FullRangeGetOptions opts(txn_kv_);
675
7
    opts.prefetch = true;
676
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
677
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
678
679
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
680
18
        auto [k, v] = *kv;
681
18
        StorageVaultPB vault;
682
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
683
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
684
0
            return -1;
685
0
        }
686
18
        std::string recycler_storage_vault_white_list = accumulate(
687
18
                config::recycler_storage_vault_white_list.begin(),
688
18
                config::recycler_storage_vault_white_list.end(), std::string(),
689
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
689
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
690
18
        LOG_INFO("config::recycler_storage_vault_white_list")
691
18
                .tag("", recycler_storage_vault_white_list);
692
18
        if (!config::recycler_storage_vault_white_list.empty()) {
693
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
694
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
695
8
                it == config::recycler_storage_vault_white_list.end()) {
696
2
                LOG_WARNING(
697
2
                        "failed to init accessor for vault because this vault is not in "
698
2
                        "config::recycler_storage_vault_white_list. ")
699
2
                        .tag(" vault name:", vault.name())
700
2
                        .tag(" config::recycler_storage_vault_white_list:",
701
2
                             recycler_storage_vault_white_list);
702
2
                continue;
703
2
            }
704
8
        }
705
16
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
706
16
                                 &accessor_map_, &vault);
707
16
        if (vault.has_hdfs_info()) {
708
9
#ifdef ENABLE_HDFS_STORAGE_VAULT
709
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
710
9
            int ret = accessor->init();
711
9
            if (ret != 0) {
712
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
713
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
714
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
715
4
                continue;
716
4
            }
717
5
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
718
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
719
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
720
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
721
#else
722
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
723
                       << "but HDFS storage vaults were detected";
724
#endif
725
7
        } else if (vault.has_obj_info()) {
726
            // TODO: Propagate object storage session tokens to Recycler in a follow-up PR.
727
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
728
7
            if (!s3_conf) {
729
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
730
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
731
1
                continue;
732
1
            }
733
734
6
            std::shared_ptr<S3Accessor> accessor;
735
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
736
6
            if (ret != 0) {
737
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
738
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
739
0
                             << " ret=" << ret
740
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
741
0
                continue;
742
0
            }
743
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
744
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
745
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
746
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
747
6
        }
748
16
    }
749
750
7
    if (!it->is_valid()) {
751
0
        LOG_WARNING("failed to get storage vault kv");
752
0
        return -1;
753
0
    }
754
755
7
    if (accessor_map_.empty()) {
756
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
757
1
        return -2;
758
1
    }
759
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
760
6
             instance_id_);
761
762
6
    return 0;
763
7
}
764
765
130
int InstanceRecycler::init() {
766
130
    if (instance_info_.status() == InstanceInfoPB::DELETED &&
767
130
        (instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING ||
768
4
         instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED)) {
769
1
        return 0;
770
1
    }
771
772
129
    int ret = init_obj_store_accessors();
773
129
    if (ret != 0) {
774
0
        return ret;
775
0
    }
776
777
129
    return init_storage_vault_accessors();
778
129
}
779
780
template <typename... Func>
781
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
782
120
    return [funcs...]() {
783
120
        return [](std::initializer_list<int> ret_vals) {
784
120
            int i = 0;
785
140
            for (int ret : ret_vals) {
786
140
                if (ret != 0) {
787
0
                    i = ret;
788
0
                }
789
140
            }
790
120
            return i;
791
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
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
0
                    i = ret;
788
0
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
0
                    i = ret;
788
0
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
20
            for (int ret : ret_vals) {
786
20
                if (ret != 0) {
787
0
                    i = ret;
788
0
                }
789
20
            }
790
10
            return i;
791
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
0
                    i = ret;
788
0
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
0
                    i = ret;
788
0
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
0
                    i = ret;
788
0
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
20
            for (int ret : ret_vals) {
786
20
                if (ret != 0) {
787
0
                    i = ret;
788
0
                }
789
20
            }
790
10
            return i;
791
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
0
                    i = ret;
788
0
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
0
                    i = ret;
788
0
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
0
                    i = ret;
788
0
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
0
                    i = ret;
788
0
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
0
                    i = ret;
788
0
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
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
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
793
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
781
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
793
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
781
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
793
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
781
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
793
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
781
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
793
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
781
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
793
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
781
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
793
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
781
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
793
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
781
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
793
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
781
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
793
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
781
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
793
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
781
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
793
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
781
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
782
10
    return [funcs...]() {
783
10
        return [](std::initializer_list<int> ret_vals) {
784
10
            int i = 0;
785
10
            for (int ret : ret_vals) {
786
10
                if (ret != 0) {
787
10
                    i = ret;
788
10
                }
789
10
            }
790
10
            return i;
791
10
        }({funcs()...});
792
10
    };
793
10
}
794
795
11
int InstanceRecycler::do_recycle() {
796
11
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
797
11
    tablet_metrics_context_.reset();
798
11
    segment_metrics_context_.reset();
799
11
    DORIS_CLOUD_DEFER {
800
11
        tablet_metrics_context_.finish_report();
801
11
        segment_metrics_context_.finish_report();
802
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
799
11
    DORIS_CLOUD_DEFER {
800
11
        tablet_metrics_context_.finish_report();
801
11
        segment_metrics_context_.finish_report();
802
11
    };
803
11
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
804
1
        int res = recycle_cluster_snapshots();
805
1
        if (res != 0) {
806
0
            return -1;
807
0
        }
808
1
        return recycle_deleted_instance();
809
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
810
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
811
10
                                        fmt::format("instance id {}", instance_id_),
812
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
812
120
                                        [](int r) { return r != 0; });
813
10
        sync_executor
814
10
                .add(task_wrapper(
815
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
815
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
816
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
816
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
817
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
818
                                   // becase they may both recycle the same set of tablets
819
                        // recycle dropped table or idexes(mv, rollup)
820
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
820
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
821
                        // recycle dropped partitions
822
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
822
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
823
10
                .add(task_wrapper(
824
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
824
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
825
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
825
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
826
10
                .add(task_wrapper(
827
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
827
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
828
10
                .add(task_wrapper(
829
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
829
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
830
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
830
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
831
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
831
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
832
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
832
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
833
10
                .add(task_wrapper(
834
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
834
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
835
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
835
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
836
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
836
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
837
10
        bool finished = true;
838
10
        std::vector<int> rets = sync_executor.when_all(&finished);
839
120
        for (int ret : rets) {
840
120
            if (ret != 0) {
841
0
                return ret;
842
0
            }
843
120
        }
844
10
        return finished ? 0 : -1;
845
10
    } else {
846
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
847
0
                     << " instance_id=" << instance_id_;
848
0
        return -1;
849
0
    }
850
11
}
851
852
/**
853
* 1. delete all remote data
854
* 2. delete all kv
855
*/
856
13
int InstanceRecycler::recycle_deleted_instance() {
857
13
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
858
859
13
    int ret = 0;
860
13
    auto start_time = steady_clock::now();
861
13
    const auto recycle_state = instance_info_.recycle_state();
862
863
13
    if (recycle_state == InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
864
4
        return 0;
865
4
    }
866
867
9
    DORIS_CLOUD_DEFER {
868
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
869
9
        if (ret != 0) {
870
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
871
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
872
0
                         << "s, instance_id=" << instance_id_;
873
9
        } else if (recycle_state ==
874
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
875
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
876
0
                      << "s, instance_id=" << instance_id_;
877
9
        } else {
878
9
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
879
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
880
9
                      << "s, instance_id=" << instance_id_;
881
9
        }
882
9
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
867
9
    DORIS_CLOUD_DEFER {
868
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
869
9
        if (ret != 0) {
870
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
871
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
872
0
                         << "s, instance_id=" << instance_id_;
873
9
        } else if (recycle_state ==
874
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
875
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
876
0
                      << "s, instance_id=" << instance_id_;
877
9
        } else {
878
9
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
879
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
880
9
                      << "s, instance_id=" << instance_id_;
881
9
        }
882
9
    };
883
884
9
    switch (recycle_state) {
885
6
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING:
886
6
        ret = recycle_deleted_instance_data();
887
6
        break;
888
3
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING:
889
3
        ret = recycle_deleted_instance_metadata();
890
3
        break;
891
0
    default:
892
0
        LOG_WARNING("invalid instance recycle state")
893
0
                .tag("instance_id", instance_id_)
894
0
                .tag("recycle_state", instance_info_.recycle_state());
895
0
        ret = -1;
896
0
        break;
897
9
    }
898
899
9
    return ret;
900
9
}
901
902
6
int InstanceRecycler::recycle_deleted_instance_data() {
903
6
    int ret = 0;
904
905
    // Step 1: Recycle tmp rowsets (contains ref count but txn is not committed)
906
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
907
6
        int res = recycle_tmp_rowsets();
908
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
909
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
910
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
911
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
912
            // and cannot be recycled.
913
0
            res = recycle_tmp_rowsets();
914
0
        }
915
6
        return res;
916
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
Line
Count
Source
906
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
907
6
        int res = recycle_tmp_rowsets();
908
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
909
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
910
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
911
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
912
            // and cannot be recycled.
913
0
            res = recycle_tmp_rowsets();
914
0
        }
915
6
        return res;
916
6
    };
917
918
6
    if (recycle_tmp_rowsets_with_mark_delete_enabled() != 0) {
919
0
        LOG_WARNING("failed to recycle tmp rowsets").tag("instance_id", instance_id_);
920
0
        return -1;
921
0
    }
922
923
    // Step 2: Recycle versioned rowsets in recycle space (already marked for deletion)
924
6
    if (recycle_versioned_rowsets() != 0) {
925
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
926
0
        return -1;
927
0
    }
928
929
    // Step 3: Recycle operation logs (can recycle logs not referenced by snapshots)
930
6
    if (recycle_operation_logs() != 0) {
931
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
932
0
        return -1;
933
0
    }
934
935
    // Step 4: Check if there are still cluster snapshots
936
6
    bool has_snapshots = false;
937
6
    if (has_cluster_snapshots(&has_snapshots) != 0) {
938
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
939
0
        return -1;
940
6
    } else if (has_snapshots) {
941
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
942
1
        return 0;
943
1
    }
944
945
5
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
946
5
                            instance_info().snapshot_switch_status() !=
947
1
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
948
5
    if (snapshot_enabled) {
949
1
        bool has_unrecycled_rowsets = false;
950
1
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
951
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
952
0
            return -1;
953
1
        } else if (has_unrecycled_rowsets) {
954
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
955
0
                    .tag("instance_id", instance_id_);
956
0
            return ret;
957
0
        }
958
4
    } else { // delete all remote data if snapshot is disabled
959
4
        for (auto& [_, accessor] : accessor_map_) {
960
4
            if (stopped()) {
961
0
                return ret;
962
0
            }
963
964
4
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
965
4
            int del_ret = accessor->delete_all();
966
4
            if (del_ret == 0) {
967
4
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
968
4
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
969
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
970
                // so the recycling has been successful.
971
0
                ret = -1;
972
0
            }
973
4
        }
974
975
4
        if (ret != 0) {
976
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
977
0
            return ret;
978
0
        }
979
4
    }
980
981
5
    if (update_instance_recycle_state(
982
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING,
983
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) != 0) {
984
0
        return -1;
985
0
    }
986
987
5
    return 0;
988
5
}
989
990
6
int InstanceRecycler::recycle_deleted_instance_metadata() {
991
    // Check successor instance, if exists, skip deleting kv because successor instance may still need the data in kv
992
6
    if (instance_info_.has_successor_instance_id() &&
993
6
        !instance_info_.successor_instance_id().empty()) {
994
3
        std::string key = instance_key(instance_info_.successor_instance_id());
995
3
        std::unique_ptr<Transaction> txn;
996
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
997
3
        if (err != TxnErrorCode::TXN_OK) {
998
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_
999
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1000
0
                         << " err=" << err;
1001
0
            return -1;
1002
0
        }
1003
1004
3
        InstanceInfoPB successor_instance;
1005
3
        std::string value;
1006
3
        err = txn->get(key, &value);
1007
3
        if (err == TxnErrorCode::TXN_OK) {
1008
2
            InstanceInfoPB successor_instance;
1009
2
            if (!successor_instance.ParseFromString(value)) {
1010
0
                LOG(WARNING) << "failed to parse successor instance, instance_id=" << instance_id_
1011
0
                             << " successor_instance_id=" << instance_info_.successor_instance_id();
1012
0
                return -1;
1013
0
            }
1014
2
            if (successor_instance.status() != InstanceInfoPB::DELETED ||
1015
2
                successor_instance.recycle_state() !=
1016
2
                        InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1017
1
                LOG(INFO) << "instance successor has not completed recycling, skip deleting kv,"
1018
1
                          << " instance_id=" << instance_id_
1019
1
                          << " successor_instance_id=" << instance_info_.successor_instance_id()
1020
1
                          << " successor_status=" << successor_instance.status()
1021
1
                          << " successor_recycled_state=" << successor_instance.recycle_state();
1022
1
                return 0;
1023
1
            }
1024
2
        } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1025
0
            LOG(WARNING) << "failed to get successor instance, instance_id=" << instance_id_
1026
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1027
0
                         << " err=" << err;
1028
1029
0
            return -1;
1030
0
        }
1031
3
    }
1032
1033
    // delete all kv
1034
5
    std::unique_ptr<Transaction> txn;
1035
5
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1036
5
    if (err != TxnErrorCode::TXN_OK) {
1037
0
        LOG(WARNING) << "failed to create txn";
1038
0
        return -1;
1039
0
    }
1040
5
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
1041
    // delete kv before deleting objects to prevent the checker from misjudging data loss
1042
5
    std::string start_txn_key = txn_key_prefix(instance_id_);
1043
5
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
1044
5
    txn->remove(start_txn_key, end_txn_key);
1045
5
    std::string start_version_key = version_key_prefix(instance_id_);
1046
5
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
1047
5
    txn->remove(start_version_key, end_version_key);
1048
5
    std::string start_meta_key = meta_key_prefix(instance_id_);
1049
5
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
1050
5
    txn->remove(start_meta_key, end_meta_key);
1051
5
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
1052
5
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
1053
5
    txn->remove(start_recycle_key, end_recycle_key);
1054
5
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
1055
5
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1056
5
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
1057
5
    std::string start_copy_key = copy_key_prefix(instance_id_);
1058
5
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
1059
5
    txn->remove(start_copy_key, end_copy_key);
1060
    // should not remove job key range, because we need to reserve job recycle kv
1061
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
1062
5
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
1063
5
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1064
5
    txn->remove(start_job_tablet_key, end_job_tablet_key);
1065
5
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
1066
5
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
1067
5
    std::string start_vault_key = storage_vault_key(key_info0);
1068
5
    std::string end_vault_key = storage_vault_key(key_info1);
1069
5
    txn->remove(start_vault_key, end_vault_key);
1070
5
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
1071
5
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
1072
5
    txn->remove(versioned_version_key_start, versioned_version_key_end);
1073
5
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
1074
5
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
1075
5
    txn->remove(versioned_index_key_start, versioned_index_key_end);
1076
5
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
1077
5
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
1078
5
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
1079
5
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
1080
5
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
1081
5
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
1082
5
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
1083
5
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
1084
5
    txn->remove(versioned_data_key_start, versioned_data_key_end);
1085
5
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
1086
5
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
1087
5
    txn->remove(versioned_log_key_start, versioned_log_key_end);
1088
1089
    // Updating the recycle state also commits this transaction, making the metadata deletions
1090
    // and state transition atomic.
1091
5
    if (update_instance_recycle_state(
1092
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING,
1093
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED, txn.get()) != 0) {
1094
0
        return -1;
1095
0
    }
1096
1097
5
    return 0;
1098
5
}
1099
1100
0
int InstanceRecycler::remove_instance_key() {
1101
0
    std::unique_ptr<Transaction> txn;
1102
0
    std::string key = instance_key(instance_info_.instance_id());
1103
0
    std::string value;
1104
0
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1105
0
    if (err != TxnErrorCode::TXN_OK) {
1106
0
        LOG(WARNING) << "failed to create txn";
1107
0
        return -1;
1108
0
    }
1109
1110
0
    err = txn->get(key, &value);
1111
0
    if (err != TxnErrorCode::TXN_OK) {
1112
0
        LOG(WARNING) << "failed to get instance, instance_id=" << instance_info_.instance_id()
1113
0
                     << ", err=" << err;
1114
0
        return -1;
1115
0
    }
1116
1117
0
    InstanceInfoPB instance;
1118
0
    if (!instance.ParseFromString(value)) {
1119
0
        LOG(WARNING) << "malformed instance info, key=" << key;
1120
0
        return -1;
1121
0
    }
1122
1123
0
    if (instance.status() != InstanceInfoPB::DELETED) {
1124
0
        LOG(WARNING) << "failed to remove instance key, instance is not deleted, instance_id="
1125
0
                     << instance_id_ << ", status=" << instance.status();
1126
0
        return -1;
1127
0
    }
1128
1129
0
    if (instance.recycle_state() != INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1130
0
        LOG(WARNING) << "failed to remove instance key, invalid recycle state, instance_id="
1131
0
                     << instance_id_
1132
0
                     << ", current_state=" << InstanceRecycleState_Name(instance.recycle_state())
1133
0
                     << ", expected_state="
1134
0
                     << InstanceRecycleState_Name(INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1135
0
        return -1;
1136
0
    }
1137
1138
0
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1139
0
    txn->remove(key);
1140
0
    err = txn->commit();
1141
0
    if (err != TxnErrorCode::TXN_OK) {
1142
0
        LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
1143
0
                     << " err=" << err;
1144
0
        return -1;
1145
0
    }
1146
0
    return 0;
1147
0
}
1148
1149
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState expected_state,
1150
7
                                                    InstanceRecycleState target_state) {
1151
7
    std::unique_ptr<Transaction> txn;
1152
7
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1153
7
    if (err != TxnErrorCode::TXN_OK) {
1154
0
        LOG(WARNING) << "failed to create txn";
1155
0
        return -1;
1156
0
    }
1157
7
    return update_instance_recycle_state(expected_state, target_state, txn.get());
1158
7
}
1159
1160
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState current_state,
1161
                                                    InstanceRecycleState target_state,
1162
12
                                                    Transaction* txn) {
1163
12
    const bool valid_transition =
1164
12
            (current_state == INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING &&
1165
12
             target_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) ||
1166
12
            (current_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING &&
1167
6
             target_state == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1168
1169
12
    if (!valid_transition) {
1170
1
        LOG_WARNING("invalid instance recycled state transition")
1171
1
                .tag("instance_id", instance_id_)
1172
1
                .tag("current_state", InstanceRecycleState_Name(current_state))
1173
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1174
1
        return -1;
1175
1
    }
1176
1177
11
    std::string key = instance_key({instance_id_});
1178
11
    std::string value;
1179
11
    TxnErrorCode err = txn->get(key, &value);
1180
11
    if (err != TxnErrorCode::TXN_OK) {
1181
0
        LOG_WARNING("failed to get instance when updating instance recycled state")
1182
0
                .tag("instance_id", instance_id_)
1183
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1184
0
                .tag("target_state", InstanceRecycleState_Name(target_state))
1185
0
                .tag("err", err);
1186
0
        return -1;
1187
0
    }
1188
1189
11
    InstanceInfoPB instance;
1190
11
    if (!instance.ParseFromString(value)) {
1191
0
        LOG_WARNING("failed to parse InstanceInfoPB when updating instance recycled state")
1192
0
                .tag("instance_id", instance_id_)
1193
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1194
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1195
0
        return -1;
1196
0
    }
1197
11
    if (instance.status() != InstanceInfoPB::DELETED) {
1198
0
        LOG_WARNING("instance is not deleted when updating instance recycled state")
1199
0
                .tag("instance_id", instance_id_)
1200
0
                .tag("status", instance.status())
1201
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1202
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1203
0
        return -1;
1204
0
    }
1205
11
    if (instance.recycle_state() != current_state) {
1206
1
        LOG_WARNING("instance recycled state changed before update")
1207
1
                .tag("instance_id", instance_id_)
1208
1
                .tag("current_state", InstanceRecycleState_Name(instance.recycle_state()))
1209
1
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1210
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1211
1
        return -1;
1212
1
    }
1213
1214
10
    instance.set_recycle_state(target_state);
1215
10
    instance.set_recycle_state_update_time_ms(
1216
10
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count());
1217
10
    if (!instance.SerializeToString(&value)) {
1218
0
        LOG_WARNING("failed to serialize InstanceInfoPB when updating instance recycled state")
1219
0
                .tag("instance_id", instance_id_)
1220
0
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1221
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1222
0
        return -1;
1223
0
    }
1224
1225
10
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1226
10
    txn->put(key, value);
1227
10
    err = txn->commit();
1228
10
    if (err != TxnErrorCode::TXN_OK) {
1229
0
        LOG(WARNING) << "failed to commit fdb txn when updating instance recycled state, "
1230
0
                     << "instance_id=" << instance_id_ << ", err=" << err;
1231
0
        return -1;
1232
0
    }
1233
1234
10
    instance_info_.Swap(&instance);
1235
10
    LOG_INFO("updated instance recycled state")
1236
10
            .tag("instance_id", instance_id_)
1237
10
            .tag("recycle_state", InstanceRecycleState_Name(target_state));
1238
10
    return 0;
1239
10
}
1240
1241
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
1242
9
                                          bool* exists, PackedFileRecycleStats* stats) {
1243
9
    if (exists == nullptr) {
1244
0
        return -1;
1245
0
    }
1246
9
    *exists = false;
1247
1248
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
1249
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1250
9
    std::string scan_begin = begin;
1251
1252
9
    while (true) {
1253
9
        std::unique_ptr<RangeGetIterator> it_range;
1254
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
1255
9
        if (get_ret < 0) {
1256
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1257
0
                    .tag("instance_id", instance_id_)
1258
0
                    .tag("tablet_id", tablet_id)
1259
0
                    .tag("ret", get_ret);
1260
0
            return -1;
1261
0
        }
1262
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1263
6
            return 0;
1264
6
        }
1265
1266
3
        std::string last_key;
1267
3
        while (it_range->has_next()) {
1268
3
            auto [k, v] = it_range->next();
1269
3
            last_key.assign(k.data(), k.size());
1270
3
            doris::RowsetMetaCloudPB rowset_meta;
1271
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1272
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1273
0
                        .tag("instance_id", instance_id_)
1274
0
                        .tag("tablet_id", tablet_id)
1275
0
                        .tag("key", hex(k));
1276
0
                continue;
1277
0
            }
1278
3
            if (stats) {
1279
3
                ++stats->rowset_scan_count;
1280
3
            }
1281
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1282
3
                *exists = true;
1283
3
                return 0;
1284
3
            }
1285
3
        }
1286
1287
0
        if (!it_range->more()) {
1288
0
            return 0;
1289
0
        }
1290
1291
        // Continue scanning from the next key to keep each transaction short.
1292
0
        scan_begin = std::move(last_key);
1293
0
        scan_begin.push_back('\x00');
1294
0
    }
1295
9
}
1296
1297
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1298
                                                          const std::string& rowset_id,
1299
                                                          int64_t txn_id, bool* recycle_exists,
1300
11
                                                          bool* tmp_exists) {
1301
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1302
0
        return -1;
1303
0
    }
1304
11
    *recycle_exists = false;
1305
11
    *tmp_exists = false;
1306
1307
11
    if (txn_id <= 0) {
1308
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1309
0
                .tag("instance_id", instance_id_)
1310
0
                .tag("tablet_id", tablet_id)
1311
0
                .tag("rowset_id", rowset_id)
1312
0
                .tag("txn_id", txn_id);
1313
0
        return -1;
1314
0
    }
1315
1316
11
    std::unique_ptr<Transaction> txn;
1317
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1318
11
    if (err != TxnErrorCode::TXN_OK) {
1319
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1320
0
                .tag("instance_id", instance_id_)
1321
0
                .tag("tablet_id", tablet_id)
1322
0
                .tag("rowset_id", rowset_id)
1323
0
                .tag("txn_id", txn_id)
1324
0
                .tag("err", err);
1325
0
        return -1;
1326
0
    }
1327
1328
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1329
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1330
11
    if (ret == TxnErrorCode::TXN_OK) {
1331
1
        *recycle_exists = true;
1332
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1333
0
        LOG_WARNING("failed to check recycle rowset existence")
1334
0
                .tag("instance_id", instance_id_)
1335
0
                .tag("tablet_id", tablet_id)
1336
0
                .tag("rowset_id", rowset_id)
1337
0
                .tag("key", hex(recycle_key))
1338
0
                .tag("err", ret);
1339
0
        return -1;
1340
0
    }
1341
1342
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1343
11
    ret = key_exists(txn.get(), tmp_key, true);
1344
11
    if (ret == TxnErrorCode::TXN_OK) {
1345
1
        *tmp_exists = true;
1346
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1347
0
        LOG_WARNING("failed to check tmp rowset existence")
1348
0
                .tag("instance_id", instance_id_)
1349
0
                .tag("tablet_id", tablet_id)
1350
0
                .tag("txn_id", txn_id)
1351
0
                .tag("key", hex(tmp_key))
1352
0
                .tag("err", ret);
1353
0
        return -1;
1354
0
    }
1355
1356
11
    return 0;
1357
11
}
1358
1359
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1360
8
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1361
8
    if (!hint.empty()) {
1362
8
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1363
8
            return {hint, it->second};
1364
8
        }
1365
8
    }
1366
1367
0
    return {"", nullptr};
1368
8
}
1369
1370
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1371
                                               const std::string& packed_file_path,
1372
3
                                               PackedFileRecycleStats* stats) {
1373
3
    bool local_changed = false;
1374
3
    int64_t left_num = 0;
1375
3
    int64_t left_bytes = 0;
1376
3
    bool all_small_files_confirmed = true;
1377
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1378
1379
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1380
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1381
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1382
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1383
14
        LOG_INFO("packed slice correction status")
1384
14
                .tag("instance_id", instance_id_)
1385
14
                .tag("packed_file_path", packed_file_path)
1386
14
                .tag("small_file_path", file.path())
1387
14
                .tag("tablet_id", tablet_id)
1388
14
                .tag("rowset_id", rowset_id)
1389
14
                .tag("txn_id", txn_id)
1390
14
                .tag("size", file.size())
1391
14
                .tag("deleted", file.deleted())
1392
14
                .tag("corrected", file.corrected())
1393
14
                .tag("confirmed_this_round", confirmed_this_round);
1394
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
1379
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1380
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1381
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1382
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1383
14
        LOG_INFO("packed slice correction status")
1384
14
                .tag("instance_id", instance_id_)
1385
14
                .tag("packed_file_path", packed_file_path)
1386
14
                .tag("small_file_path", file.path())
1387
14
                .tag("tablet_id", tablet_id)
1388
14
                .tag("rowset_id", rowset_id)
1389
14
                .tag("txn_id", txn_id)
1390
14
                .tag("size", file.size())
1391
14
                .tag("deleted", file.deleted())
1392
14
                .tag("corrected", file.corrected())
1393
14
                .tag("confirmed_this_round", confirmed_this_round);
1394
14
    };
1395
1396
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1397
14
        auto* small_file = packed_info->mutable_slices(i);
1398
14
        if (small_file->deleted()) {
1399
3
            log_small_file_status(*small_file, small_file->corrected());
1400
3
            continue;
1401
3
        }
1402
1403
11
        if (small_file->corrected()) {
1404
0
            left_num++;
1405
0
            left_bytes += small_file->size();
1406
0
            log_small_file_status(*small_file, true);
1407
0
            continue;
1408
0
        }
1409
1410
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1411
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1412
0
                    .tag("instance_id", instance_id_)
1413
0
                    .tag("small_file_path", small_file->path())
1414
0
                    .tag("index", i);
1415
0
            return -1;
1416
0
        }
1417
1418
11
        int64_t tablet_id = small_file->tablet_id();
1419
11
        const std::string& rowset_id = small_file->rowset_id();
1420
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1421
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1422
0
                    .tag("instance_id", instance_id_)
1423
0
                    .tag("small_file_path", small_file->path())
1424
0
                    .tag("index", i)
1425
0
                    .tag("tablet_id", tablet_id)
1426
0
                    .tag("rowset_id", rowset_id)
1427
0
                    .tag("has_txn_id", small_file->has_txn_id())
1428
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1429
0
            return -1;
1430
0
        }
1431
11
        int64_t txn_id = small_file->txn_id();
1432
11
        bool recycle_exists = false;
1433
11
        bool tmp_exists = false;
1434
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1435
11
                                                &tmp_exists) != 0) {
1436
0
            return -1;
1437
0
        }
1438
1439
11
        bool small_file_confirmed = false;
1440
11
        if (tmp_exists) {
1441
1
            left_num++;
1442
1
            left_bytes += small_file->size();
1443
1
            small_file_confirmed = true;
1444
10
        } else if (recycle_exists) {
1445
1
            left_num++;
1446
1
            left_bytes += small_file->size();
1447
            // keep small_file_confirmed=false so the packed file remains uncorrected
1448
9
        } else {
1449
9
            bool rowset_exists = false;
1450
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1451
0
                return -1;
1452
0
            }
1453
1454
9
            if (!rowset_exists) {
1455
6
                if (!small_file->deleted()) {
1456
6
                    small_file->set_deleted(true);
1457
6
                    local_changed = true;
1458
6
                }
1459
6
                if (!small_file->corrected()) {
1460
6
                    small_file->set_corrected(true);
1461
6
                    local_changed = true;
1462
6
                }
1463
6
                small_file_confirmed = true;
1464
6
            } else {
1465
3
                left_num++;
1466
3
                left_bytes += small_file->size();
1467
3
                small_file_confirmed = true;
1468
3
            }
1469
9
        }
1470
1471
11
        if (!small_file_confirmed) {
1472
1
            all_small_files_confirmed = false;
1473
1
        }
1474
1475
11
        if (small_file->corrected() != small_file_confirmed) {
1476
4
            small_file->set_corrected(small_file_confirmed);
1477
4
            local_changed = true;
1478
4
        }
1479
1480
11
        log_small_file_status(*small_file, small_file_confirmed);
1481
11
    }
1482
1483
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1484
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1485
3
        local_changed = true;
1486
3
    }
1487
3
    if (packed_info->ref_cnt() != left_num) {
1488
3
        auto old_ref_cnt = packed_info->ref_cnt();
1489
3
        packed_info->set_ref_cnt(left_num);
1490
3
        LOG_INFO("corrected packed file ref count")
1491
3
                .tag("instance_id", instance_id_)
1492
3
                .tag("resource_id", packed_info->resource_id())
1493
3
                .tag("packed_file_path", packed_file_path)
1494
3
                .tag("old_ref_cnt", old_ref_cnt)
1495
3
                .tag("new_ref_cnt", left_num);
1496
3
        local_changed = true;
1497
3
    }
1498
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1499
2
        packed_info->set_corrected(all_small_files_confirmed);
1500
2
        local_changed = true;
1501
2
    }
1502
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1503
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1504
1
        local_changed = true;
1505
1
    }
1506
1507
3
    if (changed != nullptr) {
1508
3
        *changed = local_changed;
1509
3
    }
1510
3
    return 0;
1511
3
}
1512
1513
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1514
                                                 const std::string& packed_file_path,
1515
3
                                                 PackedFileRecycleStats* stats) {
1516
3
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1517
3
    bool correction_ok = false;
1518
3
    cloud::PackedFileInfoPB packed_info;
1519
1520
3
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1521
3
        if (stopped()) {
1522
0
            LOG_WARNING("recycler stopped before processing packed file")
1523
0
                    .tag("instance_id", instance_id_)
1524
0
                    .tag("packed_file_path", packed_file_path)
1525
0
                    .tag("attempt", attempt);
1526
0
            return -1;
1527
0
        }
1528
1529
3
        std::unique_ptr<Transaction> txn;
1530
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1531
3
        if (err != TxnErrorCode::TXN_OK) {
1532
0
            LOG_WARNING("failed to create txn when processing packed file")
1533
0
                    .tag("instance_id", instance_id_)
1534
0
                    .tag("packed_file_path", packed_file_path)
1535
0
                    .tag("attempt", attempt)
1536
0
                    .tag("err", err);
1537
0
            return -1;
1538
0
        }
1539
1540
3
        std::string packed_val;
1541
3
        err = txn->get(packed_key, &packed_val);
1542
3
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1543
0
            return 0;
1544
0
        }
1545
3
        if (err != TxnErrorCode::TXN_OK) {
1546
0
            LOG_WARNING("failed to get packed file kv")
1547
0
                    .tag("instance_id", instance_id_)
1548
0
                    .tag("packed_file_path", packed_file_path)
1549
0
                    .tag("attempt", attempt)
1550
0
                    .tag("err", err);
1551
0
            return -1;
1552
0
        }
1553
1554
3
        if (!packed_info.ParseFromString(packed_val)) {
1555
0
            LOG_WARNING("failed to parse packed file info")
1556
0
                    .tag("instance_id", instance_id_)
1557
0
                    .tag("packed_file_path", packed_file_path)
1558
0
                    .tag("attempt", attempt);
1559
0
            return -1;
1560
0
        }
1561
1562
3
        int64_t now_sec = ::time(nullptr);
1563
3
        bool corrected = packed_info.corrected();
1564
3
        bool due = config::force_immediate_recycle ||
1565
3
                   now_sec - packed_info.created_at_sec() >=
1566
3
                           config::packed_file_correction_delay_seconds;
1567
1568
3
        if (!corrected && due) {
1569
3
            bool changed = false;
1570
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1571
0
                LOG_WARNING("correct_packed_file_info failed")
1572
0
                        .tag("instance_id", instance_id_)
1573
0
                        .tag("packed_file_path", packed_file_path)
1574
0
                        .tag("attempt", attempt);
1575
0
                return -1;
1576
0
            }
1577
3
            if (changed) {
1578
3
                std::string updated;
1579
3
                if (!packed_info.SerializeToString(&updated)) {
1580
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1581
0
                            .tag("instance_id", instance_id_)
1582
0
                            .tag("packed_file_path", packed_file_path)
1583
0
                            .tag("attempt", attempt);
1584
0
                    return -1;
1585
0
                }
1586
3
                txn->put(packed_key, updated);
1587
3
                err = txn->commit();
1588
3
                if (err == TxnErrorCode::TXN_OK) {
1589
3
                    if (stats) {
1590
3
                        ++stats->num_corrected;
1591
3
                    }
1592
3
                } else {
1593
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1594
0
                        LOG_WARNING(
1595
0
                                "failed to commit correction for packed file due to conflict, "
1596
0
                                "retrying")
1597
0
                                .tag("instance_id", instance_id_)
1598
0
                                .tag("packed_file_path", packed_file_path)
1599
0
                                .tag("attempt", attempt);
1600
0
                        sleep_for_packed_file_retry();
1601
0
                        packed_info.Clear();
1602
0
                        continue;
1603
0
                    }
1604
0
                    LOG_WARNING("failed to commit correction for packed file")
1605
0
                            .tag("instance_id", instance_id_)
1606
0
                            .tag("packed_file_path", packed_file_path)
1607
0
                            .tag("attempt", attempt)
1608
0
                            .tag("err", err);
1609
0
                    return -1;
1610
0
                }
1611
3
            }
1612
3
        }
1613
1614
3
        correction_ok = true;
1615
3
        break;
1616
3
    }
1617
1618
3
    if (!correction_ok) {
1619
0
        return -1;
1620
0
    }
1621
1622
3
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1623
3
          packed_info.ref_cnt() == 0)) {
1624
2
        return 0;
1625
2
    }
1626
1627
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1628
0
        LOG_WARNING("packed file missing resource id when recycling")
1629
0
                .tag("instance_id", instance_id_)
1630
0
                .tag("packed_file_path", packed_file_path);
1631
0
        return -1;
1632
0
    }
1633
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1634
1
    if (!accessor) {
1635
0
        LOG_WARNING("no accessor available to delete packed file")
1636
0
                .tag("instance_id", instance_id_)
1637
0
                .tag("packed_file_path", packed_file_path)
1638
0
                .tag("resource_id", packed_info.resource_id());
1639
0
        return -1;
1640
0
    }
1641
1
    int del_ret = accessor->delete_file(packed_file_path);
1642
1
    if (del_ret != 0 && del_ret != 1) {
1643
0
        LOG_WARNING("failed to delete packed file")
1644
0
                .tag("instance_id", instance_id_)
1645
0
                .tag("packed_file_path", packed_file_path)
1646
0
                .tag("resource_id", resource_id)
1647
0
                .tag("ret", del_ret);
1648
0
        return -1;
1649
0
    }
1650
1
    if (del_ret == 1) {
1651
0
        LOG_INFO("packed file already removed")
1652
0
                .tag("instance_id", instance_id_)
1653
0
                .tag("packed_file_path", packed_file_path)
1654
0
                .tag("resource_id", resource_id);
1655
1
    } else {
1656
1
        LOG_INFO("deleted packed file")
1657
1
                .tag("instance_id", instance_id_)
1658
1
                .tag("packed_file_path", packed_file_path)
1659
1
                .tag("resource_id", resource_id);
1660
1
    }
1661
1662
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1663
1
        std::unique_ptr<Transaction> del_txn;
1664
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1665
1
        if (err != TxnErrorCode::TXN_OK) {
1666
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1667
0
                    .tag("instance_id", instance_id_)
1668
0
                    .tag("packed_file_path", packed_file_path)
1669
0
                    .tag("del_attempt", del_attempt)
1670
0
                    .tag("err", err);
1671
0
            return -1;
1672
0
        }
1673
1674
1
        std::string latest_val;
1675
1
        err = del_txn->get(packed_key, &latest_val);
1676
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1677
0
            return 0;
1678
0
        }
1679
1
        if (err != TxnErrorCode::TXN_OK) {
1680
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1681
0
                    .tag("instance_id", instance_id_)
1682
0
                    .tag("packed_file_path", packed_file_path)
1683
0
                    .tag("del_attempt", del_attempt)
1684
0
                    .tag("err", err);
1685
0
            return -1;
1686
0
        }
1687
1688
1
        cloud::PackedFileInfoPB latest_info;
1689
1
        if (!latest_info.ParseFromString(latest_val)) {
1690
0
            LOG_WARNING("failed to parse packed file info before removal")
1691
0
                    .tag("instance_id", instance_id_)
1692
0
                    .tag("packed_file_path", packed_file_path)
1693
0
                    .tag("del_attempt", del_attempt);
1694
0
            return -1;
1695
0
        }
1696
1697
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1698
1
              latest_info.ref_cnt() == 0)) {
1699
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1700
0
                    .tag("instance_id", instance_id_)
1701
0
                    .tag("packed_file_path", packed_file_path)
1702
0
                    .tag("del_attempt", del_attempt);
1703
0
            return 0;
1704
0
        }
1705
1706
1
        del_txn->remove(packed_key);
1707
1
        err = del_txn->commit();
1708
1
        if (err == TxnErrorCode::TXN_OK) {
1709
1
            if (stats) {
1710
1
                ++stats->num_deleted;
1711
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1712
1
                                        static_cast<int64_t>(latest_val.size());
1713
1
                if (del_ret == 0 || del_ret == 1) {
1714
1
                    ++stats->num_object_deleted;
1715
1
                    int64_t object_size = latest_info.total_slice_bytes();
1716
1
                    if (object_size <= 0) {
1717
0
                        object_size = packed_info.total_slice_bytes();
1718
0
                    }
1719
1
                    stats->bytes_object_deleted += object_size;
1720
1
                }
1721
1
            }
1722
1
            LOG_INFO("removed packed file metadata")
1723
1
                    .tag("instance_id", instance_id_)
1724
1
                    .tag("packed_file_path", packed_file_path);
1725
1
            return 0;
1726
1
        }
1727
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1728
0
            if (del_attempt >= max_retry_times) {
1729
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1730
0
                        .tag("instance_id", instance_id_)
1731
0
                        .tag("packed_file_path", packed_file_path)
1732
0
                        .tag("del_attempt", del_attempt);
1733
0
                return -1;
1734
0
            }
1735
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1736
0
                    .tag("instance_id", instance_id_)
1737
0
                    .tag("packed_file_path", packed_file_path)
1738
0
                    .tag("del_attempt", del_attempt);
1739
0
            sleep_for_packed_file_retry();
1740
0
            continue;
1741
0
        }
1742
0
        LOG_WARNING("failed to remove packed file kv")
1743
0
                .tag("instance_id", instance_id_)
1744
0
                .tag("packed_file_path", packed_file_path)
1745
0
                .tag("del_attempt", del_attempt)
1746
0
                .tag("err", err);
1747
0
        return -1;
1748
0
    }
1749
1750
0
    return -1;
1751
1
}
1752
1753
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view value,
1754
4
                                            PackedFileRecycleStats* stats, int* ret) {
1755
4
    if (stats) {
1756
4
        ++stats->num_scanned;
1757
4
    }
1758
4
    std::string packed_file_path;
1759
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1760
0
        LOG_WARNING("failed to decode packed file key")
1761
0
                .tag("instance_id", instance_id_)
1762
0
                .tag("key", hex(key));
1763
0
        if (stats) {
1764
0
            ++stats->num_failed;
1765
0
        }
1766
0
        if (ret) {
1767
0
            *ret = -1;
1768
0
        }
1769
0
        return 0;
1770
0
    }
1771
1772
4
    cloud::PackedFileInfoPB packed_info;
1773
4
    if (!packed_info.ParseFromArray(value.data(), value.size())) {
1774
0
        LOG_WARNING("failed to parse packed file info from scan")
1775
0
                .tag("instance_id", instance_id_)
1776
0
                .tag("packed_file_path", packed_file_path);
1777
0
        if (stats) {
1778
0
            ++stats->num_failed;
1779
0
        }
1780
0
        if (ret) {
1781
0
            *ret = -1;
1782
0
        }
1783
0
        return 0;
1784
0
    }
1785
1786
4
    const int64_t now_sec = ::time(nullptr);
1787
4
    const bool due =
1788
4
            config::force_immediate_recycle ||
1789
4
            now_sec - packed_info.created_at_sec() >= config::packed_file_correction_delay_seconds;
1790
4
    const bool need_correction = !packed_info.corrected() && due;
1791
4
    const bool need_recycle =
1792
4
            packed_info.state() == cloud::PackedFileInfoPB::RECYCLING && packed_info.ref_cnt() == 0;
1793
4
    if (!need_correction && !need_recycle) {
1794
1
        return 0;
1795
1
    }
1796
1797
3
    std::string packed_key(key);
1798
3
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1799
3
    if (process_ret != 0) {
1800
0
        if (stats) {
1801
0
            ++stats->num_failed;
1802
0
        }
1803
0
        if (ret) {
1804
0
            *ret = -1;
1805
0
        }
1806
0
    }
1807
3
    return 0;
1808
4
}
1809
1810
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1811
6.06k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1812
6.06k
    if (config::force_immediate_recycle) {
1813
15
        return 0L;
1814
15
    }
1815
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1816
6.05k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1817
6.05k
    int64_t retention_seconds = config::retention_seconds;
1818
6.05k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1819
4.74k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1820
4.74k
    }
1821
6.05k
    int64_t final_expiration = expiration + retention_seconds;
1822
6.05k
    if (*earlest_ts > final_expiration) {
1823
16
        *earlest_ts = final_expiration;
1824
16
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1825
16
    }
1826
6.05k
    return final_expiration;
1827
6.06k
}
1828
1829
int64_t calculate_partition_expired_time(
1830
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1831
11
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1832
11
    if (config::force_immediate_recycle) {
1833
5
        return 0L;
1834
5
    }
1835
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1836
6
                                                            : partition_meta_pb.creation_time();
1837
6
    int64_t retention_seconds = config::retention_seconds;
1838
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1839
6
        retention_seconds =
1840
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1841
6
    }
1842
6
    int64_t final_expiration = expiration + retention_seconds;
1843
6
    if (*earlest_ts > final_expiration) {
1844
2
        *earlest_ts = final_expiration;
1845
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1846
2
    }
1847
6
    return final_expiration;
1848
11
}
1849
1850
int64_t calculate_index_expired_time(const std::string& instance_id_,
1851
                                     const RecycleIndexPB& index_meta_pb,
1852
14
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1853
14
    if (config::force_immediate_recycle) {
1854
8
        return 0L;
1855
8
    }
1856
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1857
6
                                                        : index_meta_pb.creation_time();
1858
6
    int64_t retention_seconds = config::retention_seconds;
1859
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1860
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1861
6
    }
1862
6
    int64_t final_expiration = expiration + retention_seconds;
1863
6
    if (*earlest_ts > final_expiration) {
1864
2
        *earlest_ts = final_expiration;
1865
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1866
2
    }
1867
6
    return final_expiration;
1868
14
}
1869
1870
int64_t calculate_tmp_rowset_expired_time(
1871
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1872
53.0k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1873
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1874
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1875
    //  duration or timeout always < `retention_time` in practice.
1876
53.0k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1877
53.0k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1878
53.0k
                                 : tmp_rowset_meta_pb.creation_time();
1879
53.0k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1880
53.0k
    int64_t final_expiration = expiration + config::retention_seconds;
1881
53.0k
    if (*earlest_ts > final_expiration) {
1882
18
        *earlest_ts = final_expiration;
1883
18
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1884
18
    }
1885
53.0k
    return final_expiration;
1886
53.0k
}
1887
1888
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1889
30.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1890
30.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1891
30.0k
    if (*earlest_ts > final_expiration / 1000) {
1892
8
        *earlest_ts = final_expiration / 1000;
1893
8
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1894
8
    }
1895
30.0k
    return final_expiration;
1896
30.0k
}
1897
1898
int64_t calculate_restore_job_expired_time(
1899
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1900
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1901
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1902
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1903
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1904
        // final state, recycle immediately
1905
41
        return 0L;
1906
41
    }
1907
    // not final state, wait much longer than the FE's timeout(1 day)
1908
0
    int64_t last_modified_s =
1909
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1910
0
    int64_t expiration = restore_job.expired_at_s() > 0
1911
0
                                 ? last_modified_s + restore_job.expired_at_s()
1912
0
                                 : last_modified_s;
1913
0
    int64_t final_expiration = expiration + config::retention_seconds;
1914
0
    if (*earlest_ts > final_expiration) {
1915
0
        *earlest_ts = final_expiration;
1916
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1917
0
    }
1918
0
    return final_expiration;
1919
41
}
1920
1921
2
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1922
2
    AbortTxnRequest req;
1923
2
    TxnInfoPB txn_info;
1924
2
    MetaServiceCode code = MetaServiceCode::OK;
1925
2
    std::string msg;
1926
2
    std::stringstream ss;
1927
2
    std::unique_ptr<Transaction> txn;
1928
2
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1929
2
    if (err != TxnErrorCode::TXN_OK) {
1930
0
        LOG_WARNING("failed to create txn").tag("err", err);
1931
0
        return -1;
1932
0
    }
1933
1934
    // get txn index
1935
2
    TxnIndexPB txn_idx_pb;
1936
2
    auto index_key = txn_index_key({instance_id_, txn_id});
1937
2
    std::string index_val;
1938
2
    err = txn->get(index_key, &index_val);
1939
2
    if (err != TxnErrorCode::TXN_OK) {
1940
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1941
            // maybe recycled
1942
0
            LOG_INFO("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1943
0
                    .tag("key", hex(index_key))
1944
0
                    .tag("txn_id", txn_id);
1945
0
            return 0;
1946
0
        }
1947
0
        LOG_WARNING("failed to get txn index")
1948
0
                .tag("err", err)
1949
0
                .tag("key", hex(index_key))
1950
0
                .tag("txn_id", txn_id);
1951
0
        return -1;
1952
0
    }
1953
2
    if (!txn_idx_pb.ParseFromString(index_val)) {
1954
0
        LOG_WARNING("failed to parse txn index")
1955
0
                .tag("err", err)
1956
0
                .tag("key", hex(index_key))
1957
0
                .tag("txn_id", txn_id);
1958
0
        return -1;
1959
0
    }
1960
1961
2
    auto info_key = txn_info_key({instance_id_, txn_idx_pb.tablet_index().db_id(), txn_id});
1962
2
    std::string info_val;
1963
2
    err = txn->get(info_key, &info_val);
1964
2
    if (err != TxnErrorCode::TXN_OK) {
1965
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1966
            // maybe recycled
1967
0
            LOG_INFO("txn info not found, txn_id={} instance_id={}", txn_id, instance_id_)
1968
0
                    .tag("key", hex(info_key))
1969
0
                    .tag("txn_id", txn_id);
1970
0
            return 0;
1971
0
        }
1972
0
        LOG_WARNING("failed to get txn info")
1973
0
                .tag("err", err)
1974
0
                .tag("key", hex(info_key))
1975
0
                .tag("txn_id", txn_id);
1976
0
        return -1;
1977
0
    }
1978
2
    if (!txn_info.ParseFromString(info_val)) {
1979
0
        LOG_WARNING("failed to parse txn info")
1980
0
                .tag("err", err)
1981
0
                .tag("key", hex(info_key))
1982
0
                .tag("txn_id", txn_id);
1983
0
        return -1;
1984
0
    }
1985
1986
2
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
1987
0
        LOG_INFO("txn is not prepared status, txn_id={} status={}", txn_id, txn_info.status())
1988
0
                .tag("key", hex(info_key))
1989
0
                .tag("txn_id", txn_id);
1990
0
        return 0;
1991
0
    }
1992
1993
2
    req.set_txn_id(txn_id);
1994
1995
2
    LOG(INFO) << "begin abort txn for related rowset, txn_id=" << txn_id
1996
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString();
1997
1998
2
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
1999
2
    err = txn->commit();
2000
2
    if (err != TxnErrorCode::TXN_OK) {
2001
0
        code = cast_as<ErrCategory::COMMIT>(err);
2002
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
2003
0
        msg = ss.str();
2004
0
        return -1;
2005
0
    }
2006
2007
2
    LOG(INFO) << "finish abort txn for related rowset, txn_id=" << txn_id
2008
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString()
2009
2
              << " code=" << code << " msg=" << msg;
2010
2011
2
    return 0;
2012
2
}
2013
2014
4
int InstanceRecycler::abort_job_for_related_rowset(const RowsetMetaCloudPB& rowset_meta) {
2015
4
    FinishTabletJobRequest req;
2016
4
    FinishTabletJobResponse res;
2017
4
    req.set_action(FinishTabletJobRequest::ABORT);
2018
4
    MetaServiceCode code = MetaServiceCode::OK;
2019
4
    std::string msg;
2020
4
    std::stringstream ss;
2021
2022
4
    TabletIndexPB tablet_idx;
2023
4
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, rowset_meta.tablet_id(), tablet_idx);
2024
4
    if (ret == 1) {
2025
        // tablet maybe recycled, directly return 0
2026
1
        return 0;
2027
3
    } else if (ret != 0) {
2028
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << rowset_meta.tablet_id()
2029
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
2030
0
        return ret;
2031
0
    }
2032
2033
3
    std::unique_ptr<Transaction> txn;
2034
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2035
3
    if (err != TxnErrorCode::TXN_OK) {
2036
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
2037
0
        return -1;
2038
0
    }
2039
2040
3
    std::string job_key =
2041
3
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
2042
3
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
2043
3
    std::string job_val;
2044
3
    err = txn->get(job_key, &job_val);
2045
3
    if (err != TxnErrorCode::TXN_OK) {
2046
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2047
0
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
2048
0
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2049
0
            return 0;
2050
0
        }
2051
0
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
2052
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
2053
0
                     << " key=" << hex(job_key);
2054
0
        return -1;
2055
0
    }
2056
2057
3
    TabletJobInfoPB job_pb;
2058
3
    if (!job_pb.ParseFromString(job_val)) {
2059
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
2060
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2061
0
        return -1;
2062
0
    }
2063
2064
3
    std::string job_id {};
2065
3
    if (!job_pb.compaction().empty()) {
2066
2
        for (const auto& c : job_pb.compaction()) {
2067
2
            if (c.id() == rowset_meta.job_id()) {
2068
2
                job_id = c.id();
2069
2
                break;
2070
2
            }
2071
2
        }
2072
2
    } else if (job_pb.has_schema_change()) {
2073
1
        job_id = job_pb.schema_change().id();
2074
1
    }
2075
2076
3
    if (!job_id.empty() && rowset_meta.job_id() == job_id) {
2077
3
        LOG(INFO) << "begin to abort job for related rowset, job_id=" << rowset_meta.job_id()
2078
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
2079
3
        req.mutable_job()->CopyFrom(job_pb);
2080
3
        req.set_action(FinishTabletJobRequest::ABORT);
2081
3
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
2082
3
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
2083
3
                           ss);
2084
3
        if (code != MetaServiceCode::OK) {
2085
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
2086
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
2087
0
                         << " msg=" << msg;
2088
0
            return -1;
2089
0
        }
2090
3
        LOG(INFO) << "finish abort job for related rowset, job_id=" << rowset_meta.job_id()
2091
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
2092
3
                  << " code=" << code << " msg=" << msg;
2093
3
    } else {
2094
        // clang-format off
2095
0
        LOG(INFO) << "there is no job for related rowset, directly recycle rowset data"
2096
0
                  << ", instance_id=" << instance_id_ 
2097
0
                  << ", tablet_id=" << tablet_idx.tablet_id() 
2098
0
                  << ", job_id=" << job_id
2099
0
                  << ", rowset_id=" << rowset_meta.rowset_id_v2();
2100
        // clang-format on
2101
0
    }
2102
2103
3
    return 0;
2104
3
}
2105
2106
template <typename T>
2107
13
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2108
13
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2109
9
        return rowset_meta_pb.mutable_rowset_meta();
2110
9
    } else {
2111
9
        return &rowset_meta_pb;
2112
9
    }
2113
13
}
_ZN5doris5cloud19mutable_rowset_metaINS0_15RecycleRowsetPBEEEPNS_17RowsetMetaCloudPBERT_
Line
Count
Source
2107
4
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2108
4
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2109
4
        return rowset_meta_pb.mutable_rowset_meta();
2110
4
    } else {
2111
4
        return &rowset_meta_pb;
2112
4
    }
2113
4
}
_ZN5doris5cloud19mutable_rowset_metaINS_17RowsetMetaCloudPBEEEPS2_RT_
Line
Count
Source
2107
9
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2108
9
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2109
9
        return rowset_meta_pb.mutable_rowset_meta();
2110
9
    } else {
2111
9
        return &rowset_meta_pb;
2112
9
    }
2113
9
}
2114
2115
template <typename T>
2116
51
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2117
51
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2118
35
        return rowset_meta_pb.rowset_meta();
2119
35
    } else {
2120
35
        return rowset_meta_pb;
2121
35
    }
2122
51
}
_ZN5doris5cloud11rowset_metaINS0_15RecycleRowsetPBEEERKNS_17RowsetMetaCloudPBERKT_
Line
Count
Source
2116
16
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2117
16
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2118
16
        return rowset_meta_pb.rowset_meta();
2119
16
    } else {
2120
16
        return rowset_meta_pb;
2121
16
    }
2122
16
}
_ZN5doris5cloud11rowset_metaINS_17RowsetMetaCloudPBEEERKS2_RKT_
Line
Count
Source
2116
35
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2117
35
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2118
35
        return rowset_meta_pb.rowset_meta();
2119
35
    } else {
2120
35
        return rowset_meta_pb;
2121
35
    }
2122
35
}
2123
2124
struct DeferredRecycleAbortTask {
2125
    enum class Type : uint8_t {
2126
        TXN,
2127
        JOB,
2128
    };
2129
2130
    Type type = Type::TXN;
2131
    int64_t txn_id = 0;
2132
    int64_t tablet_id = 0;
2133
    int64_t start_version = 0;
2134
    int64_t end_version = 0;
2135
    std::string rowset_id;
2136
    std::string job_id;
2137
};
2138
2139
struct DeferredRecyclePrepareDeleteTask {
2140
    std::string key;
2141
    std::string resource_id;
2142
    std::string rowset_id;
2143
    int64_t tablet_id = 0;
2144
};
2145
2146
template <typename T>
2147
14
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
2148
14
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2149
4
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2150
0
            return std::nullopt;
2151
0
        }
2152
4
    }
2153
2154
4
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2155
4
    DeferredRecycleAbortTask task;
2156
4
    task.tablet_id = rs_meta.tablet_id();
2157
4
    task.start_version = rs_meta.start_version();
2158
4
    task.end_version = rs_meta.end_version();
2159
14
    if (rs_meta.has_load_id()) {
2160
4
        task.type = DeferredRecycleAbortTask::Type::TXN;
2161
4
        task.txn_id = rs_meta.txn_id();
2162
4
        return task;
2163
4
    }
2164
10
    if (rs_meta.has_job_id()) {
2165
6
        task.type = DeferredRecycleAbortTask::Type::JOB;
2166
6
        task.rowset_id = rs_meta.rowset_id_v2();
2167
6
        task.job_id = rs_meta.job_id();
2168
6
        return task;
2169
6
    }
2170
4
    return std::nullopt;
2171
10
}
_ZN5doris5cloud24make_deferred_abort_taskINS0_15RecycleRowsetPBEEESt8optionalINS0_24DeferredRecycleAbortTaskEERKT_
Line
Count
Source
2147
4
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
2148
4
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2149
4
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2150
0
            return std::nullopt;
2151
0
        }
2152
4
    }
2153
2154
4
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2155
4
    DeferredRecycleAbortTask task;
2156
4
    task.tablet_id = rs_meta.tablet_id();
2157
4
    task.start_version = rs_meta.start_version();
2158
4
    task.end_version = rs_meta.end_version();
2159
4
    if (rs_meta.has_load_id()) {
2160
2
        task.type = DeferredRecycleAbortTask::Type::TXN;
2161
2
        task.txn_id = rs_meta.txn_id();
2162
2
        return task;
2163
2
    }
2164
2
    if (rs_meta.has_job_id()) {
2165
2
        task.type = DeferredRecycleAbortTask::Type::JOB;
2166
2
        task.rowset_id = rs_meta.rowset_id_v2();
2167
2
        task.job_id = rs_meta.job_id();
2168
2
        return task;
2169
2
    }
2170
0
    return std::nullopt;
2171
2
}
_ZN5doris5cloud24make_deferred_abort_taskINS_17RowsetMetaCloudPBEEESt8optionalINS0_24DeferredRecycleAbortTaskEERKT_
Line
Count
Source
2147
10
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
2148
10
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2149
10
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2150
10
            return std::nullopt;
2151
10
        }
2152
10
    }
2153
2154
10
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2155
10
    DeferredRecycleAbortTask task;
2156
10
    task.tablet_id = rs_meta.tablet_id();
2157
10
    task.start_version = rs_meta.start_version();
2158
10
    task.end_version = rs_meta.end_version();
2159
10
    if (rs_meta.has_load_id()) {
2160
2
        task.type = DeferredRecycleAbortTask::Type::TXN;
2161
2
        task.txn_id = rs_meta.txn_id();
2162
2
        return task;
2163
2
    }
2164
8
    if (rs_meta.has_job_id()) {
2165
4
        task.type = DeferredRecycleAbortTask::Type::JOB;
2166
4
        task.rowset_id = rs_meta.rowset_id_v2();
2167
4
        task.job_id = rs_meta.job_id();
2168
4
        return task;
2169
4
    }
2170
4
    return std::nullopt;
2171
8
}
2172
2173
template <typename T>
2174
35
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
2175
35
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2176
35
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
2177
35
}
_ZN5doris5cloud28need_mark_rowset_as_recycledINS0_15RecycleRowsetPBEEEbRKT_
Line
Count
Source
2174
10
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
2175
10
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2176
10
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
2177
10
}
_ZN5doris5cloud28need_mark_rowset_as_recycledINS_17RowsetMetaCloudPBEEEbRKT_
Line
Count
Source
2174
25
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
2175
25
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2176
25
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
2177
25
}
2178
2179
template <typename T>
2180
int batch_mark_rowsets_as_recycled(TxnKv* txn_kv, const std::string& instance_id,
2181
11
                                   const std::vector<std::string>& keys) {
2182
11
    std::unique_ptr<Transaction> txn;
2183
11
    TxnErrorCode err = txn_kv->create_txn(&txn);
2184
11
    if (err != TxnErrorCode::TXN_OK) {
2185
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2186
0
        return -1;
2187
0
    }
2188
11
    std::vector<std::optional<std::string>> values;
2189
11
    err = txn->batch_get(&values, keys);
2190
11
    if (err != TxnErrorCode::TXN_OK) {
2191
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2192
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
2193
0
        return -1;
2194
0
    }
2195
11
    size_t total_keys = keys.size();
2196
24
    for (size_t i = 0; i < total_keys; i++) {
2197
13
        if (!values[i].has_value()) {
2198
            // has already been removed by commit_rowset
2199
0
            continue;
2200
0
        }
2201
13
        auto key = keys[i];
2202
13
        auto val = values[i].value();
2203
13
        T rowset_meta_pb;
2204
13
        if (!rowset_meta_pb.ParseFromString(val)) {
2205
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2206
0
                         << " key=" << hex(key);
2207
0
            return -1;
2208
0
        }
2209
13
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
2210
0
            continue;
2211
0
        }
2212
13
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2213
13
        val.clear();
2214
13
        rowset_meta_pb.SerializeToString(&val);
2215
13
        txn->put(key, val);
2216
13
    }
2217
11
    err = txn->commit();
2218
11
    if (err != TxnErrorCode::TXN_OK) {
2219
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2220
0
        return -1;
2221
0
    }
2222
2223
11
    return 0;
2224
11
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2181
4
                                   const std::vector<std::string>& keys) {
2182
4
    std::unique_ptr<Transaction> txn;
2183
4
    TxnErrorCode err = txn_kv->create_txn(&txn);
2184
4
    if (err != TxnErrorCode::TXN_OK) {
2185
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2186
0
        return -1;
2187
0
    }
2188
4
    std::vector<std::optional<std::string>> values;
2189
4
    err = txn->batch_get(&values, keys);
2190
4
    if (err != TxnErrorCode::TXN_OK) {
2191
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2192
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
2193
0
        return -1;
2194
0
    }
2195
4
    size_t total_keys = keys.size();
2196
8
    for (size_t i = 0; i < total_keys; i++) {
2197
4
        if (!values[i].has_value()) {
2198
            // has already been removed by commit_rowset
2199
0
            continue;
2200
0
        }
2201
4
        auto key = keys[i];
2202
4
        auto val = values[i].value();
2203
4
        T rowset_meta_pb;
2204
4
        if (!rowset_meta_pb.ParseFromString(val)) {
2205
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2206
0
                         << " key=" << hex(key);
2207
0
            return -1;
2208
0
        }
2209
4
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
2210
0
            continue;
2211
0
        }
2212
4
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2213
4
        val.clear();
2214
4
        rowset_meta_pb.SerializeToString(&val);
2215
4
        txn->put(key, val);
2216
4
    }
2217
4
    err = txn->commit();
2218
4
    if (err != TxnErrorCode::TXN_OK) {
2219
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2220
0
        return -1;
2221
0
    }
2222
2223
4
    return 0;
2224
4
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2181
7
                                   const std::vector<std::string>& keys) {
2182
7
    std::unique_ptr<Transaction> txn;
2183
7
    TxnErrorCode err = txn_kv->create_txn(&txn);
2184
7
    if (err != TxnErrorCode::TXN_OK) {
2185
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2186
0
        return -1;
2187
0
    }
2188
7
    std::vector<std::optional<std::string>> values;
2189
7
    err = txn->batch_get(&values, keys);
2190
7
    if (err != TxnErrorCode::TXN_OK) {
2191
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2192
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
2193
0
        return -1;
2194
0
    }
2195
7
    size_t total_keys = keys.size();
2196
16
    for (size_t i = 0; i < total_keys; i++) {
2197
9
        if (!values[i].has_value()) {
2198
            // has already been removed by commit_rowset
2199
0
            continue;
2200
0
        }
2201
9
        auto key = keys[i];
2202
9
        auto val = values[i].value();
2203
9
        T rowset_meta_pb;
2204
9
        if (!rowset_meta_pb.ParseFromString(val)) {
2205
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2206
0
                         << " key=" << hex(key);
2207
0
            return -1;
2208
0
        }
2209
9
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
2210
0
            continue;
2211
0
        }
2212
9
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2213
9
        val.clear();
2214
9
        rowset_meta_pb.SerializeToString(&val);
2215
9
        txn->put(key, val);
2216
9
    }
2217
7
    err = txn->commit();
2218
7
    if (err != TxnErrorCode::TXN_OK) {
2219
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2220
0
        return -1;
2221
0
    }
2222
2223
7
    return 0;
2224
7
}
2225
2226
template <typename T>
2227
int collect_deferred_abort_tasks(TxnKv* txn_kv, const std::string& instance_id,
2228
                                 const std::vector<std::string>& keys,
2229
                                 std::vector<DeferredRecycleAbortTask>* abort_tasks,
2230
5
                                 bool skip_base_version) {
2231
5
    constexpr size_t kAbortCheckBatchSize = 256;
2232
10
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2233
5
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2234
5
        std::unique_ptr<Transaction> txn;
2235
5
        TxnErrorCode err = txn_kv->create_txn(&txn);
2236
5
        if (err != TxnErrorCode::TXN_OK) {
2237
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2238
0
            return -1;
2239
0
        }
2240
10
        for (size_t idx = offset; idx < limit; ++idx) {
2241
5
            const std::string& key = keys[idx];
2242
5
            std::string val;
2243
5
            err = txn->get(key, &val);
2244
5
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2245
                // has already been removed
2246
0
                continue;
2247
0
            }
2248
5
            if (err != TxnErrorCode::TXN_OK) {
2249
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2250
0
                             << " key=" << hex(key);
2251
0
                return -1;
2252
0
            }
2253
5
            T rowset_meta_pb;
2254
5
            if (!rowset_meta_pb.ParseFromString(val)) {
2255
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2256
0
                             << " key=" << hex(key);
2257
0
                return -1;
2258
0
            }
2259
5
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2260
0
                continue;
2261
0
            }
2262
5
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2263
5
                abort_task.has_value()) {
2264
5
                abort_tasks->emplace_back(std::move(*abort_task));
2265
5
            }
2266
5
        }
2267
5
    }
2268
5
    return 0;
2269
5
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24DeferredRecycleAbortTaskESaISI_EEb
Line
Count
Source
2230
2
                                 bool skip_base_version) {
2231
2
    constexpr size_t kAbortCheckBatchSize = 256;
2232
4
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2233
2
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2234
2
        std::unique_ptr<Transaction> txn;
2235
2
        TxnErrorCode err = txn_kv->create_txn(&txn);
2236
2
        if (err != TxnErrorCode::TXN_OK) {
2237
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2238
0
            return -1;
2239
0
        }
2240
4
        for (size_t idx = offset; idx < limit; ++idx) {
2241
2
            const std::string& key = keys[idx];
2242
2
            std::string val;
2243
2
            err = txn->get(key, &val);
2244
2
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2245
                // has already been removed
2246
0
                continue;
2247
0
            }
2248
2
            if (err != TxnErrorCode::TXN_OK) {
2249
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2250
0
                             << " key=" << hex(key);
2251
0
                return -1;
2252
0
            }
2253
2
            T rowset_meta_pb;
2254
2
            if (!rowset_meta_pb.ParseFromString(val)) {
2255
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2256
0
                             << " key=" << hex(key);
2257
0
                return -1;
2258
0
            }
2259
2
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2260
0
                continue;
2261
0
            }
2262
2
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2263
2
                abort_task.has_value()) {
2264
2
                abort_tasks->emplace_back(std::move(*abort_task));
2265
2
            }
2266
2
        }
2267
2
    }
2268
2
    return 0;
2269
2
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24DeferredRecycleAbortTaskESaISI_EEb
Line
Count
Source
2230
3
                                 bool skip_base_version) {
2231
3
    constexpr size_t kAbortCheckBatchSize = 256;
2232
6
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2233
3
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2234
3
        std::unique_ptr<Transaction> txn;
2235
3
        TxnErrorCode err = txn_kv->create_txn(&txn);
2236
3
        if (err != TxnErrorCode::TXN_OK) {
2237
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2238
0
            return -1;
2239
0
        }
2240
6
        for (size_t idx = offset; idx < limit; ++idx) {
2241
3
            const std::string& key = keys[idx];
2242
3
            std::string val;
2243
3
            err = txn->get(key, &val);
2244
3
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2245
                // has already been removed
2246
0
                continue;
2247
0
            }
2248
3
            if (err != TxnErrorCode::TXN_OK) {
2249
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2250
0
                             << " key=" << hex(key);
2251
0
                return -1;
2252
0
            }
2253
3
            T rowset_meta_pb;
2254
3
            if (!rowset_meta_pb.ParseFromString(val)) {
2255
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2256
0
                             << " key=" << hex(key);
2257
0
                return -1;
2258
0
            }
2259
3
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2260
0
                continue;
2261
0
            }
2262
3
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2263
3
                abort_task.has_value()) {
2264
3
                abort_tasks->emplace_back(std::move(*abort_task));
2265
3
            }
2266
3
        }
2267
3
    }
2268
3
    return 0;
2269
3
}
2270
2271
template <typename T>
2272
int InstanceRecycler::batch_abort_txn_or_job_for_recycle(const std::vector<std::string>& keys,
2273
5
                                                         bool skip_base_version) {
2274
5
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2275
5
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2276
5
                                        skip_base_version) != 0) {
2277
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2278
0
        return -1;
2279
0
    }
2280
5
    for (const auto& abort_task : abort_tasks) {
2281
5
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2282
5
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2283
5
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2284
5
        int abort_ret = 0;
2285
5
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2286
2
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2287
3
        } else {
2288
3
            RowsetMetaCloudPB rowset_meta;
2289
3
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2290
3
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2291
3
            rowset_meta.set_job_id(abort_task.job_id);
2292
3
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2293
3
        }
2294
5
        if (abort_ret != 0) {
2295
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2296
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2297
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2298
0
            return abort_ret;
2299
0
        }
2300
5
    }
2301
5
    return 0;
2302
5
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEb
Line
Count
Source
2273
2
                                                         bool skip_base_version) {
2274
2
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2275
2
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2276
2
                                        skip_base_version) != 0) {
2277
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2278
0
        return -1;
2279
0
    }
2280
2
    for (const auto& abort_task : abort_tasks) {
2281
2
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2282
2
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2283
2
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2284
2
        int abort_ret = 0;
2285
2
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2286
1
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2287
1
        } else {
2288
1
            RowsetMetaCloudPB rowset_meta;
2289
1
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2290
1
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2291
1
            rowset_meta.set_job_id(abort_task.job_id);
2292
1
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2293
1
        }
2294
2
        if (abort_ret != 0) {
2295
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2296
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2297
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2298
0
            return abort_ret;
2299
0
        }
2300
2
    }
2301
2
    return 0;
2302
2
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEb
Line
Count
Source
2273
3
                                                         bool skip_base_version) {
2274
3
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2275
3
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2276
3
                                        skip_base_version) != 0) {
2277
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2278
0
        return -1;
2279
0
    }
2280
3
    for (const auto& abort_task : abort_tasks) {
2281
3
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2282
3
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2283
3
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2284
3
        int abort_ret = 0;
2285
3
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2286
1
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2287
2
        } else {
2288
2
            RowsetMetaCloudPB rowset_meta;
2289
2
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2290
2
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2291
2
            rowset_meta.set_job_id(abort_task.job_id);
2292
2
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2293
2
        }
2294
3
        if (abort_ret != 0) {
2295
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2296
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2297
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2298
0
            return abort_ret;
2299
0
        }
2300
3
    }
2301
3
    return 0;
2302
3
}
2303
2304
int collect_prepare_delete_tasks(TxnKv* txn_kv, const std::string& instance_id,
2305
                                 const std::vector<std::string>& keys,
2306
0
                                 std::vector<DeferredRecyclePrepareDeleteTask>* delete_tasks) {
2307
0
    constexpr size_t kPrepareCheckBatchSize = 256;
2308
0
    for (size_t offset = 0; offset < keys.size(); offset += kPrepareCheckBatchSize) {
2309
0
        size_t limit = std::min(keys.size(), offset + kPrepareCheckBatchSize);
2310
0
        std::unique_ptr<Transaction> txn;
2311
0
        TxnErrorCode err = txn_kv->create_txn(&txn);
2312
0
        if (err != TxnErrorCode::TXN_OK) {
2313
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2314
0
            return -1;
2315
0
        }
2316
0
        for (size_t idx = offset; idx < limit; ++idx) {
2317
0
            const std::string& key = keys[idx];
2318
0
            std::string val;
2319
0
            err = txn->get(key, &val);
2320
0
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2321
                // has already been removed
2322
0
                continue;
2323
0
            }
2324
0
            if (err != TxnErrorCode::TXN_OK) {
2325
0
                LOG(WARNING) << "failed to get recycle rowset, instance_id=" << instance_id
2326
0
                             << " key=" << hex(key);
2327
0
                return -1;
2328
0
            }
2329
0
            RecycleRowsetPB rowset;
2330
0
            if (!rowset.ParseFromString(val)) {
2331
0
                LOG(WARNING) << "failed to parse recycle rowset, instance_id=" << instance_id
2332
0
                             << " key=" << hex(key);
2333
0
                return -1;
2334
0
            }
2335
0
            if (rowset.type() != RecycleRowsetPB::PREPARE) {
2336
0
                continue;
2337
0
            }
2338
0
            const auto& rs_meta = rowset.rowset_meta();
2339
0
            delete_tasks->push_back(
2340
0
                    {key, rs_meta.resource_id(), rs_meta.rowset_id_v2(), rs_meta.tablet_id()});
2341
0
        }
2342
0
    }
2343
0
    return 0;
2344
0
}
2345
2346
1
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
2347
1
    const std::string task_name = "recycle_ref_rowsets";
2348
1
    *has_unrecycled_rowsets = false;
2349
2350
1
    std::string data_rowset_ref_count_key_start =
2351
1
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
2352
1
    std::string data_rowset_ref_count_key_end =
2353
1
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
2354
2355
1
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
2356
2357
1
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2358
1
    register_recycle_task(task_name, start_time);
2359
2360
1
    DORIS_CLOUD_DEFER {
2361
1
        unregister_recycle_task(task_name);
2362
1
        int64_t cost =
2363
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2364
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2365
1
                .tag("instance_id", instance_id_);
2366
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Line
Count
Source
2360
1
    DORIS_CLOUD_DEFER {
2361
1
        unregister_recycle_task(task_name);
2362
1
        int64_t cost =
2363
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2364
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2365
1
                .tag("instance_id", instance_id_);
2366
1
    };
2367
2368
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
2369
1
    std::set<int64_t> tablets_with_refs;
2370
1
    int64_t num_scanned = 0;
2371
2372
1
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
2373
0
        ++num_scanned;
2374
0
        int64_t tablet_id;
2375
0
        std::string rowset_id;
2376
0
        std::string_view key(k);
2377
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
2378
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
2379
0
            return 0; // Continue scanning
2380
0
        }
2381
2382
0
        tablets_with_refs.insert(tablet_id);
2383
0
        return 0;
2384
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
2385
2386
1
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
2387
1
                         std::move(scan_func)) != 0) {
2388
0
        LOG_WARNING("failed to scan data rowset ref count keys");
2389
0
        return -1;
2390
0
    }
2391
2392
1
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
2393
1
             tablets_with_refs.size(), num_scanned)
2394
1
            .tag("instance_id", instance_id_);
2395
2396
    // Phase 2: Recycle each tablet
2397
1
    int64_t num_recycled_tablets = 0;
2398
1
    for (int64_t tablet_id : tablets_with_refs) {
2399
0
        if (stopped()) {
2400
0
            LOG_INFO("recycler stopped, skip remaining tablets")
2401
0
                    .tag("instance_id", instance_id_)
2402
0
                    .tag("tablets_processed", num_recycled_tablets)
2403
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
2404
0
            break;
2405
0
        }
2406
2407
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
2408
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
2409
0
            LOG_WARNING("failed to recycle tablet")
2410
0
                    .tag("instance_id", instance_id_)
2411
0
                    .tag("tablet_id", tablet_id);
2412
0
            return -1;
2413
0
        }
2414
0
        ++num_recycled_tablets;
2415
0
    }
2416
2417
1
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
2418
1
            .tag("instance_id", instance_id_)
2419
1
            .tag("total_tablets", tablets_with_refs.size());
2420
2421
    // Phase 3: Scan again to check if any ref count keys still exist
2422
1
    std::unique_ptr<Transaction> txn;
2423
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2424
1
    if (err != TxnErrorCode::TXN_OK) {
2425
0
        LOG_WARNING("failed to create txn for final check")
2426
0
                .tag("instance_id", instance_id_)
2427
0
                .tag("err", err);
2428
0
        return -1;
2429
0
    }
2430
2431
1
    std::unique_ptr<RangeGetIterator> iter;
2432
1
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2433
1
    if (err != TxnErrorCode::TXN_OK) {
2434
0
        LOG_WARNING("failed to create range iterator for final check")
2435
0
                .tag("instance_id", instance_id_)
2436
0
                .tag("err", err);
2437
0
        return -1;
2438
0
    }
2439
2440
1
    *has_unrecycled_rowsets = iter->has_next();
2441
1
    if (*has_unrecycled_rowsets) {
2442
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2443
0
                .tag("instance_id", instance_id_);
2444
0
    }
2445
2446
1
    return 0;
2447
1
}
2448
2449
int InstanceRecycler::recycle_table_stream_offset_prefix(std::string prefix,
2450
6
                                                         RecyclerMetricsContext* metrics_context) {
2451
6
    std::string end = prefix;
2452
6
    end.push_back('\xff');
2453
6
    std::vector<std::string_view> keys;
2454
8
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2455
8
        keys.push_back(key);
2456
8
        return 0;
2457
8
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_1clESt17basic_string_viewIcS5_ESC_
Line
Count
Source
2454
2
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2455
2
        keys.push_back(key);
2456
2
        return 0;
2457
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_1clESt17basic_string_viewIcS5_ESC_
Line
Count
Source
2454
6
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2455
6
        keys.push_back(key);
2456
6
        return 0;
2457
6
    };
2458
6
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2459
4
        if (keys.empty()) {
2460
0
            return 0;
2461
0
        }
2462
4
        DORIS_CLOUD_DEFER {
2463
4
            keys.clear();
2464
4
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlvE_clEv
Line
Count
Source
2462
2
        DORIS_CLOUD_DEFER {
2463
2
            keys.clear();
2464
2
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlvE_clEv
Line
Count
Source
2462
2
        DORIS_CLOUD_DEFER {
2463
2
            keys.clear();
2464
2
        };
2465
4
        const size_t num_keys = keys.size();
2466
4
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2467
0
            LOG_WARNING("failed to delete table stream offsets")
2468
0
                    .tag("instance_id", instance_id_)
2469
0
                    .tag("num_keys", num_keys);
2470
0
            return -1;
2471
0
        }
2472
4
        metrics_context->total_recycled_num += num_keys;
2473
4
        metrics_context->report();
2474
4
        return 0;
2475
4
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2458
2
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2459
2
        if (keys.empty()) {
2460
0
            return 0;
2461
0
        }
2462
2
        DORIS_CLOUD_DEFER {
2463
2
            keys.clear();
2464
2
        };
2465
2
        const size_t num_keys = keys.size();
2466
2
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2467
0
            LOG_WARNING("failed to delete table stream offsets")
2468
0
                    .tag("instance_id", instance_id_)
2469
0
                    .tag("num_keys", num_keys);
2470
0
            return -1;
2471
0
        }
2472
2
        metrics_context->total_recycled_num += num_keys;
2473
2
        metrics_context->report();
2474
2
        return 0;
2475
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2458
2
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2459
2
        if (keys.empty()) {
2460
0
            return 0;
2461
0
        }
2462
2
        DORIS_CLOUD_DEFER {
2463
2
            keys.clear();
2464
2
        };
2465
2
        const size_t num_keys = keys.size();
2466
2
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2467
0
            LOG_WARNING("failed to delete table stream offsets")
2468
0
                    .tag("instance_id", instance_id_)
2469
0
                    .tag("num_keys", num_keys);
2470
0
            return -1;
2471
0
        }
2472
2
        metrics_context->total_recycled_num += num_keys;
2473
2
        metrics_context->report();
2474
2
        return 0;
2475
2
    };
2476
6
    return scan_and_recycle(std::move(prefix), end, std::move(collect_key), std::move(remove_keys));
2477
6
}
2478
2479
int InstanceRecycler::finalize_recycle_stream(int64_t stream_id,
2480
                                              const RecycleIndexPB& recycle_index,
2481
3
                                              std::string_view recycle_key) {
2482
3
    std::unique_ptr<Transaction> txn;
2483
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2484
3
    if (err != TxnErrorCode::TXN_OK) {
2485
0
        LOG_WARNING("failed to create transaction for final table stream cleanup")
2486
0
                .tag("instance_id", instance_id_)
2487
0
                .tag("stream_id", stream_id)
2488
0
                .tag("err", err);
2489
0
        return -1;
2490
0
    }
2491
2492
3
    std::string current_recycle_value;
2493
3
    err = txn->get(recycle_key, &current_recycle_value);
2494
3
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2495
0
        return 0;
2496
0
    }
2497
3
    if (err != TxnErrorCode::TXN_OK) {
2498
0
        LOG_WARNING("failed to read table stream recycle index")
2499
0
                .tag("instance_id", instance_id_)
2500
0
                .tag("stream_id", stream_id)
2501
0
                .tag("err", err);
2502
0
        return -1;
2503
0
    }
2504
3
    RecycleIndexPB current_recycle_index;
2505
3
    if (!current_recycle_index.ParseFromString(current_recycle_value) ||
2506
3
        current_recycle_index.state() != RecycleIndexPB::RECYCLING ||
2507
3
        current_recycle_index.object_type() != IndexObjectTypePB::TABLE_STREAM ||
2508
3
        current_recycle_index.db_id() != recycle_index.db_id() ||
2509
3
        current_recycle_index.table_id() != recycle_index.table_id() ||
2510
3
        current_recycle_index.stream_db_id() != recycle_index.stream_db_id()) {
2511
0
        LOG_WARNING("table stream recycle index changed during recycling")
2512
0
                .tag("instance_id", instance_id_)
2513
0
                .tag("stream_id", stream_id);
2514
0
        return -1;
2515
0
    }
2516
2517
3
    txn->remove(recycle_key);
2518
3
    err = txn->commit();
2519
3
    if (err != TxnErrorCode::TXN_OK) {
2520
0
        LOG_WARNING("failed to commit final table stream cleanup")
2521
0
                .tag("instance_id", instance_id_)
2522
0
                .tag("stream_id", stream_id)
2523
0
                .tag("err", err);
2524
0
        return -1;
2525
0
    }
2526
3
    return 0;
2527
3
}
2528
2529
int InstanceRecycler::recycle_stream(int64_t stream_id, const RecycleIndexPB& recycle_index,
2530
3
                                     std::string_view recycle_key) {
2531
3
    if (!recycle_index.has_db_id() || !recycle_index.has_stream_db_id()) {
2532
0
        LOG_WARNING("table stream recycle index is missing binding")
2533
0
                .tag("instance_id", instance_id_)
2534
0
                .tag("stream_id", stream_id);
2535
0
        return -1;
2536
0
    }
2537
2538
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stream");
2539
3
    DORIS_CLOUD_DEFER {
2540
3
        metrics_context.finish_report();
2541
3
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_streamElRKNS0_14RecycleIndexPBESt17basic_string_viewIcSt11char_traitsIcEEENK3$_0clEv
Line
Count
Source
2539
2
    DORIS_CLOUD_DEFER {
2540
2
        metrics_context.finish_report();
2541
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_streamElRKNS0_14RecycleIndexPBESt17basic_string_viewIcSt11char_traitsIcEEENK3$_0clEv
Line
Count
Source
2539
1
    DORIS_CLOUD_DEFER {
2540
1
        metrics_context.finish_report();
2541
1
    };
2542
3
    const std::string latest_offset_prefix = table_stream_offset_key_prefix(
2543
3
            instance_id_, recycle_index.db_id(), recycle_index.table_id(),
2544
3
            recycle_index.stream_db_id(), stream_id);
2545
3
    if (recycle_table_stream_offset_prefix(latest_offset_prefix, &metrics_context) != 0) {
2546
0
        return -1;
2547
0
    }
2548
3
    const std::string versioned_offset_prefix = versioned::table_stream_offset_key_prefix(
2549
3
            instance_id_, recycle_index.db_id(), recycle_index.table_id(),
2550
3
            recycle_index.stream_db_id(), stream_id);
2551
3
    if (recycle_table_stream_offset_prefix(versioned_offset_prefix, &metrics_context) != 0 ||
2552
3
        stopped()) {
2553
0
        return -1;
2554
0
    }
2555
3
    return finalize_recycle_stream(stream_id, recycle_index, recycle_key);
2556
3
}
2557
2558
int InstanceRecycler::recycle_partition_table_stream_offsets(
2559
        int64_t db_id, int64_t table_id, int64_t partition_id,
2560
10
        const google::protobuf::RepeatedPtrField<TableStreamIdentityPB>& table_streams) {
2561
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stream_partition_offsets");
2562
10
    DORIS_CLOUD_DEFER {
2563
10
        metrics_context.finish_report();
2564
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler38recycle_partition_table_stream_offsetsElllRKN6google8protobuf16RepeatedPtrFieldINS0_21TableStreamIdentityPBEEEENK3$_0clEv
Line
Count
Source
2562
1
    DORIS_CLOUD_DEFER {
2563
1
        metrics_context.finish_report();
2564
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler38recycle_partition_table_stream_offsetsElllRKN6google8protobuf16RepeatedPtrFieldINS0_21TableStreamIdentityPBEEEENK3$_0clEv
Line
Count
Source
2562
9
    DORIS_CLOUD_DEFER {
2563
9
        metrics_context.finish_report();
2564
9
    };
2565
10
    const size_t batch_size = std::max(1, config::recycler_max_tasks_per_batch);
2566
12
    for (size_t begin_index = 0; begin_index < table_streams.size(); begin_index += batch_size) {
2567
2
        const size_t end_index =
2568
2
                std::min(static_cast<size_t>(table_streams.size()), begin_index + batch_size);
2569
2
        std::unique_ptr<Transaction> txn;
2570
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2571
2
        if (err != TxnErrorCode::TXN_OK) {
2572
0
            LOG_WARNING("failed to create transaction for partition stream offset cleanup")
2573
0
                    .tag("instance_id", instance_id_)
2574
0
                    .tag("partition_id", partition_id)
2575
0
                    .tag("err", err);
2576
0
            return -1;
2577
0
        }
2578
4
        for (size_t i = begin_index; i < end_index; ++i) {
2579
2
            const TableStreamIdentityPB& stream = table_streams.Get(i);
2580
2
            if (stream.base_db_id() != db_id || stream.base_table_id() != table_id ||
2581
2
                stream.stream_db_id() <= 0 || stream.stream_id() <= 0) {
2582
0
                LOG_WARNING("invalid table stream binding in recycle partition")
2583
0
                        .tag("instance_id", instance_id_)
2584
0
                        .tag("partition_id", partition_id)
2585
0
                        .tag("stream_id", stream.stream_id());
2586
0
                return -1;
2587
0
            }
2588
2
            txn->remove(table_stream_offset_key({instance_id_, stream.base_db_id(),
2589
2
                                                 stream.base_table_id(), stream.stream_db_id(),
2590
2
                                                 stream.stream_id(), partition_id}));
2591
2
            versioned_remove_all(
2592
2
                    txn.get(), versioned::table_stream_offset_key(
2593
2
                                       {instance_id_, stream.base_db_id(), stream.base_table_id(),
2594
2
                                        stream.stream_db_id(), stream.stream_id(), partition_id}));
2595
2
        }
2596
2
        err = txn->commit();
2597
2
        if (err != TxnErrorCode::TXN_OK) {
2598
0
            LOG_WARNING("failed to commit partition stream offset cleanup")
2599
0
                    .tag("instance_id", instance_id_)
2600
0
                    .tag("partition_id", partition_id)
2601
0
                    .tag("err", err);
2602
0
            return -1;
2603
0
        }
2604
2
        metrics_context.total_recycled_num += end_index - begin_index;
2605
2
        metrics_context.report();
2606
2
    }
2607
10
    return 0;
2608
10
}
2609
2610
19
int InstanceRecycler::recycle_indexes() {
2611
19
    const std::string task_name = "recycle_indexes";
2612
19
    int64_t num_scanned = 0;
2613
19
    int64_t num_expired = 0;
2614
19
    int64_t num_recycled = 0;
2615
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2616
2617
19
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2618
19
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2619
19
    std::string index_key0;
2620
19
    std::string index_key1;
2621
19
    recycle_index_key(index_key_info0, &index_key0);
2622
19
    recycle_index_key(index_key_info1, &index_key1);
2623
2624
19
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2625
2626
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2627
19
    register_recycle_task(task_name, start_time);
2628
2629
19
    DORIS_CLOUD_DEFER {
2630
19
        unregister_recycle_task(task_name);
2631
19
        int64_t cost =
2632
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2633
19
        metrics_context.finish_report();
2634
19
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2635
19
                .tag("instance_id", instance_id_)
2636
19
                .tag("num_scanned", num_scanned)
2637
19
                .tag("num_expired", num_expired)
2638
19
                .tag("num_recycled", num_recycled);
2639
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2629
3
    DORIS_CLOUD_DEFER {
2630
3
        unregister_recycle_task(task_name);
2631
3
        int64_t cost =
2632
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2633
3
        metrics_context.finish_report();
2634
3
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2635
3
                .tag("instance_id", instance_id_)
2636
3
                .tag("num_scanned", num_scanned)
2637
3
                .tag("num_expired", num_expired)
2638
3
                .tag("num_recycled", num_recycled);
2639
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2629
16
    DORIS_CLOUD_DEFER {
2630
16
        unregister_recycle_task(task_name);
2631
16
        int64_t cost =
2632
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2633
16
        metrics_context.finish_report();
2634
16
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2635
16
                .tag("instance_id", instance_id_)
2636
16
                .tag("num_scanned", num_scanned)
2637
16
                .tag("num_expired", num_expired)
2638
16
                .tag("num_recycled", num_recycled);
2639
16
    };
2640
2641
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2642
2643
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2644
19
    std::vector<std::string_view> index_keys;
2645
19
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2646
13
        ++num_scanned;
2647
13
        RecycleIndexPB index_pb;
2648
13
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2649
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2650
0
            return -1;
2651
0
        }
2652
13
        int64_t current_time = ::time(nullptr);
2653
13
        if (current_time <
2654
13
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2655
0
            return 0;
2656
0
        }
2657
13
        ++num_expired;
2658
        // decode index_id
2659
13
        auto k1 = k;
2660
13
        k1.remove_prefix(1);
2661
13
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2662
13
        decode_key(&k1, &out);
2663
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2664
13
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2665
13
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2666
13
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2667
13
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2668
        // Change state to RECYCLING
2669
13
        std::unique_ptr<Transaction> txn;
2670
13
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2671
13
        if (err != TxnErrorCode::TXN_OK) {
2672
0
            LOG_WARNING("failed to create txn").tag("err", err);
2673
0
            return -1;
2674
0
        }
2675
13
        std::string val;
2676
13
        err = txn->get(k, &val);
2677
13
        if (err ==
2678
13
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2679
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2680
0
            return 0;
2681
0
        }
2682
13
        if (err != TxnErrorCode::TXN_OK) {
2683
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2684
0
            return -1;
2685
0
        }
2686
13
        index_pb.Clear();
2687
13
        if (!index_pb.ParseFromString(val)) {
2688
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2689
0
            return -1;
2690
0
        }
2691
13
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2692
12
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2693
12
            txn->put(k, index_pb.SerializeAsString());
2694
12
            err = txn->commit();
2695
12
            if (err != TxnErrorCode::TXN_OK) {
2696
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2697
0
                return -1;
2698
0
            }
2699
12
        }
2700
13
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
2701
3
            if (recycle_stream(index_id, index_pb, k) != 0) {
2702
0
                LOG_WARNING("failed to recycle table stream")
2703
0
                        .tag("instance_id", instance_id_)
2704
0
                        .tag("stream_id", index_id);
2705
0
                return -1;
2706
0
            }
2707
3
            metrics_context.total_recycled_num = ++num_recycled;
2708
3
            metrics_context.report();
2709
3
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2710
3
            return 0;
2711
3
        }
2712
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2713
1
            LOG_WARNING("failed to recycle tablets under index")
2714
1
                    .tag("table_id", index_pb.table_id())
2715
1
                    .tag("instance_id", instance_id_)
2716
1
                    .tag("index_id", index_id);
2717
1
            return -1;
2718
1
        }
2719
2720
9
        if (index_pb.has_db_id()) {
2721
            // Recycle the versioned keys
2722
3
            std::unique_ptr<Transaction> txn;
2723
3
            err = txn_kv_->create_txn(&txn);
2724
3
            if (err != TxnErrorCode::TXN_OK) {
2725
0
                LOG_WARNING("failed to create txn").tag("err", err);
2726
0
                return -1;
2727
0
            }
2728
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2729
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2730
3
            std::string index_inverted_key = versioned::index_inverted_key(
2731
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2732
3
            versioned_remove_all(txn.get(), meta_key);
2733
3
            txn->remove(index_key);
2734
3
            txn->remove(index_inverted_key);
2735
3
            err = txn->commit();
2736
3
            if (err != TxnErrorCode::TXN_OK) {
2737
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2738
0
                return -1;
2739
0
            }
2740
3
        }
2741
2742
9
        metrics_context.total_recycled_num = ++num_recycled;
2743
9
        metrics_context.report();
2744
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2745
9
        index_keys.push_back(k);
2746
9
        return 0;
2747
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2645
4
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2646
4
        ++num_scanned;
2647
4
        RecycleIndexPB index_pb;
2648
4
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2649
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2650
0
            return -1;
2651
0
        }
2652
4
        int64_t current_time = ::time(nullptr);
2653
4
        if (current_time <
2654
4
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2655
0
            return 0;
2656
0
        }
2657
4
        ++num_expired;
2658
        // decode index_id
2659
4
        auto k1 = k;
2660
4
        k1.remove_prefix(1);
2661
4
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2662
4
        decode_key(&k1, &out);
2663
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2664
4
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2665
4
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2666
4
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2667
4
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2668
        // Change state to RECYCLING
2669
4
        std::unique_ptr<Transaction> txn;
2670
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2671
4
        if (err != TxnErrorCode::TXN_OK) {
2672
0
            LOG_WARNING("failed to create txn").tag("err", err);
2673
0
            return -1;
2674
0
        }
2675
4
        std::string val;
2676
4
        err = txn->get(k, &val);
2677
4
        if (err ==
2678
4
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2679
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2680
0
            return 0;
2681
0
        }
2682
4
        if (err != TxnErrorCode::TXN_OK) {
2683
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2684
0
            return -1;
2685
0
        }
2686
4
        index_pb.Clear();
2687
4
        if (!index_pb.ParseFromString(val)) {
2688
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2689
0
            return -1;
2690
0
        }
2691
4
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2692
3
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2693
3
            txn->put(k, index_pb.SerializeAsString());
2694
3
            err = txn->commit();
2695
3
            if (err != TxnErrorCode::TXN_OK) {
2696
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2697
0
                return -1;
2698
0
            }
2699
3
        }
2700
4
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
2701
2
            if (recycle_stream(index_id, index_pb, k) != 0) {
2702
0
                LOG_WARNING("failed to recycle table stream")
2703
0
                        .tag("instance_id", instance_id_)
2704
0
                        .tag("stream_id", index_id);
2705
0
                return -1;
2706
0
            }
2707
2
            metrics_context.total_recycled_num = ++num_recycled;
2708
2
            metrics_context.report();
2709
2
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2710
2
            return 0;
2711
2
        }
2712
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2713
1
            LOG_WARNING("failed to recycle tablets under index")
2714
1
                    .tag("table_id", index_pb.table_id())
2715
1
                    .tag("instance_id", instance_id_)
2716
1
                    .tag("index_id", index_id);
2717
1
            return -1;
2718
1
        }
2719
2720
1
        if (index_pb.has_db_id()) {
2721
            // Recycle the versioned keys
2722
1
            std::unique_ptr<Transaction> txn;
2723
1
            err = txn_kv_->create_txn(&txn);
2724
1
            if (err != TxnErrorCode::TXN_OK) {
2725
0
                LOG_WARNING("failed to create txn").tag("err", err);
2726
0
                return -1;
2727
0
            }
2728
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2729
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2730
1
            std::string index_inverted_key = versioned::index_inverted_key(
2731
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2732
1
            versioned_remove_all(txn.get(), meta_key);
2733
1
            txn->remove(index_key);
2734
1
            txn->remove(index_inverted_key);
2735
1
            err = txn->commit();
2736
1
            if (err != TxnErrorCode::TXN_OK) {
2737
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2738
0
                return -1;
2739
0
            }
2740
1
        }
2741
2742
1
        metrics_context.total_recycled_num = ++num_recycled;
2743
1
        metrics_context.report();
2744
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2745
1
        index_keys.push_back(k);
2746
1
        return 0;
2747
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2645
9
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2646
9
        ++num_scanned;
2647
9
        RecycleIndexPB index_pb;
2648
9
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2649
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2650
0
            return -1;
2651
0
        }
2652
9
        int64_t current_time = ::time(nullptr);
2653
9
        if (current_time <
2654
9
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2655
0
            return 0;
2656
0
        }
2657
9
        ++num_expired;
2658
        // decode index_id
2659
9
        auto k1 = k;
2660
9
        k1.remove_prefix(1);
2661
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2662
9
        decode_key(&k1, &out);
2663
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2664
9
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2665
9
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2666
9
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2667
9
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2668
        // Change state to RECYCLING
2669
9
        std::unique_ptr<Transaction> txn;
2670
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2671
9
        if (err != TxnErrorCode::TXN_OK) {
2672
0
            LOG_WARNING("failed to create txn").tag("err", err);
2673
0
            return -1;
2674
0
        }
2675
9
        std::string val;
2676
9
        err = txn->get(k, &val);
2677
9
        if (err ==
2678
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2679
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2680
0
            return 0;
2681
0
        }
2682
9
        if (err != TxnErrorCode::TXN_OK) {
2683
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2684
0
            return -1;
2685
0
        }
2686
9
        index_pb.Clear();
2687
9
        if (!index_pb.ParseFromString(val)) {
2688
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2689
0
            return -1;
2690
0
        }
2691
9
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2692
9
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2693
9
            txn->put(k, index_pb.SerializeAsString());
2694
9
            err = txn->commit();
2695
9
            if (err != TxnErrorCode::TXN_OK) {
2696
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2697
0
                return -1;
2698
0
            }
2699
9
        }
2700
9
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
2701
1
            if (recycle_stream(index_id, index_pb, k) != 0) {
2702
0
                LOG_WARNING("failed to recycle table stream")
2703
0
                        .tag("instance_id", instance_id_)
2704
0
                        .tag("stream_id", index_id);
2705
0
                return -1;
2706
0
            }
2707
1
            metrics_context.total_recycled_num = ++num_recycled;
2708
1
            metrics_context.report();
2709
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2710
1
            return 0;
2711
1
        }
2712
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2713
0
            LOG_WARNING("failed to recycle tablets under index")
2714
0
                    .tag("table_id", index_pb.table_id())
2715
0
                    .tag("instance_id", instance_id_)
2716
0
                    .tag("index_id", index_id);
2717
0
            return -1;
2718
0
        }
2719
2720
8
        if (index_pb.has_db_id()) {
2721
            // Recycle the versioned keys
2722
2
            std::unique_ptr<Transaction> txn;
2723
2
            err = txn_kv_->create_txn(&txn);
2724
2
            if (err != TxnErrorCode::TXN_OK) {
2725
0
                LOG_WARNING("failed to create txn").tag("err", err);
2726
0
                return -1;
2727
0
            }
2728
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2729
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2730
2
            std::string index_inverted_key = versioned::index_inverted_key(
2731
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2732
2
            versioned_remove_all(txn.get(), meta_key);
2733
2
            txn->remove(index_key);
2734
2
            txn->remove(index_inverted_key);
2735
2
            err = txn->commit();
2736
2
            if (err != TxnErrorCode::TXN_OK) {
2737
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2738
0
                return -1;
2739
0
            }
2740
2
        }
2741
2742
8
        metrics_context.total_recycled_num = ++num_recycled;
2743
8
        metrics_context.report();
2744
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2745
8
        index_keys.push_back(k);
2746
8
        return 0;
2747
8
    };
2748
2749
19
    auto loop_done = [&index_keys, this]() -> int {
2750
8
        if (index_keys.empty()) return 0;
2751
5
        DORIS_CLOUD_DEFER {
2752
5
            index_keys.clear();
2753
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2751
1
        DORIS_CLOUD_DEFER {
2752
1
            index_keys.clear();
2753
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2751
4
        DORIS_CLOUD_DEFER {
2752
4
            index_keys.clear();
2753
4
        };
2754
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2755
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2756
0
            return -1;
2757
0
        }
2758
5
        return 0;
2759
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2749
3
    auto loop_done = [&index_keys, this]() -> int {
2750
3
        if (index_keys.empty()) return 0;
2751
1
        DORIS_CLOUD_DEFER {
2752
1
            index_keys.clear();
2753
1
        };
2754
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2755
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2756
0
            return -1;
2757
0
        }
2758
1
        return 0;
2759
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2749
5
    auto loop_done = [&index_keys, this]() -> int {
2750
5
        if (index_keys.empty()) return 0;
2751
4
        DORIS_CLOUD_DEFER {
2752
4
            index_keys.clear();
2753
4
        };
2754
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2755
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2756
0
            return -1;
2757
0
        }
2758
4
        return 0;
2759
4
    };
2760
2761
19
    if (config::enable_recycler_stats_metrics) {
2762
0
        scan_and_statistics_indexes();
2763
0
    }
2764
    // recycle_func and loop_done for scan and recycle
2765
19
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
2766
19
}
2767
2768
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
2769
8.25k
                             int64_t tablet_id) {
2770
8.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
2771
2772
8.25k
    std::unique_ptr<Transaction> txn;
2773
8.25k
    TxnErrorCode err = txn_kv->create_txn(&txn);
2774
8.25k
    if (err != TxnErrorCode::TXN_OK) {
2775
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
2776
0
                     << " tablet_id=" << tablet_id << " err=" << err;
2777
0
        return false;
2778
0
    }
2779
2780
8.25k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
2781
8.25k
    std::string tablet_idx_val;
2782
8.25k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
2783
8.25k
    if (TxnErrorCode::TXN_OK != err) {
2784
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
2785
0
                     << " tablet_id=" << tablet_id << " err=" << err
2786
0
                     << " key=" << hex(tablet_idx_key);
2787
0
        return false;
2788
0
    }
2789
2790
8.25k
    TabletIndexPB tablet_idx_pb;
2791
8.25k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
2792
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
2793
0
                     << " tablet_id=" << tablet_id;
2794
0
        return false;
2795
0
    }
2796
2797
8.25k
    if (!tablet_idx_pb.has_db_id()) {
2798
        // In the previous version, the db_id was not set in the index_pb.
2799
        // If updating to the version which enable txn lazy commit, the db_id will be set.
2800
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
2801
0
                  << " instance_id=" << instance_id
2802
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
2803
0
        return true;
2804
0
    }
2805
2806
8.25k
    std::string ver_val;
2807
8.25k
    std::string ver_key =
2808
8.25k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
2809
8.25k
                                   tablet_idx_pb.partition_id()});
2810
8.25k
    err = txn->get(ver_key, &ver_val);
2811
2812
8.25k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
2813
214
        LOG(INFO) << ""
2814
214
                     "partition version not found, instance_id="
2815
214
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
2816
214
                  << " table_id=" << tablet_idx_pb.table_id()
2817
214
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
2818
214
                  << " key=" << hex(ver_key);
2819
214
        return true;
2820
214
    }
2821
2822
8.03k
    if (TxnErrorCode::TXN_OK != err) {
2823
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
2824
0
                     << " db_id=" << tablet_idx_pb.db_id()
2825
0
                     << " table_id=" << tablet_idx_pb.table_id()
2826
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2827
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
2828
0
        return false;
2829
0
    }
2830
2831
8.03k
    VersionPB version_pb;
2832
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
2833
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
2834
0
                     << " db_id=" << tablet_idx_pb.db_id()
2835
0
                     << " table_id=" << tablet_idx_pb.table_id()
2836
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2837
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
2838
0
        return false;
2839
0
    }
2840
2841
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
2842
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
2843
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
2844
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
2845
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
2846
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
2847
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
2848
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
2849
4.00k
                     << " key=" << hex(ver_key);
2850
4.00k
        return false;
2851
4.00k
    }
2852
4.03k
    return true;
2853
8.03k
}
2854
2855
17
int InstanceRecycler::recycle_partitions() {
2856
17
    const std::string task_name = "recycle_partitions";
2857
17
    int64_t num_scanned = 0;
2858
17
    int64_t num_expired = 0;
2859
17
    int64_t num_recycled = 0;
2860
17
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2861
2862
17
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
2863
17
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
2864
17
    std::string part_key0;
2865
17
    std::string part_key1;
2866
17
    recycle_partition_key(part_key_info0, &part_key0);
2867
17
    recycle_partition_key(part_key_info1, &part_key1);
2868
2869
17
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
2870
2871
17
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2872
17
    register_recycle_task(task_name, start_time);
2873
2874
17
    DORIS_CLOUD_DEFER {
2875
17
        unregister_recycle_task(task_name);
2876
17
        int64_t cost =
2877
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2878
17
        metrics_context.finish_report();
2879
17
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2880
17
                .tag("instance_id", instance_id_)
2881
17
                .tag("num_scanned", num_scanned)
2882
17
                .tag("num_expired", num_expired)
2883
17
                .tag("num_recycled", num_recycled);
2884
17
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2874
2
    DORIS_CLOUD_DEFER {
2875
2
        unregister_recycle_task(task_name);
2876
2
        int64_t cost =
2877
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2878
2
        metrics_context.finish_report();
2879
2
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2880
2
                .tag("instance_id", instance_id_)
2881
2
                .tag("num_scanned", num_scanned)
2882
2
                .tag("num_expired", num_expired)
2883
2
                .tag("num_recycled", num_recycled);
2884
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2874
15
    DORIS_CLOUD_DEFER {
2875
15
        unregister_recycle_task(task_name);
2876
15
        int64_t cost =
2877
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2878
15
        metrics_context.finish_report();
2879
15
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2880
15
                .tag("instance_id", instance_id_)
2881
15
                .tag("num_scanned", num_scanned)
2882
15
                .tag("num_expired", num_expired)
2883
15
                .tag("num_recycled", num_recycled);
2884
15
    };
2885
2886
17
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2887
2888
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
2889
17
    std::vector<std::string_view> partition_keys;
2890
17
    std::vector<std::string> partition_version_keys;
2891
17
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2892
11
        ++num_scanned;
2893
11
        RecyclePartitionPB part_pb;
2894
11
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2895
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2896
0
            return -1;
2897
0
        }
2898
11
        int64_t current_time = ::time(nullptr);
2899
11
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2900
11
                                                            &earlest_ts)) { // not expired
2901
0
            return 0;
2902
0
        }
2903
11
        ++num_expired;
2904
        // decode partition_id
2905
11
        auto k1 = k;
2906
11
        k1.remove_prefix(1);
2907
11
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2908
11
        decode_key(&k1, &out);
2909
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2910
11
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2911
11
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2912
11
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2913
11
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2914
        // Change state to RECYCLING
2915
11
        std::unique_ptr<Transaction> txn;
2916
11
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2917
11
        if (err != TxnErrorCode::TXN_OK) {
2918
0
            LOG_WARNING("failed to create txn").tag("err", err);
2919
0
            return -1;
2920
0
        }
2921
11
        std::string val;
2922
11
        err = txn->get(k, &val);
2923
11
        if (err ==
2924
11
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2925
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2926
0
            return 0;
2927
0
        }
2928
11
        if (err != TxnErrorCode::TXN_OK) {
2929
0
            LOG_WARNING("failed to get kv");
2930
0
            return -1;
2931
0
        }
2932
11
        part_pb.Clear();
2933
11
        if (!part_pb.ParseFromString(val)) {
2934
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2935
0
            return -1;
2936
0
        }
2937
        // Partitions with PREPARED state MUST have no data
2938
11
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2939
10
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2940
10
            txn->put(k, part_pb.SerializeAsString());
2941
10
            err = txn->commit();
2942
10
            if (err != TxnErrorCode::TXN_OK) {
2943
0
                LOG_WARNING("failed to commit txn: {}", err);
2944
0
                return -1;
2945
0
            }
2946
10
        }
2947
2948
11
        int ret = 0;
2949
35
        for (int64_t index_id : part_pb.index_id()) {
2950
35
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2951
1
                LOG_WARNING("failed to recycle tablets under partition")
2952
1
                        .tag("table_id", part_pb.table_id())
2953
1
                        .tag("instance_id", instance_id_)
2954
1
                        .tag("index_id", index_id)
2955
1
                        .tag("partition_id", partition_id);
2956
1
                ret = -1;
2957
1
            }
2958
35
        }
2959
11
        if (ret == 0 && part_pb.has_db_id() &&
2960
11
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
2961
10
                                                   partition_id, part_pb.table_streams()) != 0) {
2962
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
2963
0
                    .tag("instance_id", instance_id_)
2964
0
                    .tag("table_id", part_pb.table_id())
2965
0
                    .tag("partition_id", partition_id);
2966
0
            ret = -1;
2967
0
        }
2968
11
        if (ret == 0 && part_pb.has_db_id()) {
2969
            // Recycle the versioned keys
2970
10
            std::unique_ptr<Transaction> txn;
2971
10
            err = txn_kv_->create_txn(&txn);
2972
10
            if (err != TxnErrorCode::TXN_OK) {
2973
0
                LOG_WARNING("failed to create txn").tag("err", err);
2974
0
                return -1;
2975
0
            }
2976
10
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2977
10
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2978
10
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2979
10
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2980
10
            std::string partition_version_key =
2981
10
                    versioned::partition_version_key({instance_id_, partition_id});
2982
10
            versioned_remove_all(txn.get(), meta_key);
2983
10
            txn->remove(index_key);
2984
10
            txn->remove(inverted_index_key);
2985
10
            versioned_remove_all(txn.get(), partition_version_key);
2986
10
            err = txn->commit();
2987
10
            if (err != TxnErrorCode::TXN_OK) {
2988
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2989
0
                return -1;
2990
0
            }
2991
10
        }
2992
2993
11
        if (ret == 0) {
2994
10
            ++num_recycled;
2995
10
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2996
10
            partition_keys.push_back(k);
2997
10
            if (part_pb.db_id() > 0) {
2998
10
                partition_version_keys.push_back(partition_version_key(
2999
10
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3000
10
            }
3001
10
            metrics_context.total_recycled_num = num_recycled;
3002
10
            metrics_context.report();
3003
10
        }
3004
11
        return ret;
3005
11
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2891
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2892
2
        ++num_scanned;
2893
2
        RecyclePartitionPB part_pb;
2894
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2895
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2896
0
            return -1;
2897
0
        }
2898
2
        int64_t current_time = ::time(nullptr);
2899
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2900
2
                                                            &earlest_ts)) { // not expired
2901
0
            return 0;
2902
0
        }
2903
2
        ++num_expired;
2904
        // decode partition_id
2905
2
        auto k1 = k;
2906
2
        k1.remove_prefix(1);
2907
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2908
2
        decode_key(&k1, &out);
2909
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2910
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2911
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2912
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2913
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2914
        // Change state to RECYCLING
2915
2
        std::unique_ptr<Transaction> txn;
2916
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2917
2
        if (err != TxnErrorCode::TXN_OK) {
2918
0
            LOG_WARNING("failed to create txn").tag("err", err);
2919
0
            return -1;
2920
0
        }
2921
2
        std::string val;
2922
2
        err = txn->get(k, &val);
2923
2
        if (err ==
2924
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2925
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2926
0
            return 0;
2927
0
        }
2928
2
        if (err != TxnErrorCode::TXN_OK) {
2929
0
            LOG_WARNING("failed to get kv");
2930
0
            return -1;
2931
0
        }
2932
2
        part_pb.Clear();
2933
2
        if (!part_pb.ParseFromString(val)) {
2934
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2935
0
            return -1;
2936
0
        }
2937
        // Partitions with PREPARED state MUST have no data
2938
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2939
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2940
1
            txn->put(k, part_pb.SerializeAsString());
2941
1
            err = txn->commit();
2942
1
            if (err != TxnErrorCode::TXN_OK) {
2943
0
                LOG_WARNING("failed to commit txn: {}", err);
2944
0
                return -1;
2945
0
            }
2946
1
        }
2947
2948
2
        int ret = 0;
2949
2
        for (int64_t index_id : part_pb.index_id()) {
2950
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2951
1
                LOG_WARNING("failed to recycle tablets under partition")
2952
1
                        .tag("table_id", part_pb.table_id())
2953
1
                        .tag("instance_id", instance_id_)
2954
1
                        .tag("index_id", index_id)
2955
1
                        .tag("partition_id", partition_id);
2956
1
                ret = -1;
2957
1
            }
2958
2
        }
2959
2
        if (ret == 0 && part_pb.has_db_id() &&
2960
2
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
2961
1
                                                   partition_id, part_pb.table_streams()) != 0) {
2962
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
2963
0
                    .tag("instance_id", instance_id_)
2964
0
                    .tag("table_id", part_pb.table_id())
2965
0
                    .tag("partition_id", partition_id);
2966
0
            ret = -1;
2967
0
        }
2968
2
        if (ret == 0 && part_pb.has_db_id()) {
2969
            // Recycle the versioned keys
2970
1
            std::unique_ptr<Transaction> txn;
2971
1
            err = txn_kv_->create_txn(&txn);
2972
1
            if (err != TxnErrorCode::TXN_OK) {
2973
0
                LOG_WARNING("failed to create txn").tag("err", err);
2974
0
                return -1;
2975
0
            }
2976
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2977
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2978
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2979
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2980
1
            std::string partition_version_key =
2981
1
                    versioned::partition_version_key({instance_id_, partition_id});
2982
1
            versioned_remove_all(txn.get(), meta_key);
2983
1
            txn->remove(index_key);
2984
1
            txn->remove(inverted_index_key);
2985
1
            versioned_remove_all(txn.get(), partition_version_key);
2986
1
            err = txn->commit();
2987
1
            if (err != TxnErrorCode::TXN_OK) {
2988
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2989
0
                return -1;
2990
0
            }
2991
1
        }
2992
2993
2
        if (ret == 0) {
2994
1
            ++num_recycled;
2995
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2996
1
            partition_keys.push_back(k);
2997
1
            if (part_pb.db_id() > 0) {
2998
1
                partition_version_keys.push_back(partition_version_key(
2999
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3000
1
            }
3001
1
            metrics_context.total_recycled_num = num_recycled;
3002
1
            metrics_context.report();
3003
1
        }
3004
2
        return ret;
3005
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2891
9
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2892
9
        ++num_scanned;
2893
9
        RecyclePartitionPB part_pb;
2894
9
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2895
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2896
0
            return -1;
2897
0
        }
2898
9
        int64_t current_time = ::time(nullptr);
2899
9
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2900
9
                                                            &earlest_ts)) { // not expired
2901
0
            return 0;
2902
0
        }
2903
9
        ++num_expired;
2904
        // decode partition_id
2905
9
        auto k1 = k;
2906
9
        k1.remove_prefix(1);
2907
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2908
9
        decode_key(&k1, &out);
2909
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2910
9
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2911
9
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2912
9
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2913
9
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2914
        // Change state to RECYCLING
2915
9
        std::unique_ptr<Transaction> txn;
2916
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2917
9
        if (err != TxnErrorCode::TXN_OK) {
2918
0
            LOG_WARNING("failed to create txn").tag("err", err);
2919
0
            return -1;
2920
0
        }
2921
9
        std::string val;
2922
9
        err = txn->get(k, &val);
2923
9
        if (err ==
2924
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2925
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2926
0
            return 0;
2927
0
        }
2928
9
        if (err != TxnErrorCode::TXN_OK) {
2929
0
            LOG_WARNING("failed to get kv");
2930
0
            return -1;
2931
0
        }
2932
9
        part_pb.Clear();
2933
9
        if (!part_pb.ParseFromString(val)) {
2934
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2935
0
            return -1;
2936
0
        }
2937
        // Partitions with PREPARED state MUST have no data
2938
9
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2939
9
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2940
9
            txn->put(k, part_pb.SerializeAsString());
2941
9
            err = txn->commit();
2942
9
            if (err != TxnErrorCode::TXN_OK) {
2943
0
                LOG_WARNING("failed to commit txn: {}", err);
2944
0
                return -1;
2945
0
            }
2946
9
        }
2947
2948
9
        int ret = 0;
2949
33
        for (int64_t index_id : part_pb.index_id()) {
2950
33
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2951
0
                LOG_WARNING("failed to recycle tablets under partition")
2952
0
                        .tag("table_id", part_pb.table_id())
2953
0
                        .tag("instance_id", instance_id_)
2954
0
                        .tag("index_id", index_id)
2955
0
                        .tag("partition_id", partition_id);
2956
0
                ret = -1;
2957
0
            }
2958
33
        }
2959
9
        if (ret == 0 && part_pb.has_db_id() &&
2960
9
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
2961
9
                                                   partition_id, part_pb.table_streams()) != 0) {
2962
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
2963
0
                    .tag("instance_id", instance_id_)
2964
0
                    .tag("table_id", part_pb.table_id())
2965
0
                    .tag("partition_id", partition_id);
2966
0
            ret = -1;
2967
0
        }
2968
9
        if (ret == 0 && part_pb.has_db_id()) {
2969
            // Recycle the versioned keys
2970
9
            std::unique_ptr<Transaction> txn;
2971
9
            err = txn_kv_->create_txn(&txn);
2972
9
            if (err != TxnErrorCode::TXN_OK) {
2973
0
                LOG_WARNING("failed to create txn").tag("err", err);
2974
0
                return -1;
2975
0
            }
2976
9
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2977
9
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2978
9
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2979
9
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2980
9
            std::string partition_version_key =
2981
9
                    versioned::partition_version_key({instance_id_, partition_id});
2982
9
            versioned_remove_all(txn.get(), meta_key);
2983
9
            txn->remove(index_key);
2984
9
            txn->remove(inverted_index_key);
2985
9
            versioned_remove_all(txn.get(), partition_version_key);
2986
9
            err = txn->commit();
2987
9
            if (err != TxnErrorCode::TXN_OK) {
2988
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2989
0
                return -1;
2990
0
            }
2991
9
        }
2992
2993
9
        if (ret == 0) {
2994
9
            ++num_recycled;
2995
9
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2996
9
            partition_keys.push_back(k);
2997
9
            if (part_pb.db_id() > 0) {
2998
9
                partition_version_keys.push_back(partition_version_key(
2999
9
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3000
9
            }
3001
9
            metrics_context.total_recycled_num = num_recycled;
3002
9
            metrics_context.report();
3003
9
        }
3004
9
        return ret;
3005
9
    };
3006
3007
17
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3008
7
        if (partition_keys.empty()) return 0;
3009
6
        DORIS_CLOUD_DEFER {
3010
6
            partition_keys.clear();
3011
6
            partition_version_keys.clear();
3012
6
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3009
1
        DORIS_CLOUD_DEFER {
3010
1
            partition_keys.clear();
3011
1
            partition_version_keys.clear();
3012
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3009
5
        DORIS_CLOUD_DEFER {
3010
5
            partition_keys.clear();
3011
5
            partition_version_keys.clear();
3012
5
        };
3013
6
        std::unique_ptr<Transaction> txn;
3014
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3015
6
        if (err != TxnErrorCode::TXN_OK) {
3016
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3017
0
            return -1;
3018
0
        }
3019
10
        for (auto& k : partition_keys) {
3020
10
            txn->remove(k);
3021
10
        }
3022
10
        for (auto& k : partition_version_keys) {
3023
10
            txn->remove(k);
3024
10
        }
3025
6
        err = txn->commit();
3026
6
        if (err != TxnErrorCode::TXN_OK) {
3027
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3028
0
                         << " err=" << err;
3029
0
            return -1;
3030
0
        }
3031
6
        return 0;
3032
6
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3007
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3008
2
        if (partition_keys.empty()) return 0;
3009
1
        DORIS_CLOUD_DEFER {
3010
1
            partition_keys.clear();
3011
1
            partition_version_keys.clear();
3012
1
        };
3013
1
        std::unique_ptr<Transaction> txn;
3014
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3015
1
        if (err != TxnErrorCode::TXN_OK) {
3016
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3017
0
            return -1;
3018
0
        }
3019
1
        for (auto& k : partition_keys) {
3020
1
            txn->remove(k);
3021
1
        }
3022
1
        for (auto& k : partition_version_keys) {
3023
1
            txn->remove(k);
3024
1
        }
3025
1
        err = txn->commit();
3026
1
        if (err != TxnErrorCode::TXN_OK) {
3027
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3028
0
                         << " err=" << err;
3029
0
            return -1;
3030
0
        }
3031
1
        return 0;
3032
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3007
5
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3008
5
        if (partition_keys.empty()) return 0;
3009
5
        DORIS_CLOUD_DEFER {
3010
5
            partition_keys.clear();
3011
5
            partition_version_keys.clear();
3012
5
        };
3013
5
        std::unique_ptr<Transaction> txn;
3014
5
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3015
5
        if (err != TxnErrorCode::TXN_OK) {
3016
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3017
0
            return -1;
3018
0
        }
3019
9
        for (auto& k : partition_keys) {
3020
9
            txn->remove(k);
3021
9
        }
3022
9
        for (auto& k : partition_version_keys) {
3023
9
            txn->remove(k);
3024
9
        }
3025
5
        err = txn->commit();
3026
5
        if (err != TxnErrorCode::TXN_OK) {
3027
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3028
0
                         << " err=" << err;
3029
0
            return -1;
3030
0
        }
3031
5
        return 0;
3032
5
    };
3033
3034
17
    if (config::enable_recycler_stats_metrics) {
3035
0
        scan_and_statistics_partitions();
3036
0
    }
3037
    // recycle_func and loop_done for scan and recycle
3038
17
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
3039
17
}
3040
3041
14
int InstanceRecycler::recycle_versions() {
3042
14
    if (should_recycle_versioned_keys()) {
3043
2
        return recycle_orphan_partitions();
3044
2
    }
3045
3046
12
    int64_t num_scanned = 0;
3047
12
    int64_t num_recycled = 0;
3048
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
3049
3050
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
3051
3052
12
    auto start_time = steady_clock::now();
3053
3054
12
    DORIS_CLOUD_DEFER {
3055
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3056
12
        metrics_context.finish_report();
3057
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3058
12
                .tag("instance_id", instance_id_)
3059
12
                .tag("num_scanned", num_scanned)
3060
12
                .tag("num_recycled", num_recycled);
3061
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
3054
12
    DORIS_CLOUD_DEFER {
3055
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3056
12
        metrics_context.finish_report();
3057
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3058
12
                .tag("instance_id", instance_id_)
3059
12
                .tag("num_scanned", num_scanned)
3060
12
                .tag("num_recycled", num_recycled);
3061
12
    };
3062
3063
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
3064
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
3065
12
    int64_t last_scanned_table_id = 0;
3066
12
    bool is_recycled = false; // Is last scanned kv recycled
3067
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
3068
12
                         &metrics_context, this](std::string_view k, std::string_view) {
3069
2
        ++num_scanned;
3070
2
        auto k1 = k;
3071
2
        k1.remove_prefix(1);
3072
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3073
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3074
2
        decode_key(&k1, &out);
3075
2
        DCHECK_EQ(out.size(), 6) << k;
3076
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3077
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3078
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3079
0
            return 0;
3080
0
        }
3081
2
        last_scanned_table_id = table_id;
3082
2
        is_recycled = false;
3083
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3084
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3085
2
        std::unique_ptr<Transaction> txn;
3086
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3087
2
        if (err != TxnErrorCode::TXN_OK) {
3088
0
            return -1;
3089
0
        }
3090
2
        std::unique_ptr<RangeGetIterator> iter;
3091
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3092
2
        if (err != TxnErrorCode::TXN_OK) {
3093
0
            return -1;
3094
0
        }
3095
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3096
1
            return 0;
3097
1
        }
3098
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3099
        // 1. Remove all partition version kvs of this table
3100
1
        auto partition_version_key_begin =
3101
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3102
1
        auto partition_version_key_end =
3103
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3104
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3105
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3106
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3107
1
                     << " table_id=" << table_id;
3108
        // 2. Remove the table version kv of this table
3109
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3110
1
        txn->remove(tbl_version_key);
3111
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3112
        // 3. Remove mow delete bitmap update lock and tablet job lock
3113
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3114
1
        txn->remove(lock_key);
3115
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3116
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3117
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3118
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3119
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3120
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3121
1
                     << " table_id=" << table_id;
3122
1
        err = txn->commit();
3123
1
        if (err != TxnErrorCode::TXN_OK) {
3124
0
            return -1;
3125
0
        }
3126
1
        metrics_context.total_recycled_num = ++num_recycled;
3127
1
        metrics_context.report();
3128
1
        is_recycled = true;
3129
1
        return 0;
3130
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3068
2
                         &metrics_context, this](std::string_view k, std::string_view) {
3069
2
        ++num_scanned;
3070
2
        auto k1 = k;
3071
2
        k1.remove_prefix(1);
3072
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3073
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3074
2
        decode_key(&k1, &out);
3075
2
        DCHECK_EQ(out.size(), 6) << k;
3076
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3077
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3078
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3079
0
            return 0;
3080
0
        }
3081
2
        last_scanned_table_id = table_id;
3082
2
        is_recycled = false;
3083
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3084
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3085
2
        std::unique_ptr<Transaction> txn;
3086
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3087
2
        if (err != TxnErrorCode::TXN_OK) {
3088
0
            return -1;
3089
0
        }
3090
2
        std::unique_ptr<RangeGetIterator> iter;
3091
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3092
2
        if (err != TxnErrorCode::TXN_OK) {
3093
0
            return -1;
3094
0
        }
3095
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3096
1
            return 0;
3097
1
        }
3098
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3099
        // 1. Remove all partition version kvs of this table
3100
1
        auto partition_version_key_begin =
3101
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3102
1
        auto partition_version_key_end =
3103
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3104
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3105
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3106
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3107
1
                     << " table_id=" << table_id;
3108
        // 2. Remove the table version kv of this table
3109
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3110
1
        txn->remove(tbl_version_key);
3111
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3112
        // 3. Remove mow delete bitmap update lock and tablet job lock
3113
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3114
1
        txn->remove(lock_key);
3115
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3116
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3117
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3118
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3119
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3120
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3121
1
                     << " table_id=" << table_id;
3122
1
        err = txn->commit();
3123
1
        if (err != TxnErrorCode::TXN_OK) {
3124
0
            return -1;
3125
0
        }
3126
1
        metrics_context.total_recycled_num = ++num_recycled;
3127
1
        metrics_context.report();
3128
1
        is_recycled = true;
3129
1
        return 0;
3130
1
    };
3131
3132
12
    if (config::enable_recycler_stats_metrics) {
3133
0
        scan_and_statistics_versions();
3134
0
    }
3135
    // recycle_func and loop_done for scan and recycle
3136
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
3137
14
}
3138
3139
3
int InstanceRecycler::recycle_orphan_partitions() {
3140
3
    int64_t num_scanned = 0;
3141
3
    int64_t num_recycled = 0;
3142
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
3143
3144
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
3145
3
            .tag("instance_id", instance_id_);
3146
3147
3
    auto start_time = steady_clock::now();
3148
3149
3
    DORIS_CLOUD_DEFER {
3150
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3151
3
        metrics_context.finish_report();
3152
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3153
3
                .tag("instance_id", instance_id_)
3154
3
                .tag("num_scanned", num_scanned)
3155
3
                .tag("num_recycled", num_recycled);
3156
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
3149
3
    DORIS_CLOUD_DEFER {
3150
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3151
3
        metrics_context.finish_report();
3152
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3153
3
                .tag("instance_id", instance_id_)
3154
3
                .tag("num_scanned", num_scanned)
3155
3
                .tag("num_recycled", num_recycled);
3156
3
    };
3157
3158
3
    bool is_empty_table = false;        // whether the table has no indexes
3159
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
3160
3
    int64_t current_table_id = 0;       // current scanning table id
3161
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
3162
3
                         &current_table_id, &is_table_kvs_recycled,
3163
3
                         this](std::string_view k, std::string_view) {
3164
2
        ++num_scanned;
3165
3166
2
        std::string_view k1(k);
3167
2
        int64_t db_id, table_id, partition_id;
3168
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3169
2
                                                            &partition_id)) {
3170
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3171
0
            return -1;
3172
2
        } else if (table_id != current_table_id) {
3173
2
            current_table_id = table_id;
3174
2
            is_table_kvs_recycled = false;
3175
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3176
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3177
2
            if (err != TxnErrorCode::TXN_OK) {
3178
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3179
0
                             << " table_id=" << table_id << " err=" << err;
3180
0
                return -1;
3181
0
            }
3182
2
        }
3183
3184
2
        if (!is_empty_table) {
3185
            // table is not empty, skip recycle
3186
1
            return 0;
3187
1
        }
3188
3189
1
        std::unique_ptr<Transaction> txn;
3190
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3191
1
        if (err != TxnErrorCode::TXN_OK) {
3192
0
            return -1;
3193
0
        }
3194
3195
        // 1. Remove all partition related kvs
3196
1
        std::string partition_meta_key =
3197
1
                versioned::meta_partition_key({instance_id_, partition_id});
3198
1
        std::string partition_index_key =
3199
1
                versioned::partition_index_key({instance_id_, partition_id});
3200
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3201
1
                {instance_id_, db_id, table_id, partition_id});
3202
1
        std::string partition_version_key =
3203
1
                versioned::partition_version_key({instance_id_, partition_id});
3204
1
        txn->remove(partition_index_key);
3205
1
        txn->remove(partition_inverted_key);
3206
1
        versioned_remove_all(txn.get(), partition_meta_key);
3207
1
        versioned_remove_all(txn.get(), partition_version_key);
3208
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3209
1
                     << " table_id=" << table_id << " db_id=" << db_id
3210
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3211
1
                     << " partition_version_key=" << hex(partition_version_key);
3212
3213
1
        if (!is_table_kvs_recycled) {
3214
1
            is_table_kvs_recycled = true;
3215
3216
            // 2. Remove the table version kv of this table
3217
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3218
1
            versioned_remove_all(txn.get(), table_version_key);
3219
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3220
            // 3. Remove mow delete bitmap update lock and tablet job lock
3221
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3222
1
            txn->remove(lock_key);
3223
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3224
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3225
1
            std::string tablet_job_key_end =
3226
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3227
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3228
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3229
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3230
1
                         << " table_id=" << table_id;
3231
1
        }
3232
3233
1
        err = txn->commit();
3234
1
        if (err != TxnErrorCode::TXN_OK) {
3235
0
            return -1;
3236
0
        }
3237
1
        metrics_context.total_recycled_num = ++num_recycled;
3238
1
        metrics_context.report();
3239
1
        return 0;
3240
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
3163
2
                         this](std::string_view k, std::string_view) {
3164
2
        ++num_scanned;
3165
3166
2
        std::string_view k1(k);
3167
2
        int64_t db_id, table_id, partition_id;
3168
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3169
2
                                                            &partition_id)) {
3170
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3171
0
            return -1;
3172
2
        } else if (table_id != current_table_id) {
3173
2
            current_table_id = table_id;
3174
2
            is_table_kvs_recycled = false;
3175
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3176
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3177
2
            if (err != TxnErrorCode::TXN_OK) {
3178
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3179
0
                             << " table_id=" << table_id << " err=" << err;
3180
0
                return -1;
3181
0
            }
3182
2
        }
3183
3184
2
        if (!is_empty_table) {
3185
            // table is not empty, skip recycle
3186
1
            return 0;
3187
1
        }
3188
3189
1
        std::unique_ptr<Transaction> txn;
3190
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3191
1
        if (err != TxnErrorCode::TXN_OK) {
3192
0
            return -1;
3193
0
        }
3194
3195
        // 1. Remove all partition related kvs
3196
1
        std::string partition_meta_key =
3197
1
                versioned::meta_partition_key({instance_id_, partition_id});
3198
1
        std::string partition_index_key =
3199
1
                versioned::partition_index_key({instance_id_, partition_id});
3200
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3201
1
                {instance_id_, db_id, table_id, partition_id});
3202
1
        std::string partition_version_key =
3203
1
                versioned::partition_version_key({instance_id_, partition_id});
3204
1
        txn->remove(partition_index_key);
3205
1
        txn->remove(partition_inverted_key);
3206
1
        versioned_remove_all(txn.get(), partition_meta_key);
3207
1
        versioned_remove_all(txn.get(), partition_version_key);
3208
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3209
1
                     << " table_id=" << table_id << " db_id=" << db_id
3210
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3211
1
                     << " partition_version_key=" << hex(partition_version_key);
3212
3213
1
        if (!is_table_kvs_recycled) {
3214
1
            is_table_kvs_recycled = true;
3215
3216
            // 2. Remove the table version kv of this table
3217
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3218
1
            versioned_remove_all(txn.get(), table_version_key);
3219
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3220
            // 3. Remove mow delete bitmap update lock and tablet job lock
3221
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3222
1
            txn->remove(lock_key);
3223
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3224
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3225
1
            std::string tablet_job_key_end =
3226
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3227
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3228
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3229
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3230
1
                         << " table_id=" << table_id;
3231
1
        }
3232
3233
1
        err = txn->commit();
3234
1
        if (err != TxnErrorCode::TXN_OK) {
3235
0
            return -1;
3236
0
        }
3237
1
        metrics_context.total_recycled_num = ++num_recycled;
3238
1
        metrics_context.report();
3239
1
        return 0;
3240
1
    };
3241
3242
    // recycle_func and loop_done for scan and recycle
3243
3
    return scan_and_recycle(
3244
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
3245
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
3246
3
            std::move(recycle_func));
3247
3
}
3248
3249
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
3250
                                      RecyclerMetricsContext& metrics_context,
3251
54
                                      int64_t partition_id) {
3252
54
    bool is_multi_version =
3253
54
            instance_info_.has_multi_version_status() &&
3254
54
            instance_info_.multi_version_status() != MultiVersionStatus::MULTI_VERSION_DISABLED;
3255
54
    int64_t num_scanned = 0;
3256
54
    std::atomic_long num_recycled = 0;
3257
3258
54
    std::string tablet_key_begin, tablet_key_end;
3259
54
    std::string stats_key_begin, stats_key_end;
3260
54
    std::string job_key_begin, job_key_end;
3261
3262
54
    std::string tablet_belongs;
3263
54
    if (partition_id > 0) {
3264
        // recycle tablets in a partition belonging to the index
3265
35
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
3266
35
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
3267
35
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
3268
35
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
3269
35
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
3270
35
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
3271
35
        tablet_belongs = "partition";
3272
35
    } else {
3273
        // recycle tablets in the index
3274
19
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
3275
19
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
3276
19
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
3277
19
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
3278
19
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
3279
19
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
3280
19
        tablet_belongs = "index";
3281
19
    }
3282
3283
54
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
3284
54
            .tag("table_id", table_id)
3285
54
            .tag("index_id", index_id)
3286
54
            .tag("partition_id", partition_id);
3287
3288
54
    auto start_time = steady_clock::now();
3289
3290
54
    DORIS_CLOUD_DEFER {
3291
54
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3292
54
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3293
54
                .tag("instance_id", instance_id_)
3294
54
                .tag("table_id", table_id)
3295
54
                .tag("index_id", index_id)
3296
54
                .tag("partition_id", partition_id)
3297
54
                .tag("num_scanned", num_scanned)
3298
54
                .tag("num_recycled", num_recycled);
3299
54
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3290
4
    DORIS_CLOUD_DEFER {
3291
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3292
4
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3293
4
                .tag("instance_id", instance_id_)
3294
4
                .tag("table_id", table_id)
3295
4
                .tag("index_id", index_id)
3296
4
                .tag("partition_id", partition_id)
3297
4
                .tag("num_scanned", num_scanned)
3298
4
                .tag("num_recycled", num_recycled);
3299
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3290
50
    DORIS_CLOUD_DEFER {
3291
50
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3292
50
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3293
50
                .tag("instance_id", instance_id_)
3294
50
                .tag("table_id", table_id)
3295
50
                .tag("index_id", index_id)
3296
50
                .tag("partition_id", partition_id)
3297
50
                .tag("num_scanned", num_scanned)
3298
50
                .tag("num_recycled", num_recycled);
3299
50
    };
3300
3301
    // The tablet key and id which have been recycled.
3302
54
    struct TabletInfo {
3303
54
        std::string_view tablet_meta_key;
3304
54
        int64_t tablet_id;
3305
54
    };
3306
54
    SyncExecutor<TabletInfo> sync_executor(
3307
54
            _thread_pool_group.recycle_tablet_pool,
3308
54
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
3309
54
                        index_id, partition_id),
3310
4.24k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3310
4.00k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3310
241
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
3311
3312
    // Elements in `tablets_info` has the same lifetime as `it` in `scan_and_recycle`
3313
54
    std::vector<std::string> init_rs_keys;
3314
54
    bool has_failure = false;
3315
8.25k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3316
8.25k
        ++num_scanned;
3317
8.25k
        doris::TabletMetaCloudPB tablet_meta_pb;
3318
8.25k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3319
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3320
0
            has_failure = true;
3321
0
            return -1;
3322
0
        }
3323
8.25k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3324
3325
8.25k
        if (config::enable_recycler_check_lazy_txn_finished &&
3326
8.25k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3327
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3328
4.00k
            has_failure = true;
3329
4.00k
            return -1;
3330
4.00k
        }
3331
3332
4.25k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3333
4.25k
        sync_executor.add(
3334
4.25k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3335
4.25k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3336
2
                        LOG_WARNING("failed to recycle tablet")
3337
2
                                .tag("instance_id", instance_id_)
3338
2
                                .tag("tablet_id", tid);
3339
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3340
2
                    }
3341
4.25k
                    ++num_recycled;
3342
4.25k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3343
4.25k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3344
4.25k
                });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3334
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3335
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3336
0
                        LOG_WARNING("failed to recycle tablet")
3337
0
                                .tag("instance_id", instance_id_)
3338
0
                                .tag("tablet_id", tid);
3339
0
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3340
0
                    }
3341
4.00k
                    ++num_recycled;
3342
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3343
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3344
4.00k
                });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3334
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3335
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3336
2
                        LOG_WARNING("failed to recycle tablet")
3337
2
                                .tag("instance_id", instance_id_)
3338
2
                                .tag("tablet_id", tid);
3339
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3340
2
                    }
3341
248
                    ++num_recycled;
3342
248
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3343
248
                    return {.tablet_meta_key = k, .tablet_id = tid};
3344
250
                });
3345
4.25k
        return 0;
3346
4.25k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3315
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3316
8.00k
        ++num_scanned;
3317
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
3318
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3319
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3320
0
            has_failure = true;
3321
0
            return -1;
3322
0
        }
3323
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3324
3325
8.00k
        if (config::enable_recycler_check_lazy_txn_finished &&
3326
8.00k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3327
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3328
4.00k
            has_failure = true;
3329
4.00k
            return -1;
3330
4.00k
        }
3331
3332
4.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3333
4.00k
        sync_executor.add(
3334
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3335
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3336
4.00k
                        LOG_WARNING("failed to recycle tablet")
3337
4.00k
                                .tag("instance_id", instance_id_)
3338
4.00k
                                .tag("tablet_id", tid);
3339
4.00k
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3340
4.00k
                    }
3341
4.00k
                    ++num_recycled;
3342
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3343
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3344
4.00k
                });
3345
4.00k
        return 0;
3346
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3315
251
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3316
251
        ++num_scanned;
3317
251
        doris::TabletMetaCloudPB tablet_meta_pb;
3318
251
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3319
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3320
0
            has_failure = true;
3321
0
            return -1;
3322
0
        }
3323
251
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3324
3325
251
        if (config::enable_recycler_check_lazy_txn_finished &&
3326
251
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3327
1
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3328
1
            has_failure = true;
3329
1
            return -1;
3330
1
        }
3331
3332
250
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3333
250
        sync_executor.add(
3334
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3335
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3336
250
                        LOG_WARNING("failed to recycle tablet")
3337
250
                                .tag("instance_id", instance_id_)
3338
250
                                .tag("tablet_id", tid);
3339
250
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3340
250
                    }
3341
250
                    ++num_recycled;
3342
250
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3343
250
                    return {.tablet_meta_key = k, .tablet_id = tid};
3344
250
                });
3345
250
        return 0;
3346
250
    };
3347
3348
54
    auto loop_done = [&, this]() -> int {
3349
52
        int ret = 0;
3350
52
        bool finished = true;
3351
52
        bool has_empty_key = false;
3352
52
        DORIS_CLOUD_DEFER {
3353
52
            init_rs_keys.clear();
3354
52
            has_failure = false;
3355
52
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3352
4
        DORIS_CLOUD_DEFER {
3353
4
            init_rs_keys.clear();
3354
4
            has_failure = false;
3355
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3352
48
        DORIS_CLOUD_DEFER {
3353
48
            init_rs_keys.clear();
3354
48
            has_failure = false;
3355
48
        };
3356
52
        auto tablets_info = sync_executor.when_all(&finished);
3357
52
        if (!finished) {
3358
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3359
1
            return -1;
3360
1
        }
3361
3362
51
        size_t size_before_erase = tablets_info.size();
3363
4.25k
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKZNS1_15recycle_tabletsEllS3_lE10TabletInfoE_clES7_
Line
Count
Source
3363
4.00k
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKZNS1_15recycle_tabletsEllS3_lE10TabletInfoE_clES7_
Line
Count
Source
3363
249
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3364
51
        if (tablets_info.empty()) {
3365
2
            return size_before_erase == 0 ? 0 : -1;
3366
49
        } else if (size_before_erase != tablets_info.size()) {
3367
1
            has_empty_key = true;
3368
1
        }
3369
3370
49
        ret = has_empty_key ? -1 : 0;
3371
        // sort the vector using key's order
3372
49.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3373
49.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3374
49.4k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3372
48.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3373
48.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3374
48.4k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3372
958
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3373
958
            return prev.tablet_meta_key < last.tablet_meta_key;
3374
958
        });
3375
49
        std::unique_ptr<Transaction> txn;
3376
49
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3377
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3378
0
            return -1;
3379
0
        }
3380
49
        std::string tablet_key_end;
3381
49
        if (!tablets_info.empty()) {
3382
49
            if (!has_empty_key && !has_failure) {
3383
47
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3384
47
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3385
47
            } else {
3386
8
                for (auto& tablet_info : tablets_info) {
3387
8
                    txn->remove(tablet_info.tablet_meta_key);
3388
8
                }
3389
2
            }
3390
49
        }
3391
49
        if (is_multi_version) {
3392
6
            for (auto& tablet_info : tablets_info) {
3393
                // Remove all versions of tablet compact stats for recycled tablet
3394
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3395
6
                LOG_INFO("remove versioned tablet compact stats key")
3396
6
                        .tag("compact_stats_key", hex(k));
3397
6
                versioned_remove_all(txn.get(), k);
3398
6
            }
3399
6
            for (auto& tablet_info : tablets_info) {
3400
                // Remove all versions of tablet load stats for recycled tablet
3401
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3402
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3403
6
                versioned_remove_all(txn.get(), k);
3404
6
            }
3405
6
            for (auto& tablet_info : tablets_info) {
3406
                // Remove all versions of meta tablet for recycled tablet
3407
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3408
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3409
6
                versioned_remove_all(txn.get(), k);
3410
6
            }
3411
5
        }
3412
4.25k
        for (auto& tablet_info : tablets_info) {
3413
4.25k
            std::string k;
3414
4.25k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3415
4.25k
            txn->remove(k);
3416
4.25k
        }
3417
4.25k
        for (auto& tablet_info : tablets_info) {
3418
4.25k
            std::string k;
3419
4.25k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3420
4.25k
            txn->remove(k);
3421
4.25k
        }
3422
49
        for (auto& k : init_rs_keys) {
3423
0
            txn->remove(k);
3424
0
        }
3425
49
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3426
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3427
0
                         << ", err=" << err;
3428
0
            return -1;
3429
0
        }
3430
49
        return ret;
3431
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
3348
4
    auto loop_done = [&, this]() -> int {
3349
4
        int ret = 0;
3350
4
        bool finished = true;
3351
4
        bool has_empty_key = false;
3352
4
        DORIS_CLOUD_DEFER {
3353
4
            init_rs_keys.clear();
3354
4
            has_failure = false;
3355
4
        };
3356
4
        auto tablets_info = sync_executor.when_all(&finished);
3357
4
        if (!finished) {
3358
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3359
0
            return -1;
3360
0
        }
3361
3362
4
        size_t size_before_erase = tablets_info.size();
3363
4
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3364
4
        if (tablets_info.empty()) {
3365
2
            return size_before_erase == 0 ? 0 : -1;
3366
2
        } else if (size_before_erase != tablets_info.size()) {
3367
0
            has_empty_key = true;
3368
0
        }
3369
3370
2
        ret = has_empty_key ? -1 : 0;
3371
        // sort the vector using key's order
3372
2
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3373
2
            return prev.tablet_meta_key < last.tablet_meta_key;
3374
2
        });
3375
2
        std::unique_ptr<Transaction> txn;
3376
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3377
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3378
0
            return -1;
3379
0
        }
3380
2
        std::string tablet_key_end;
3381
2
        if (!tablets_info.empty()) {
3382
2
            if (!has_empty_key && !has_failure) {
3383
2
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3384
2
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3385
2
            } else {
3386
0
                for (auto& tablet_info : tablets_info) {
3387
0
                    txn->remove(tablet_info.tablet_meta_key);
3388
0
                }
3389
0
            }
3390
2
        }
3391
2
        if (is_multi_version) {
3392
0
            for (auto& tablet_info : tablets_info) {
3393
                // Remove all versions of tablet compact stats for recycled tablet
3394
0
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3395
0
                LOG_INFO("remove versioned tablet compact stats key")
3396
0
                        .tag("compact_stats_key", hex(k));
3397
0
                versioned_remove_all(txn.get(), k);
3398
0
            }
3399
0
            for (auto& tablet_info : tablets_info) {
3400
                // Remove all versions of tablet load stats for recycled tablet
3401
0
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3402
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3403
0
                versioned_remove_all(txn.get(), k);
3404
0
            }
3405
0
            for (auto& tablet_info : tablets_info) {
3406
                // Remove all versions of meta tablet for recycled tablet
3407
0
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3408
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3409
0
                versioned_remove_all(txn.get(), k);
3410
0
            }
3411
0
        }
3412
4.00k
        for (auto& tablet_info : tablets_info) {
3413
4.00k
            std::string k;
3414
4.00k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3415
4.00k
            txn->remove(k);
3416
4.00k
        }
3417
4.00k
        for (auto& tablet_info : tablets_info) {
3418
4.00k
            std::string k;
3419
4.00k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3420
4.00k
            txn->remove(k);
3421
4.00k
        }
3422
2
        for (auto& k : init_rs_keys) {
3423
0
            txn->remove(k);
3424
0
        }
3425
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3426
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3427
0
                         << ", err=" << err;
3428
0
            return -1;
3429
0
        }
3430
2
        return ret;
3431
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
3348
48
    auto loop_done = [&, this]() -> int {
3349
48
        int ret = 0;
3350
48
        bool finished = true;
3351
48
        bool has_empty_key = false;
3352
48
        DORIS_CLOUD_DEFER {
3353
48
            init_rs_keys.clear();
3354
48
            has_failure = false;
3355
48
        };
3356
48
        auto tablets_info = sync_executor.when_all(&finished);
3357
48
        if (!finished) {
3358
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3359
1
            return -1;
3360
1
        }
3361
3362
47
        size_t size_before_erase = tablets_info.size();
3363
47
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3364
47
        if (tablets_info.empty()) {
3365
0
            return size_before_erase == 0 ? 0 : -1;
3366
47
        } else if (size_before_erase != tablets_info.size()) {
3367
1
            has_empty_key = true;
3368
1
        }
3369
3370
47
        ret = has_empty_key ? -1 : 0;
3371
        // sort the vector using key's order
3372
47
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3373
47
            return prev.tablet_meta_key < last.tablet_meta_key;
3374
47
        });
3375
47
        std::unique_ptr<Transaction> txn;
3376
47
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3377
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3378
0
            return -1;
3379
0
        }
3380
47
        std::string tablet_key_end;
3381
47
        if (!tablets_info.empty()) {
3382
47
            if (!has_empty_key && !has_failure) {
3383
45
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3384
45
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3385
45
            } else {
3386
8
                for (auto& tablet_info : tablets_info) {
3387
8
                    txn->remove(tablet_info.tablet_meta_key);
3388
8
                }
3389
2
            }
3390
47
        }
3391
47
        if (is_multi_version) {
3392
6
            for (auto& tablet_info : tablets_info) {
3393
                // Remove all versions of tablet compact stats for recycled tablet
3394
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3395
6
                LOG_INFO("remove versioned tablet compact stats key")
3396
6
                        .tag("compact_stats_key", hex(k));
3397
6
                versioned_remove_all(txn.get(), k);
3398
6
            }
3399
6
            for (auto& tablet_info : tablets_info) {
3400
                // Remove all versions of tablet load stats for recycled tablet
3401
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3402
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3403
6
                versioned_remove_all(txn.get(), k);
3404
6
            }
3405
6
            for (auto& tablet_info : tablets_info) {
3406
                // Remove all versions of meta tablet for recycled tablet
3407
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3408
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3409
6
                versioned_remove_all(txn.get(), k);
3410
6
            }
3411
5
        }
3412
248
        for (auto& tablet_info : tablets_info) {
3413
248
            std::string k;
3414
248
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3415
248
            txn->remove(k);
3416
248
        }
3417
248
        for (auto& tablet_info : tablets_info) {
3418
248
            std::string k;
3419
248
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3420
248
            txn->remove(k);
3421
248
        }
3422
47
        for (auto& k : init_rs_keys) {
3423
0
            txn->remove(k);
3424
0
        }
3425
47
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3426
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3427
0
                         << ", err=" << err;
3428
0
            return -1;
3429
0
        }
3430
47
        return ret;
3431
47
    };
3432
3433
54
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
3434
54
                               std::move(loop_done));
3435
54
    if (ret != 0) {
3436
5
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
3437
5
        return ret;
3438
5
    }
3439
3440
    // directly remove tablet stats and tablet jobs of these dropped index or partition
3441
49
    std::unique_ptr<Transaction> txn;
3442
49
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3443
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
3444
0
        return -1;
3445
0
    }
3446
49
    txn->remove(stats_key_begin, stats_key_end);
3447
49
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
3448
49
                 << " end=" << hex(stats_key_end);
3449
49
    txn->remove(job_key_begin, job_key_end);
3450
49
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
3451
49
    std::string schema_key_begin, schema_key_end;
3452
49
    std::string schema_dict_key;
3453
49
    std::string versioned_schema_key_begin, versioned_schema_key_end;
3454
49
    if (partition_id <= 0) {
3455
        // Delete schema kv of this index
3456
15
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
3457
15
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
3458
15
        txn->remove(schema_key_begin, schema_key_end);
3459
15
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
3460
15
                     << " end=" << hex(schema_key_end);
3461
15
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
3462
15
        txn->remove(schema_dict_key);
3463
15
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
3464
15
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
3465
15
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
3466
15
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
3467
15
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
3468
15
                     << " end=" << hex(versioned_schema_key_end);
3469
15
    }
3470
3471
49
    TxnErrorCode err = txn->commit();
3472
49
    if (err != TxnErrorCode::TXN_OK) {
3473
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
3474
0
                     << " err=" << err;
3475
0
        return -1;
3476
0
    }
3477
3478
49
    return ret;
3479
49
}
3480
3481
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
3482
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
3483
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
3484
5.61k
    if (num_segments <= 0) return 0;
3485
3486
5.61k
    std::vector<std::string> file_paths;
3487
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
3488
0
        return -1;
3489
0
    }
3490
3491
    // Process inverted indexes
3492
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
3493
5.61k
    InvertedIndexStorageFormatPB index_format = rs_meta_pb.has_inverted_index_storage_format()
3494
5.61k
                                                        ? rs_meta_pb.inverted_index_storage_format()
3495
5.61k
                                                        : InvertedIndexStorageFormatPB::V1;
3496
5.61k
    bool delete_rowset_data_by_prefix = false;
3497
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3498
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3499
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3500
0
        delete_rowset_data_by_prefix = true;
3501
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
3502
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
3503
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3504
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3505
10.0k
            }
3506
10.0k
        }
3507
4.80k
        if (!rs_meta_pb.has_inverted_index_storage_format() &&
3508
4.80k
            rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
3509
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
3510
2.00k
        }
3511
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
3512
        // schema version and index id are not found, delete rowset data by prefix directly.
3513
0
        delete_rowset_data_by_prefix = true;
3514
809
    } else {
3515
        // otherwise, try to get schema kv
3516
809
        InvertedIndexInfo index_info;
3517
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
3518
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
3519
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3520
809
                                 &inverted_index_get_ret);
3521
809
        if (inverted_index_get_ret == 0) {
3522
809
            if (!rs_meta_pb.has_inverted_index_storage_format()) {
3523
809
                index_format = index_info.first;
3524
809
            }
3525
809
            index_ids = index_info.second;
3526
809
        } else if (inverted_index_get_ret == 1) {
3527
            // 1. Schema kv not found means tablet has been recycled
3528
            // Maybe some tablet recycle failed by some bugs
3529
            // We need to delete again to double check
3530
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3531
            // because we are uncertain about the inverted index information.
3532
            // If there are inverted indexes, some data might not be deleted,
3533
            // but this is acceptable as we have made our best effort to delete the data.
3534
0
            LOG_INFO(
3535
0
                    "delete rowset data schema kv not found, need to delete again to double "
3536
0
                    "check")
3537
0
                    .tag("instance_id", instance_id_)
3538
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3539
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
3540
            // Currently index_ids is guaranteed to be empty,
3541
            // but we clear it again here as a safeguard against future code changes
3542
            // that might cause index_ids to no longer be empty
3543
0
            index_format = InvertedIndexStorageFormatPB::V2;
3544
0
            index_ids.clear();
3545
0
        } else {
3546
            // failed to get schema kv, delete rowset data by prefix directly.
3547
0
            delete_rowset_data_by_prefix = true;
3548
0
        }
3549
809
    }
3550
3551
5.61k
    if (delete_rowset_data_by_prefix) {
3552
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
3553
0
                                  rs_meta_pb.rowset_id_v2());
3554
0
    }
3555
3556
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
3557
5.61k
    if (it == accessor_map_.end()) {
3558
1.59k
        LOG_WARNING("instance has no such resource id")
3559
1.59k
                .tag("instance_id", instance_id_)
3560
1.59k
                .tag("resource_id", rs_meta_pb.resource_id());
3561
1.59k
        return -1;
3562
1.59k
    }
3563
4.01k
    auto& accessor = it->second;
3564
3565
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
3566
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
3567
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
3568
20.0k
        add_file_to_delete_if_not_packed(rs_meta_pb, segment_path(tablet_id, rowset_id, i),
3569
20.0k
                                         &file_paths);
3570
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
3571
40.0k
            for (const auto& index_id : index_ids) {
3572
40.0k
                add_file_to_delete_if_not_packed(
3573
40.0k
                        rs_meta_pb,
3574
40.0k
                        inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
3575
40.0k
                                               index_id.second),
3576
40.0k
                        &file_paths);
3577
40.0k
            }
3578
20.0k
        } else if (!index_ids.empty()) {
3579
0
            add_file_to_delete_if_not_packed(
3580
0
                    rs_meta_pb, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
3581
0
        }
3582
20.0k
    }
3583
3584
    // Process delete bitmap - check where it's stored.
3585
4.01k
    DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3586
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3587
4.01k
                                                       &delete_bitmap_storage_type) != 0) {
3588
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3589
0
                .tag("instance_id", instance_id_)
3590
0
                .tag("tablet_id", tablet_id)
3591
0
                .tag("rowset_id", rowset_id);
3592
0
        return -1;
3593
0
    }
3594
4.01k
    if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3595
2.00k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3596
2.00k
    }
3597
    // TODO(AlexYue): seems could do do batch
3598
4.01k
    return accessor->delete_files(file_paths);
3599
4.01k
}
3600
3601
62.3k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3602
62.3k
    LOG_INFO("begin process_packed_file_location_index")
3603
62.3k
            .tag("instance_id", instance_id_)
3604
62.3k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3605
62.3k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3606
62.3k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3607
62.3k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3608
62.3k
    if (index_map.empty()) {
3609
62.3k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3610
62.3k
                .tag("instance_id", instance_id_)
3611
62.3k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3612
62.3k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3613
62.3k
        return 0;
3614
62.3k
    }
3615
3616
11
    struct PackedSmallFileInfo {
3617
11
        std::string small_file_path;
3618
11
    };
3619
11
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3620
11
    packed_file_updates.reserve(index_map.size());
3621
27
    for (const auto& [small_path, index_pb] : index_map) {
3622
27
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3623
0
            continue;
3624
0
        }
3625
27
        packed_file_updates[index_pb.packed_file_path()].push_back(
3626
27
                PackedSmallFileInfo {small_path});
3627
27
    }
3628
11
    if (packed_file_updates.empty()) {
3629
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3630
0
                .tag("instance_id", instance_id_)
3631
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3632
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3633
0
                .tag("index_map_size", index_map.size());
3634
0
        return 0;
3635
0
    }
3636
3637
11
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3638
11
    int ret = 0;
3639
24
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3640
24
        if (small_files.empty()) {
3641
0
            continue;
3642
0
        }
3643
3644
24
        bool success = false;
3645
24
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3646
24
            std::unique_ptr<Transaction> txn;
3647
24
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3648
24
            if (err != TxnErrorCode::TXN_OK) {
3649
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3650
0
                        .tag("instance_id", instance_id_)
3651
0
                        .tag("packed_file_path", packed_file_path)
3652
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3653
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3654
0
                        .tag("err", err);
3655
0
                ret = -1;
3656
0
                break;
3657
0
            }
3658
3659
24
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3660
24
            std::string packed_val;
3661
24
            err = txn->get(packed_key, &packed_val);
3662
24
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3663
0
                LOG_WARNING("packed file info not found when recycling rowset")
3664
0
                        .tag("instance_id", instance_id_)
3665
0
                        .tag("packed_file_path", packed_file_path)
3666
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3667
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3668
0
                        .tag("key", hex(packed_key))
3669
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3670
                // Skip this packed file entry and continue with others
3671
0
                success = true;
3672
0
                break;
3673
0
            }
3674
24
            if (err != TxnErrorCode::TXN_OK) {
3675
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
3676
0
                        .tag("instance_id", instance_id_)
3677
0
                        .tag("packed_file_path", packed_file_path)
3678
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3679
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3680
0
                        .tag("err", err);
3681
0
                ret = -1;
3682
0
                break;
3683
0
            }
3684
3685
24
            cloud::PackedFileInfoPB packed_info;
3686
24
            if (!packed_info.ParseFromString(packed_val)) {
3687
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
3688
0
                        .tag("instance_id", instance_id_)
3689
0
                        .tag("packed_file_path", packed_file_path)
3690
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3691
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3692
0
                ret = -1;
3693
0
                break;
3694
0
            }
3695
3696
24
            LOG_INFO("packed file update check")
3697
24
                    .tag("instance_id", instance_id_)
3698
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3699
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3700
24
                    .tag("merged_file_path", packed_file_path)
3701
24
                    .tag("requested_small_files", small_files.size())
3702
24
                    .tag("merge_entries", packed_info.slices_size());
3703
3704
24
            auto* small_file_entries = packed_info.mutable_slices();
3705
24
            int64_t changed_files = 0;
3706
24
            int64_t missing_entries = 0;
3707
24
            int64_t already_deleted = 0;
3708
27
            for (const auto& small_file_info : small_files) {
3709
27
                bool found = false;
3710
87
                for (auto& small_file_entry : *small_file_entries) {
3711
87
                    if (small_file_entry.path() == small_file_info.small_file_path) {
3712
27
                        if (!small_file_entry.deleted()) {
3713
27
                            small_file_entry.set_deleted(true);
3714
27
                            if (!small_file_entry.corrected()) {
3715
27
                                small_file_entry.set_corrected(true);
3716
27
                            }
3717
27
                            ++changed_files;
3718
27
                        } else {
3719
0
                            ++already_deleted;
3720
0
                        }
3721
27
                        found = true;
3722
27
                        break;
3723
27
                    }
3724
87
                }
3725
27
                if (!found) {
3726
0
                    ++missing_entries;
3727
0
                    LOG_WARNING("packed file info missing small file entry")
3728
0
                            .tag("instance_id", instance_id_)
3729
0
                            .tag("packed_file_path", packed_file_path)
3730
0
                            .tag("small_file_path", small_file_info.small_file_path)
3731
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3732
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
3733
0
                }
3734
27
            }
3735
3736
24
            if (changed_files == 0) {
3737
0
                LOG_INFO("skip merge file update: no merge entries changed")
3738
0
                        .tag("instance_id", instance_id_)
3739
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3740
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3741
0
                        .tag("merged_file_path", packed_file_path)
3742
0
                        .tag("missing_entries", missing_entries)
3743
0
                        .tag("already_deleted", already_deleted)
3744
0
                        .tag("requested_small_files", small_files.size())
3745
0
                        .tag("merge_entries", packed_info.slices_size());
3746
0
                success = true;
3747
0
                break;
3748
0
            }
3749
3750
            // Calculate remaining files
3751
24
            int64_t left_file_count = 0;
3752
24
            int64_t left_file_bytes = 0;
3753
141
            for (const auto& small_file_entry : packed_info.slices()) {
3754
141
                if (!small_file_entry.deleted()) {
3755
57
                    ++left_file_count;
3756
57
                    left_file_bytes += small_file_entry.size();
3757
57
                }
3758
141
            }
3759
24
            packed_info.set_remaining_slice_bytes(left_file_bytes);
3760
24
            packed_info.set_ref_cnt(left_file_count);
3761
24
            LOG_INFO("updated packed file reference info")
3762
24
                    .tag("instance_id", instance_id_)
3763
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3764
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3765
24
                    .tag("packed_file_path", packed_file_path)
3766
24
                    .tag("ref_cnt", left_file_count)
3767
24
                    .tag("left_file_bytes", left_file_bytes);
3768
3769
24
            if (left_file_count == 0) {
3770
7
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3771
7
            }
3772
3773
24
            std::string updated_val;
3774
24
            if (!packed_info.SerializeToString(&updated_val)) {
3775
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
3776
0
                        .tag("instance_id", instance_id_)
3777
0
                        .tag("packed_file_path", packed_file_path)
3778
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3779
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3780
0
                ret = -1;
3781
0
                break;
3782
0
            }
3783
3784
24
            txn->put(packed_key, updated_val);
3785
24
            err = txn->commit();
3786
24
            if (err == TxnErrorCode::TXN_OK) {
3787
24
                success = true;
3788
24
                if (left_file_count == 0) {
3789
7
                    LOG_INFO("packed file ready to delete, deleting immediately")
3790
7
                            .tag("instance_id", instance_id_)
3791
7
                            .tag("packed_file_path", packed_file_path);
3792
7
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3793
0
                        ret = -1;
3794
0
                    }
3795
7
                }
3796
24
                break;
3797
24
            }
3798
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
3799
0
                if (attempt >= max_retry_times) {
3800
0
                    LOG_WARNING("packed file info update conflict after max retry")
3801
0
                            .tag("instance_id", instance_id_)
3802
0
                            .tag("packed_file_path", packed_file_path)
3803
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3804
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
3805
0
                            .tag("changed_files", changed_files)
3806
0
                            .tag("attempt", attempt);
3807
0
                    ret = -1;
3808
0
                    break;
3809
0
                }
3810
0
                LOG_WARNING("packed file info update conflict, retrying")
3811
0
                        .tag("instance_id", instance_id_)
3812
0
                        .tag("packed_file_path", packed_file_path)
3813
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3814
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3815
0
                        .tag("changed_files", changed_files)
3816
0
                        .tag("attempt", attempt);
3817
0
                sleep_for_packed_file_retry();
3818
0
                continue;
3819
0
            }
3820
3821
0
            LOG_WARNING("failed to commit packed file info update")
3822
0
                    .tag("instance_id", instance_id_)
3823
0
                    .tag("packed_file_path", packed_file_path)
3824
0
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3825
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3826
0
                    .tag("err", err)
3827
0
                    .tag("changed_files", changed_files);
3828
0
            ret = -1;
3829
0
            break;
3830
0
        }
3831
3832
24
        if (!success) {
3833
0
            ret = -1;
3834
0
        }
3835
24
    }
3836
3837
11
    return ret;
3838
11
}
3839
3840
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(
3841
        int64_t tablet_id, const std::string& rowset_id,
3842
58.2k
        DeleteBitmapStorageType* out_storage_type) {
3843
58.2k
    if (out_storage_type) {
3844
58.2k
        *out_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3845
58.2k
    }
3846
3847
    // Get delete bitmap storage info from FDB
3848
58.2k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
3849
58.2k
    std::unique_ptr<Transaction> txn;
3850
58.2k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
3851
58.2k
    if (err != TxnErrorCode::TXN_OK) {
3852
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
3853
0
                .tag("instance_id", instance_id_)
3854
0
                .tag("tablet_id", tablet_id)
3855
0
                .tag("rowset_id", rowset_id)
3856
0
                .tag("err", err);
3857
0
        return -1;
3858
0
    }
3859
3860
58.2k
    ValueBuf dbm_val;
3861
58.2k
    err = cloud::blob_get(txn.get(), dbm_key, &dbm_val);
3862
58.2k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3863
        // No delete bitmap for this rowset, nothing to do
3864
4.66k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
3865
4.66k
                .tag("instance_id", instance_id_)
3866
4.66k
                .tag("tablet_id", tablet_id)
3867
4.66k
                .tag("rowset_id", rowset_id);
3868
4.66k
        return 0;
3869
4.66k
    }
3870
53.5k
    if (err != TxnErrorCode::TXN_OK) {
3871
0
        LOG_WARNING("failed to get delete bitmap storage")
3872
0
                .tag("instance_id", instance_id_)
3873
0
                .tag("tablet_id", tablet_id)
3874
0
                .tag("rowset_id", rowset_id)
3875
0
                .tag("err", err);
3876
0
        return -1;
3877
0
    }
3878
3879
53.5k
    DeleteBitmapStoragePB storage;
3880
53.5k
    if (!dbm_val.to_pb(&storage)) {
3881
0
        LOG_WARNING("failed to parse delete bitmap storage")
3882
0
                .tag("instance_id", instance_id_)
3883
0
                .tag("tablet_id", tablet_id)
3884
0
                .tag("rowset_id", rowset_id);
3885
0
        return -1;
3886
0
    }
3887
3888
53.5k
    if (storage.store_in_fdb()) {
3889
0
        if (out_storage_type) {
3890
0
            *out_storage_type = DeleteBitmapStorageType::IN_FDB;
3891
0
        }
3892
0
        return 0;
3893
0
    }
3894
3895
    // Check if delete bitmap is stored in standalone file.
3896
53.5k
    if (!storage.has_packed_slice_location() ||
3897
53.5k
        storage.packed_slice_location().packed_file_path().empty()) {
3898
53.5k
        if (out_storage_type) {
3899
53.5k
            *out_storage_type = DeleteBitmapStorageType::STANDALONE_FILE;
3900
53.5k
        }
3901
53.5k
        return 0;
3902
53.5k
    }
3903
3904
18.4E
    if (out_storage_type) {
3905
0
        *out_storage_type = DeleteBitmapStorageType::PACKED_FILE;
3906
0
    }
3907
3908
18.4E
    const auto& packed_loc = storage.packed_slice_location();
3909
18.4E
    const std::string& packed_file_path = packed_loc.packed_file_path();
3910
3911
18.4E
    LOG_INFO("decrementing delete bitmap packed file ref count")
3912
18.4E
            .tag("instance_id", instance_id_)
3913
18.4E
            .tag("tablet_id", tablet_id)
3914
18.4E
            .tag("rowset_id", rowset_id)
3915
18.4E
            .tag("packed_file_path", packed_file_path);
3916
3917
18.4E
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3918
18.4E
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3919
0
        std::unique_ptr<Transaction> update_txn;
3920
0
        err = txn_kv_->create_txn(&update_txn);
3921
0
        if (err != TxnErrorCode::TXN_OK) {
3922
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
3923
0
                    .tag("instance_id", instance_id_)
3924
0
                    .tag("tablet_id", tablet_id)
3925
0
                    .tag("rowset_id", rowset_id)
3926
0
                    .tag("err", err);
3927
0
            return -1;
3928
0
        }
3929
3930
0
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3931
0
        std::string packed_val;
3932
0
        err = update_txn->get(packed_key, &packed_val);
3933
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3934
0
            LOG_WARNING("packed file info not found for delete bitmap")
3935
0
                    .tag("instance_id", instance_id_)
3936
0
                    .tag("tablet_id", tablet_id)
3937
0
                    .tag("rowset_id", rowset_id)
3938
0
                    .tag("packed_file_path", packed_file_path);
3939
0
            return 0;
3940
0
        }
3941
0
        if (err != TxnErrorCode::TXN_OK) {
3942
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
3943
0
                    .tag("instance_id", instance_id_)
3944
0
                    .tag("tablet_id", tablet_id)
3945
0
                    .tag("rowset_id", rowset_id)
3946
0
                    .tag("packed_file_path", packed_file_path)
3947
0
                    .tag("err", err);
3948
0
            return -1;
3949
0
        }
3950
3951
0
        cloud::PackedFileInfoPB packed_info;
3952
0
        if (!packed_info.ParseFromString(packed_val)) {
3953
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
3954
0
                    .tag("instance_id", instance_id_)
3955
0
                    .tag("tablet_id", tablet_id)
3956
0
                    .tag("rowset_id", rowset_id)
3957
0
                    .tag("packed_file_path", packed_file_path);
3958
0
            return -1;
3959
0
        }
3960
3961
        // Find and mark the small file entry as deleted
3962
        // Use tablet_id and rowset_id to match entry instead of path,
3963
        // because path format may vary with path_version (with or without shard prefix)
3964
0
        auto* entries = packed_info.mutable_slices();
3965
0
        bool found = false;
3966
0
        bool already_deleted = false;
3967
0
        for (auto& entry : *entries) {
3968
0
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
3969
0
                if (!entry.deleted()) {
3970
0
                    entry.set_deleted(true);
3971
0
                    if (!entry.corrected()) {
3972
0
                        entry.set_corrected(true);
3973
0
                    }
3974
0
                } else {
3975
0
                    already_deleted = true;
3976
0
                }
3977
0
                found = true;
3978
0
                break;
3979
0
            }
3980
0
        }
3981
3982
0
        if (!found) {
3983
0
            LOG_WARNING("delete bitmap entry not found in packed file")
3984
0
                    .tag("instance_id", instance_id_)
3985
0
                    .tag("tablet_id", tablet_id)
3986
0
                    .tag("rowset_id", rowset_id)
3987
0
                    .tag("packed_file_path", packed_file_path);
3988
0
            return 0;
3989
0
        }
3990
3991
0
        if (already_deleted) {
3992
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
3993
0
                    .tag("instance_id", instance_id_)
3994
0
                    .tag("tablet_id", tablet_id)
3995
0
                    .tag("rowset_id", rowset_id)
3996
0
                    .tag("packed_file_path", packed_file_path);
3997
0
            return 0;
3998
0
        }
3999
4000
        // Calculate remaining files
4001
0
        int64_t left_file_count = 0;
4002
0
        int64_t left_file_bytes = 0;
4003
0
        for (const auto& entry : packed_info.slices()) {
4004
0
            if (!entry.deleted()) {
4005
0
                ++left_file_count;
4006
0
                left_file_bytes += entry.size();
4007
0
            }
4008
0
        }
4009
0
        packed_info.set_remaining_slice_bytes(left_file_bytes);
4010
0
        packed_info.set_ref_cnt(left_file_count);
4011
4012
0
        if (left_file_count == 0) {
4013
0
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
4014
0
        }
4015
4016
0
        std::string updated_val;
4017
0
        if (!packed_info.SerializeToString(&updated_val)) {
4018
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
4019
0
                    .tag("instance_id", instance_id_)
4020
0
                    .tag("tablet_id", tablet_id)
4021
0
                    .tag("rowset_id", rowset_id)
4022
0
                    .tag("packed_file_path", packed_file_path);
4023
0
            return -1;
4024
0
        }
4025
4026
0
        update_txn->put(packed_key, updated_val);
4027
0
        err = update_txn->commit();
4028
0
        if (err == TxnErrorCode::TXN_OK) {
4029
0
            LOG_INFO("delete bitmap packed file ref count decremented")
4030
0
                    .tag("instance_id", instance_id_)
4031
0
                    .tag("tablet_id", tablet_id)
4032
0
                    .tag("rowset_id", rowset_id)
4033
0
                    .tag("packed_file_path", packed_file_path)
4034
0
                    .tag("left_file_count", left_file_count);
4035
0
            if (left_file_count == 0) {
4036
0
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4037
0
                    return -1;
4038
0
                }
4039
0
            }
4040
0
            return 0;
4041
0
        }
4042
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4043
0
            if (attempt >= max_retry_times) {
4044
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
4045
0
                        .tag("instance_id", instance_id_)
4046
0
                        .tag("tablet_id", tablet_id)
4047
0
                        .tag("rowset_id", rowset_id)
4048
0
                        .tag("packed_file_path", packed_file_path)
4049
0
                        .tag("attempt", attempt);
4050
0
                return -1;
4051
0
            }
4052
0
            sleep_for_packed_file_retry();
4053
0
            continue;
4054
0
        }
4055
4056
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
4057
0
                .tag("instance_id", instance_id_)
4058
0
                .tag("tablet_id", tablet_id)
4059
0
                .tag("rowset_id", rowset_id)
4060
0
                .tag("packed_file_path", packed_file_path)
4061
0
                .tag("err", err);
4062
0
        return -1;
4063
0
    }
4064
4065
18.4E
    return -1;
4066
18.4E
}
4067
4068
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
4069
                                                const std::string& packed_key,
4070
7
                                                const cloud::PackedFileInfoPB& packed_info) {
4071
7
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
4072
0
        LOG_WARNING("packed file missing resource id when recycling")
4073
0
                .tag("instance_id", instance_id_)
4074
0
                .tag("packed_file_path", packed_file_path);
4075
0
        return -1;
4076
0
    }
4077
4078
7
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
4079
7
    if (!accessor) {
4080
0
        LOG_WARNING("no accessor available to delete packed file")
4081
0
                .tag("instance_id", instance_id_)
4082
0
                .tag("packed_file_path", packed_file_path)
4083
0
                .tag("resource_id", packed_info.resource_id());
4084
0
        return -1;
4085
0
    }
4086
4087
7
    int del_ret = accessor->delete_file(packed_file_path);
4088
7
    if (del_ret != 0 && del_ret != 1) {
4089
0
        LOG_WARNING("failed to delete packed file")
4090
0
                .tag("instance_id", instance_id_)
4091
0
                .tag("packed_file_path", packed_file_path)
4092
0
                .tag("resource_id", resource_id)
4093
0
                .tag("ret", del_ret);
4094
0
        return -1;
4095
0
    }
4096
7
    if (del_ret == 1) {
4097
0
        LOG_INFO("packed file already removed")
4098
0
                .tag("instance_id", instance_id_)
4099
0
                .tag("packed_file_path", packed_file_path)
4100
0
                .tag("resource_id", resource_id);
4101
7
    } else {
4102
7
        LOG_INFO("deleted packed file")
4103
7
                .tag("instance_id", instance_id_)
4104
7
                .tag("packed_file_path", packed_file_path)
4105
7
                .tag("resource_id", resource_id);
4106
7
    }
4107
4108
7
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
4109
7
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4110
7
        std::unique_ptr<Transaction> del_txn;
4111
7
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
4112
7
        if (err != TxnErrorCode::TXN_OK) {
4113
0
            LOG_WARNING("failed to create txn when removing packed file kv")
4114
0
                    .tag("instance_id", instance_id_)
4115
0
                    .tag("packed_file_path", packed_file_path)
4116
0
                    .tag("attempt", attempt)
4117
0
                    .tag("err", err);
4118
0
            return -1;
4119
0
        }
4120
4121
7
        std::string latest_val;
4122
7
        err = del_txn->get(packed_key, &latest_val);
4123
7
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4124
0
            return 0;
4125
0
        }
4126
7
        if (err != TxnErrorCode::TXN_OK) {
4127
0
            LOG_WARNING("failed to re-read packed file kv before removal")
4128
0
                    .tag("instance_id", instance_id_)
4129
0
                    .tag("packed_file_path", packed_file_path)
4130
0
                    .tag("attempt", attempt)
4131
0
                    .tag("err", err);
4132
0
            return -1;
4133
0
        }
4134
4135
7
        cloud::PackedFileInfoPB latest_info;
4136
7
        if (!latest_info.ParseFromString(latest_val)) {
4137
0
            LOG_WARNING("failed to parse packed file info before removal")
4138
0
                    .tag("instance_id", instance_id_)
4139
0
                    .tag("packed_file_path", packed_file_path)
4140
0
                    .tag("attempt", attempt);
4141
0
            return -1;
4142
0
        }
4143
4144
7
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
4145
7
              latest_info.ref_cnt() == 0)) {
4146
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
4147
0
                    .tag("instance_id", instance_id_)
4148
0
                    .tag("packed_file_path", packed_file_path)
4149
0
                    .tag("attempt", attempt);
4150
0
            return 0;
4151
0
        }
4152
4153
7
        del_txn->remove(packed_key);
4154
7
        err = del_txn->commit();
4155
7
        if (err == TxnErrorCode::TXN_OK) {
4156
7
            LOG_INFO("removed packed file metadata")
4157
7
                    .tag("instance_id", instance_id_)
4158
7
                    .tag("packed_file_path", packed_file_path);
4159
7
            return 0;
4160
7
        }
4161
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4162
0
            if (attempt >= max_retry_times) {
4163
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
4164
0
                        .tag("instance_id", instance_id_)
4165
0
                        .tag("packed_file_path", packed_file_path)
4166
0
                        .tag("attempt", attempt);
4167
0
                return -1;
4168
0
            }
4169
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
4170
0
                    .tag("instance_id", instance_id_)
4171
0
                    .tag("packed_file_path", packed_file_path)
4172
0
                    .tag("attempt", attempt);
4173
0
            sleep_for_packed_file_retry();
4174
0
            continue;
4175
0
        }
4176
0
        LOG_WARNING("failed to remove packed file kv")
4177
0
                .tag("instance_id", instance_id_)
4178
0
                .tag("packed_file_path", packed_file_path)
4179
0
                .tag("attempt", attempt)
4180
0
                .tag("err", err);
4181
0
        return -1;
4182
0
    }
4183
0
    return -1;
4184
7
}
4185
4186
int InstanceRecycler::delete_rowset_data(
4187
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
4188
57
        RecyclerMetricsContext& metrics_context) {
4189
57
    int ret = 0;
4190
    // resource_id -> file_paths
4191
57
    std::map<std::string, std::vector<std::string>> resource_file_paths;
4192
    // (resource_id, tablet_id, rowset_id)
4193
57
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
4194
57
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
4195
4196
56.2k
    for (const auto& [_, rs] : rowsets) {
4197
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
4198
        // due to aborted schema change.
4199
56.2k
        if (is_formal_rowset) {
4200
3.19k
            std::lock_guard lock(recycled_tablets_mtx_);
4201
3.19k
            if (recycled_tablets_.count(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
4202
                // Tablet has been recycled and this rowset has no packed slices, so file data
4203
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
4204
                // slice info must still run to decrement packed file ref counts.
4205
0
                continue;
4206
0
            }
4207
3.19k
        }
4208
4209
56.2k
        int64_t num_segments = rs.num_segments();
4210
        // Check num_segments before accessor lookup, because empty rowsets
4211
        // (e.g. base compaction output of empty rowsets) may have no resource_id
4212
        // set. Skipping them early avoids a spurious "no such resource id" error
4213
        // that marks the entire batch as failed and prevents txn_remove from
4214
        // cleaning up recycle KV keys.
4215
56.2k
        if (num_segments <= 0) {
4216
0
            metrics_context.total_recycled_num++;
4217
0
            metrics_context.total_recycled_data_size += rs.total_disk_size();
4218
0
            continue;
4219
0
        }
4220
4221
56.2k
        auto it = accessor_map_.find(rs.resource_id());
4222
        // possible if the accessor is not initilized correctly
4223
56.2k
        if (it == accessor_map_.end()) [[unlikely]] {
4224
2.00k
            LOG_WARNING("instance has no such resource id")
4225
2.00k
                    .tag("instance_id", instance_id_)
4226
2.00k
                    .tag("resource_id", rs.resource_id());
4227
2.00k
            ret = -1;
4228
2.00k
            continue;
4229
2.00k
        }
4230
4231
54.2k
        auto& file_paths = resource_file_paths[rs.resource_id()];
4232
54.2k
        const auto& rowset_id = rs.rowset_id_v2();
4233
54.2k
        int64_t tablet_id = rs.tablet_id();
4234
54.2k
        LOG_INFO("recycle rowset merge index size")
4235
54.2k
                .tag("instance_id", instance_id_)
4236
54.2k
                .tag("tablet_id", tablet_id)
4237
54.2k
                .tag("rowset_id", rowset_id)
4238
54.2k
                .tag("merge_index_size", rs.packed_slice_locations_size());
4239
54.2k
        if (decrement_packed_file_ref_counts(rs) != 0) {
4240
0
            ret = -1;
4241
0
            continue;
4242
0
        }
4243
4244
        // Process delete bitmap - check where it's stored.
4245
54.2k
        DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4246
54.2k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
4247
54.2k
                                                           &delete_bitmap_storage_type) != 0) {
4248
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
4249
0
                    .tag("instance_id", instance_id_)
4250
0
                    .tag("tablet_id", tablet_id)
4251
0
                    .tag("rowset_id", rowset_id);
4252
0
            ret = -1;
4253
0
            continue;
4254
0
        }
4255
54.2k
        if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
4256
51.5k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
4257
51.5k
        }
4258
4259
        // Process inverted indexes
4260
54.2k
        std::vector<std::pair<int64_t, std::string>> index_ids;
4261
        // default format as v1.
4262
54.2k
        InvertedIndexStorageFormatPB index_format = rs.has_inverted_index_storage_format()
4263
54.2k
                                                            ? rs.inverted_index_storage_format()
4264
54.2k
                                                            : InvertedIndexStorageFormatPB::V1;
4265
54.2k
        int inverted_index_get_ret = 0;
4266
54.2k
        if (rs.has_tablet_schema()) {
4267
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
4268
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
4269
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
4270
53.5k
                }
4271
53.5k
            }
4272
26.6k
            if (!rs.has_inverted_index_storage_format() &&
4273
26.6k
                rs.tablet_schema().has_inverted_index_storage_format()) {
4274
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
4275
26.5k
            }
4276
27.6k
        } else {
4277
27.6k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
4278
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
4279
0
                                "instance_id="
4280
0
                             << instance_id_ << " tablet_id=" << tablet_id
4281
0
                             << " rowset_id=" << rowset_id;
4282
0
                ret = -1;
4283
0
                continue;
4284
0
            }
4285
27.6k
            InvertedIndexInfo index_info;
4286
27.6k
            inverted_index_get_ret =
4287
27.6k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
4288
27.6k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
4289
27.6k
                                     &inverted_index_get_ret);
4290
27.6k
            if (inverted_index_get_ret == 0) {
4291
27.1k
                if (!rs.has_inverted_index_storage_format()) {
4292
27.1k
                    index_format = index_info.first;
4293
27.1k
                }
4294
27.1k
                index_ids = index_info.second;
4295
27.1k
            } else if (inverted_index_get_ret == 1) {
4296
                // 1. Schema kv not found means tablet has been recycled
4297
                // Maybe some tablet recycle failed by some bugs
4298
                // We need to delete again to double check
4299
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
4300
                // because we are uncertain about the inverted index information.
4301
                // If there are inverted indexes, some data might not be deleted,
4302
                // but this is acceptable as we have made our best effort to delete the data.
4303
507
                LOG_INFO(
4304
507
                        "delete rowset data schema kv not found, need to delete again to "
4305
507
                        "double "
4306
507
                        "check")
4307
507
                        .tag("instance_id", instance_id_)
4308
507
                        .tag("tablet_id", tablet_id)
4309
507
                        .tag("rowset", rs.ShortDebugString());
4310
                // Currently index_ids is guaranteed to be empty,
4311
                // but we clear it again here as a safeguard against future code changes
4312
                // that might cause index_ids to no longer be empty
4313
507
                index_format = InvertedIndexStorageFormatPB::V2;
4314
507
                index_ids.clear();
4315
18.4E
            } else {
4316
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
4317
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4318
18.4E
                ret = -1;
4319
18.4E
                continue;
4320
18.4E
            }
4321
27.6k
        }
4322
54.2k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
4323
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
4324
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
4325
10
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
4326
10
            continue;
4327
10
        }
4328
324k
        for (int64_t i = 0; i < num_segments; ++i) {
4329
270k
            add_file_to_delete_if_not_packed(rs, segment_path(tablet_id, rowset_id, i),
4330
270k
                                             &file_paths);
4331
270k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
4332
536k
                for (const auto& index_id : index_ids) {
4333
536k
                    add_file_to_delete_if_not_packed(
4334
536k
                            rs,
4335
536k
                            inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
4336
536k
                                                   index_id.second),
4337
536k
                            &file_paths);
4338
536k
                }
4339
267k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
4340
                // try to recycle inverted index v2 when get_ret == 1
4341
                // we treat schema not found as if it has a v2 format inverted index
4342
                // to reduce chance of data leakage
4343
2.50k
                if (inverted_index_get_ret == 1) {
4344
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
4345
2.50k
                            .tag("instance_id", instance_id_)
4346
2.50k
                            .tag("inverted index v2 path",
4347
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, i));
4348
2.50k
                }
4349
2.50k
                add_file_to_delete_if_not_packed(
4350
2.50k
                        rs, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
4351
2.50k
            }
4352
270k
        }
4353
54.2k
    }
4354
4355
57
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
4356
57
                                                 "delete_rowset_data",
4357
58
                                                 [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clERKi
Line
Count
Source
4357
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
4357
53
                                                 [](const int& ret) { return ret != 0; });
4358
57
    for (auto& [resource_id, file_paths] : resource_file_paths) {
4359
48
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4360
48
            DCHECK(accessor_map_.count(*rid))
4361
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4362
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4363
48
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4364
48
                                     &accessor_map_);
4365
48
            if (!accessor_map_.contains(*rid)) {
4366
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4367
0
                        .tag("resource_id", resource_id)
4368
0
                        .tag("instance_id", instance_id_);
4369
0
                return -1;
4370
0
            }
4371
48
            auto& accessor = accessor_map_[*rid];
4372
48
            int ret = accessor->delete_files(*paths);
4373
48
            if (!ret) {
4374
                // deduplication of different files with the same rowset id
4375
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4376
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4377
48
                std::set<std::string> deleted_rowset_id;
4378
4379
48
                std::for_each(paths->begin(), paths->end(),
4380
48
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4381
855k
                               this](const std::string& path) {
4382
855k
                                  std::vector<std::string> str;
4383
855k
                                  butil::SplitString(path, '/', &str);
4384
855k
                                  std::string rowset_id;
4385
855k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4386
853k
                                      rowset_id = str.back().substr(0, pos);
4387
853k
                                  } else {
4388
2.35k
                                      if (path.find("packed_file/") != std::string::npos) {
4389
0
                                          return; // packed files do not have rowset_id encoded
4390
0
                                      }
4391
2.35k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4392
2.35k
                                      return;
4393
2.35k
                                  }
4394
853k
                                  auto rs_meta = rowsets.find(rowset_id);
4395
853k
                                  if (rs_meta != rowsets.end() &&
4396
856k
                                      !deleted_rowset_id.contains(rowset_id)) {
4397
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
4398
54.1k
                                      metrics_context.total_recycled_data_size +=
4399
54.1k
                                              rs_meta->second.total_disk_size();
4400
54.1k
                                      segment_metrics_context_.total_recycled_num +=
4401
54.1k
                                              rs_meta->second.num_segments();
4402
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
4403
54.1k
                                              rs_meta->second.total_disk_size();
4404
54.1k
                                      metrics_context.total_recycled_num++;
4405
54.1k
                                  }
4406
853k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
4381
7
                               this](const std::string& path) {
4382
7
                                  std::vector<std::string> str;
4383
7
                                  butil::SplitString(path, '/', &str);
4384
7
                                  std::string rowset_id;
4385
7
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4386
7
                                      rowset_id = str.back().substr(0, pos);
4387
7
                                  } else {
4388
0
                                      if (path.find("packed_file/") != std::string::npos) {
4389
0
                                          return; // packed files do not have rowset_id encoded
4390
0
                                      }
4391
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4392
0
                                      return;
4393
0
                                  }
4394
7
                                  auto rs_meta = rowsets.find(rowset_id);
4395
7
                                  if (rs_meta != rowsets.end() &&
4396
7
                                      !deleted_rowset_id.contains(rowset_id)) {
4397
7
                                      deleted_rowset_id.emplace(rowset_id);
4398
7
                                      metrics_context.total_recycled_data_size +=
4399
7
                                              rs_meta->second.total_disk_size();
4400
7
                                      segment_metrics_context_.total_recycled_num +=
4401
7
                                              rs_meta->second.num_segments();
4402
7
                                      segment_metrics_context_.total_recycled_data_size +=
4403
7
                                              rs_meta->second.total_disk_size();
4404
7
                                      metrics_context.total_recycled_num++;
4405
7
                                  }
4406
7
                              });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
4381
855k
                               this](const std::string& path) {
4382
855k
                                  std::vector<std::string> str;
4383
855k
                                  butil::SplitString(path, '/', &str);
4384
855k
                                  std::string rowset_id;
4385
855k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4386
853k
                                      rowset_id = str.back().substr(0, pos);
4387
853k
                                  } else {
4388
2.35k
                                      if (path.find("packed_file/") != std::string::npos) {
4389
0
                                          return; // packed files do not have rowset_id encoded
4390
0
                                      }
4391
2.35k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4392
2.35k
                                      return;
4393
2.35k
                                  }
4394
853k
                                  auto rs_meta = rowsets.find(rowset_id);
4395
853k
                                  if (rs_meta != rowsets.end() &&
4396
856k
                                      !deleted_rowset_id.contains(rowset_id)) {
4397
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
4398
54.1k
                                      metrics_context.total_recycled_data_size +=
4399
54.1k
                                              rs_meta->second.total_disk_size();
4400
54.1k
                                      segment_metrics_context_.total_recycled_num +=
4401
54.1k
                                              rs_meta->second.num_segments();
4402
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
4403
54.1k
                                              rs_meta->second.total_disk_size();
4404
54.1k
                                      metrics_context.total_recycled_num++;
4405
54.1k
                                  }
4406
853k
                              });
4407
48
            }
4408
48
            return ret;
4409
48
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4359
5
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4360
5
            DCHECK(accessor_map_.count(*rid))
4361
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4362
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4363
5
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4364
5
                                     &accessor_map_);
4365
5
            if (!accessor_map_.contains(*rid)) {
4366
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4367
0
                        .tag("resource_id", resource_id)
4368
0
                        .tag("instance_id", instance_id_);
4369
0
                return -1;
4370
0
            }
4371
5
            auto& accessor = accessor_map_[*rid];
4372
5
            int ret = accessor->delete_files(*paths);
4373
5
            if (!ret) {
4374
                // deduplication of different files with the same rowset id
4375
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4376
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4377
5
                std::set<std::string> deleted_rowset_id;
4378
4379
5
                std::for_each(paths->begin(), paths->end(),
4380
5
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4381
5
                               this](const std::string& path) {
4382
5
                                  std::vector<std::string> str;
4383
5
                                  butil::SplitString(path, '/', &str);
4384
5
                                  std::string rowset_id;
4385
5
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4386
5
                                      rowset_id = str.back().substr(0, pos);
4387
5
                                  } else {
4388
5
                                      if (path.find("packed_file/") != std::string::npos) {
4389
5
                                          return; // packed files do not have rowset_id encoded
4390
5
                                      }
4391
5
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4392
5
                                      return;
4393
5
                                  }
4394
5
                                  auto rs_meta = rowsets.find(rowset_id);
4395
5
                                  if (rs_meta != rowsets.end() &&
4396
5
                                      !deleted_rowset_id.contains(rowset_id)) {
4397
5
                                      deleted_rowset_id.emplace(rowset_id);
4398
5
                                      metrics_context.total_recycled_data_size +=
4399
5
                                              rs_meta->second.total_disk_size();
4400
5
                                      segment_metrics_context_.total_recycled_num +=
4401
5
                                              rs_meta->second.num_segments();
4402
5
                                      segment_metrics_context_.total_recycled_data_size +=
4403
5
                                              rs_meta->second.total_disk_size();
4404
5
                                      metrics_context.total_recycled_num++;
4405
5
                                  }
4406
5
                              });
4407
5
            }
4408
5
            return ret;
4409
5
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4359
43
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4360
43
            DCHECK(accessor_map_.count(*rid))
4361
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4362
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4363
43
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4364
43
                                     &accessor_map_);
4365
43
            if (!accessor_map_.contains(*rid)) {
4366
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4367
0
                        .tag("resource_id", resource_id)
4368
0
                        .tag("instance_id", instance_id_);
4369
0
                return -1;
4370
0
            }
4371
43
            auto& accessor = accessor_map_[*rid];
4372
43
            int ret = accessor->delete_files(*paths);
4373
43
            if (!ret) {
4374
                // deduplication of different files with the same rowset id
4375
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4376
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4377
43
                std::set<std::string> deleted_rowset_id;
4378
4379
43
                std::for_each(paths->begin(), paths->end(),
4380
43
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4381
43
                               this](const std::string& path) {
4382
43
                                  std::vector<std::string> str;
4383
43
                                  butil::SplitString(path, '/', &str);
4384
43
                                  std::string rowset_id;
4385
43
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4386
43
                                      rowset_id = str.back().substr(0, pos);
4387
43
                                  } else {
4388
43
                                      if (path.find("packed_file/") != std::string::npos) {
4389
43
                                          return; // packed files do not have rowset_id encoded
4390
43
                                      }
4391
43
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4392
43
                                      return;
4393
43
                                  }
4394
43
                                  auto rs_meta = rowsets.find(rowset_id);
4395
43
                                  if (rs_meta != rowsets.end() &&
4396
43
                                      !deleted_rowset_id.contains(rowset_id)) {
4397
43
                                      deleted_rowset_id.emplace(rowset_id);
4398
43
                                      metrics_context.total_recycled_data_size +=
4399
43
                                              rs_meta->second.total_disk_size();
4400
43
                                      segment_metrics_context_.total_recycled_num +=
4401
43
                                              rs_meta->second.num_segments();
4402
43
                                      segment_metrics_context_.total_recycled_data_size +=
4403
43
                                              rs_meta->second.total_disk_size();
4404
43
                                      metrics_context.total_recycled_num++;
4405
43
                                  }
4406
43
                              });
4407
43
            }
4408
43
            return ret;
4409
43
        });
4410
48
    }
4411
57
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
4412
10
        LOG_INFO(
4413
10
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
4414
10
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
4415
10
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
4416
10
        concurrent_delete_executor.add([&]() -> int {
4417
10
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4418
10
            if (!ret) {
4419
10
                auto rs = rowsets.at(rowset_id);
4420
10
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4421
10
                metrics_context.total_recycled_num++;
4422
10
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4423
10
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4424
10
            }
4425
10
            return ret;
4426
10
        });
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
4416
10
        concurrent_delete_executor.add([&]() -> int {
4417
10
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4418
10
            if (!ret) {
4419
10
                auto rs = rowsets.at(rowset_id);
4420
10
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4421
10
                metrics_context.total_recycled_num++;
4422
10
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4423
10
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4424
10
            }
4425
10
            return ret;
4426
10
        });
4427
10
    }
4428
4429
57
    bool finished = true;
4430
57
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4431
58
    for (int r : rets) {
4432
58
        if (r != 0) {
4433
0
            ret = -1;
4434
0
            break;
4435
0
        }
4436
58
    }
4437
57
    ret = finished ? ret : -1;
4438
57
    return ret;
4439
57
}
4440
4441
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
4442
3.31k
                                         const std::string& rowset_id) {
4443
3.31k
    auto it = accessor_map_.find(resource_id);
4444
3.31k
    if (it == accessor_map_.end()) {
4445
400
        LOG_WARNING("instance has no such resource id")
4446
400
                .tag("instance_id", instance_id_)
4447
400
                .tag("resource_id", resource_id)
4448
400
                .tag("tablet_id", tablet_id)
4449
400
                .tag("rowset_id", rowset_id);
4450
400
        return -1;
4451
400
    }
4452
2.91k
    auto& accessor = it->second;
4453
2.91k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
4454
3.31k
}
4455
4456
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
4457
4
    if (key.empty()) {
4458
0
        return false;
4459
0
    }
4460
4
    std::string_view key_view = key;
4461
4
    key_view.remove_prefix(1); // remove keyspace prefix
4462
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
4463
4
    if (decode_key(&key_view, &decoded) != 0) {
4464
0
        return false;
4465
0
    }
4466
4
    if (decoded.size() < 4) {
4467
0
        return false;
4468
0
    }
4469
4
    try {
4470
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
4471
4
    } catch (const std::bad_variant_access&) {
4472
0
        return false;
4473
0
    }
4474
4
    return true;
4475
4
}
4476
4477
14
int InstanceRecycler::recycle_packed_files() {
4478
14
    const std::string task_name = "recycle_packed_files";
4479
14
    auto start_tp = steady_clock::now();
4480
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
4481
14
    int ret = 0;
4482
14
    PackedFileRecycleStats stats;
4483
4484
14
    register_recycle_task(task_name, start_time);
4485
14
    DORIS_CLOUD_DEFER {
4486
14
        unregister_recycle_task(task_name);
4487
14
        int64_t cost =
4488
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4489
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4490
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4491
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4492
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4493
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4494
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4495
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4496
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4497
14
                                                             stats.bytes_object_deleted);
4498
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4499
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4500
14
                .tag("instance_id", instance_id_)
4501
14
                .tag("num_scanned", stats.num_scanned)
4502
14
                .tag("num_corrected", stats.num_corrected)
4503
14
                .tag("num_deleted", stats.num_deleted)
4504
14
                .tag("num_failed", stats.num_failed)
4505
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4506
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4507
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4508
14
                .tag("bytes_deleted", stats.bytes_deleted)
4509
14
                .tag("ret", ret);
4510
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
4485
14
    DORIS_CLOUD_DEFER {
4486
14
        unregister_recycle_task(task_name);
4487
14
        int64_t cost =
4488
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4489
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4490
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4491
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4492
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4493
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4494
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4495
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4496
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4497
14
                                                             stats.bytes_object_deleted);
4498
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4499
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4500
14
                .tag("instance_id", instance_id_)
4501
14
                .tag("num_scanned", stats.num_scanned)
4502
14
                .tag("num_corrected", stats.num_corrected)
4503
14
                .tag("num_deleted", stats.num_deleted)
4504
14
                .tag("num_failed", stats.num_failed)
4505
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4506
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4507
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4508
14
                .tag("bytes_deleted", stats.bytes_deleted)
4509
14
                .tag("ret", ret);
4510
14
    };
4511
4512
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4513
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4514
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4515
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
4512
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4513
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4514
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4515
4
    };
4516
4517
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
4518
4519
14
    std::string begin = packed_file_key({instance_id_, ""});
4520
14
    std::string end = packed_file_key({instance_id_, "\xff"});
4521
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
4522
0
        ret = -1;
4523
0
    }
4524
4525
14
    return ret;
4526
14
}
4527
4528
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
4529
                                                  RecyclerMetricsContext& metrics_context,
4530
0
                                                  int64_t partition_id, bool is_empty_tablet) {
4531
0
    std::string tablet_key_begin, tablet_key_end;
4532
4533
0
    if (partition_id > 0) {
4534
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
4535
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
4536
0
    } else {
4537
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
4538
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
4539
0
    }
4540
    // for calculate the total num or bytes of recyled objects
4541
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
4542
0
                                                          std::string_view v) -> int {
4543
0
        doris::TabletMetaCloudPB tablet_meta_pb;
4544
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
4545
0
            return 0;
4546
0
        }
4547
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
4548
4549
0
        if (config::enable_recycler_check_lazy_txn_finished &&
4550
0
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
4551
0
            return 0;
4552
0
        }
4553
4554
0
        if (!is_empty_tablet) {
4555
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
4556
0
                return 0;
4557
0
            }
4558
0
            tablet_metrics_context_.total_need_recycle_num++;
4559
0
        }
4560
0
        return 0;
4561
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_
4562
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
4563
0
    metrics_context.report(true);
4564
0
    tablet_metrics_context_.report(true);
4565
0
    segment_metrics_context_.report(true);
4566
0
    return ret;
4567
0
}
4568
4569
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
4570
0
                                                 RecyclerMetricsContext& metrics_context) {
4571
0
    int ret = 0;
4572
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
4573
0
    std::unique_ptr<Transaction> txn;
4574
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4575
0
        LOG_WARNING("failed to recycle tablet ")
4576
0
                .tag("tablet id", tablet_id)
4577
0
                .tag("instance_id", instance_id_)
4578
0
                .tag("reason", "failed to create txn");
4579
0
        ret = -1;
4580
0
    }
4581
0
    GetRowsetResponse resp;
4582
0
    std::string msg;
4583
0
    MetaServiceCode code = MetaServiceCode::OK;
4584
    // get rowsets in tablet
4585
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4586
0
                        tablet_id, code, msg, &resp);
4587
0
    if (code != MetaServiceCode::OK) {
4588
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4589
0
                .tag("tablet id", tablet_id)
4590
0
                .tag("msg", msg)
4591
0
                .tag("code", code)
4592
0
                .tag("instance id", instance_id_);
4593
0
        ret = -1;
4594
0
    }
4595
0
    for (const auto& rs_meta : resp.rowset_meta()) {
4596
        /*
4597
        * For compatibility, we skip the loop for [0-1] here.
4598
        * The purpose of this loop is to delete object files,
4599
        * and since [0-1] only has meta and doesn't have object files,
4600
        * skipping it doesn't affect system correctness.
4601
        *
4602
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
4603
        * would return error -1 directly, causing the recycle operation to fail.
4604
        *
4605
        * [0-1] doesn't have resource id is a bug.
4606
        * In the future, we will fix this problem, after that,
4607
        * we can remove this if statement.
4608
        *
4609
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
4610
        */
4611
4612
0
        if (rs_meta.end_version() == 1) {
4613
            // Assert that [0-1] has no resource_id to make sure
4614
            // this if statement will not be forgetted to remove
4615
            // when the resource id bug is fixed
4616
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4617
0
            continue;
4618
0
        }
4619
0
        if (!rs_meta.has_resource_id()) {
4620
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4621
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4622
0
                    .tag("instance_id", instance_id_)
4623
0
                    .tag("tablet_id", tablet_id);
4624
0
            continue;
4625
0
        }
4626
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4627
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4628
        // possible if the accessor is not initilized correctly
4629
0
        if (it == accessor_map_.end()) [[unlikely]] {
4630
0
            LOG_WARNING(
4631
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4632
0
                    "recycle process")
4633
0
                    .tag("tablet id", tablet_id)
4634
0
                    .tag("instance_id", instance_id_)
4635
0
                    .tag("resource_id", rs_meta.resource_id())
4636
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4637
0
            continue;
4638
0
        }
4639
4640
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
4641
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4642
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4643
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
4644
0
    }
4645
0
    return ret;
4646
0
}
4647
4648
4.26k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
4649
4.26k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
4650
4.26k
            .tag("instance_id", instance_id_)
4651
4.26k
            .tag("tablet_id", tablet_id);
4652
4653
4.26k
    if (should_recycle_versioned_keys()) {
4654
14
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
4655
14
        if (ret != 0) {
4656
0
            return ret;
4657
0
        }
4658
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
4659
        // during the recycle_versioned_tablet process.
4660
        //
4661
        // .. And remove restore job rowsets of this tablet too
4662
14
    }
4663
4664
4.26k
    int ret = 0;
4665
4.26k
    auto start_time = steady_clock::now();
4666
4667
4.26k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4668
4669
    // collect resource ids
4670
260
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4671
260
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4672
260
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4673
260
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4674
260
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
4675
260
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
4676
4677
260
    std::set<std::string> resource_ids;
4678
260
    int64_t recycle_rowsets_number = 0;
4679
260
    int64_t recycle_segments_number = 0;
4680
260
    int64_t recycle_rowsets_data_size = 0;
4681
260
    int64_t recycle_rowsets_index_size = 0;
4682
260
    int64_t recycle_restore_job_rowsets_number = 0;
4683
260
    int64_t recycle_restore_job_segments_number = 0;
4684
260
    int64_t recycle_restore_job_rowsets_data_size = 0;
4685
260
    int64_t recycle_restore_job_rowsets_index_size = 0;
4686
260
    int64_t max_rowset_version = 0;
4687
260
    int64_t min_rowset_creation_time = INT64_MAX;
4688
260
    int64_t max_rowset_creation_time = 0;
4689
260
    int64_t min_rowset_expiration_time = INT64_MAX;
4690
260
    int64_t max_rowset_expiration_time = 0;
4691
4692
260
    DORIS_CLOUD_DEFER {
4693
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4694
260
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4695
260
                .tag("instance_id", instance_id_)
4696
260
                .tag("tablet_id", tablet_id)
4697
260
                .tag("recycle rowsets number", recycle_rowsets_number)
4698
260
                .tag("recycle segments number", recycle_segments_number)
4699
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4700
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4701
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4702
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4703
260
                .tag("all restore job rowsets recycle data size",
4704
260
                     recycle_restore_job_rowsets_data_size)
4705
260
                .tag("all restore job rowsets recycle index size",
4706
260
                     recycle_restore_job_rowsets_index_size)
4707
260
                .tag("max rowset version", max_rowset_version)
4708
260
                .tag("min rowset creation time", min_rowset_creation_time)
4709
260
                .tag("max rowset creation time", max_rowset_creation_time)
4710
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
4711
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
4712
260
                .tag("task type", metrics_context.operation_type)
4713
260
                .tag("ret", ret);
4714
260
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4692
260
    DORIS_CLOUD_DEFER {
4693
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4694
260
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4695
260
                .tag("instance_id", instance_id_)
4696
260
                .tag("tablet_id", tablet_id)
4697
260
                .tag("recycle rowsets number", recycle_rowsets_number)
4698
260
                .tag("recycle segments number", recycle_segments_number)
4699
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4700
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4701
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4702
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4703
260
                .tag("all restore job rowsets recycle data size",
4704
260
                     recycle_restore_job_rowsets_data_size)
4705
260
                .tag("all restore job rowsets recycle index size",
4706
260
                     recycle_restore_job_rowsets_index_size)
4707
260
                .tag("max rowset version", max_rowset_version)
4708
260
                .tag("min rowset creation time", min_rowset_creation_time)
4709
260
                .tag("max rowset creation time", max_rowset_creation_time)
4710
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
4711
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
4712
260
                .tag("task type", metrics_context.operation_type)
4713
260
                .tag("ret", ret);
4714
260
    };
4715
4716
260
    std::unique_ptr<Transaction> txn;
4717
260
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4718
0
        LOG_WARNING("failed to recycle tablet ")
4719
0
                .tag("tablet id", tablet_id)
4720
0
                .tag("instance_id", instance_id_)
4721
0
                .tag("reason", "failed to create txn");
4722
0
        ret = -1;
4723
0
    }
4724
260
    GetRowsetResponse resp;
4725
260
    std::string msg;
4726
260
    MetaServiceCode code = MetaServiceCode::OK;
4727
    // get rowsets in tablet
4728
260
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4729
260
                        tablet_id, code, msg, &resp);
4730
260
    if (code != MetaServiceCode::OK) {
4731
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4732
0
                .tag("tablet id", tablet_id)
4733
0
                .tag("msg", msg)
4734
0
                .tag("code", code)
4735
0
                .tag("instance id", instance_id_);
4736
0
        ret = -1;
4737
0
    }
4738
260
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
4739
4740
2.54k
    for (const auto& rs_meta : resp.rowset_meta()) {
4741
2.54k
        if (!rs_meta.has_resource_id() || rs_meta.resource_id().empty()) {
4742
3
            if (rs_meta.num_segments() <= 0) {
4743
2
                LOG_INFO("rowset meta has no segments and no resource id, skip this rowset")
4744
2
                        .tag("rs_meta", rs_meta.ShortDebugString())
4745
2
                        .tag("instance_id", instance_id_)
4746
2
                        .tag("tablet_id", tablet_id);
4747
2
                recycle_rowsets_number += 1;
4748
2
                continue;
4749
2
            }
4750
1
            LOG_WARNING("rowset meta has a missing or empty resource id, impossible!")
4751
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
4752
1
                    .tag("instance_id", instance_id_)
4753
1
                    .tag("tablet_id", tablet_id);
4754
1
            return -1;
4755
3
        }
4756
2.54k
        DCHECK(rs_meta.has_resource_id() && !rs_meta.resource_id().empty())
4757
1
                << "rs_meta" << rs_meta.ShortDebugString();
4758
2.54k
        auto it = accessor_map_.find(rs_meta.resource_id());
4759
        // possible if the accessor is not initilized correctly
4760
2.54k
        if (it == accessor_map_.end()) [[unlikely]] {
4761
1
            LOG_WARNING(
4762
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4763
1
                    "recycle process")
4764
1
                    .tag("tablet id", tablet_id)
4765
1
                    .tag("instance_id", instance_id_)
4766
1
                    .tag("resource_id", rs_meta.resource_id())
4767
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4768
1
            return -1;
4769
1
        }
4770
2.54k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4771
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
4772
0
                    .tag("instance_id", instance_id_)
4773
0
                    .tag("tablet_id", tablet_id)
4774
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4775
0
            return -1;
4776
0
        }
4777
2.54k
        recycle_rowsets_number += 1;
4778
2.54k
        recycle_segments_number += rs_meta.num_segments();
4779
2.54k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4780
2.54k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4781
2.54k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4782
2.54k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4783
2.54k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4784
2.54k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4785
2.54k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4786
2.54k
        resource_ids.emplace(rs_meta.resource_id());
4787
2.54k
    }
4788
4789
    // get restore job rowset in tablet
4790
258
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
4791
258
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
4792
258
    if (code != MetaServiceCode::OK) {
4793
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
4794
0
                .tag("tablet id", tablet_id)
4795
0
                .tag("msg", msg)
4796
0
                .tag("code", code)
4797
0
                .tag("instance id", instance_id_);
4798
0
        return -1;
4799
0
    }
4800
4801
258
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
4802
0
        if (!rs_meta.has_resource_id()) {
4803
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4804
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4805
0
                    .tag("instance_id", instance_id_)
4806
0
                    .tag("tablet_id", tablet_id);
4807
0
            return -1;
4808
0
        }
4809
4810
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4811
        // possible if the accessor is not initilized correctly
4812
0
        if (it == accessor_map_.end()) [[unlikely]] {
4813
0
            LOG_WARNING(
4814
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4815
0
                    "recycle process")
4816
0
                    .tag("tablet id", tablet_id)
4817
0
                    .tag("instance_id", instance_id_)
4818
0
                    .tag("resource_id", rs_meta.resource_id())
4819
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4820
0
            return -1;
4821
0
        }
4822
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4823
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
4824
0
                    .tag("instance_id", instance_id_)
4825
0
                    .tag("tablet_id", tablet_id)
4826
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4827
0
            return -1;
4828
0
        }
4829
0
        recycle_restore_job_rowsets_number += 1;
4830
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
4831
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
4832
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
4833
0
        resource_ids.emplace(rs_meta.resource_id());
4834
0
    }
4835
4836
258
    LOG_INFO("recycle tablet start to delete object")
4837
258
            .tag("instance id", instance_id_)
4838
258
            .tag("tablet id", tablet_id)
4839
258
            .tag("recycle tablet resource ids are",
4840
258
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
4841
258
                                 [](std::string rs_id, const auto& it) {
4842
214
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4843
214
                                 }));
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
4841
214
                                 [](std::string rs_id, const auto& it) {
4842
214
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4843
214
                                 }));
4844
4845
258
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
4846
258
            _thread_pool_group.s3_producer_pool,
4847
258
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4848
258
            [](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
4848
208
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
4849
4850
    // delete all rowset data in this tablet
4851
    // ATTN: there may be data leak if not all accessor initilized successfully
4852
    //       partial data deleted if the tablet is stored cross-storage vault
4853
    //       vault id is not attached to TabletMeta...
4854
258
    for (const auto& resource_id : resource_ids) {
4855
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
4856
217
        concurrent_delete_executor.add(
4857
217
                [&, rs_id = resource_id,
4858
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4859
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4860
217
                    if (res != 0) {
4861
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4862
3
                                     << " path=" << accessor_ptr->uri()
4863
3
                                     << " task type=" << metrics_context.operation_type;
4864
3
                        return std::make_pair(-1, rs_id);
4865
3
                    }
4866
214
                    return std::make_pair(0, rs_id);
4867
217
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
4858
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4859
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4860
217
                    if (res != 0) {
4861
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4862
3
                                     << " path=" << accessor_ptr->uri()
4863
3
                                     << " task type=" << metrics_context.operation_type;
4864
3
                        return std::make_pair(-1, rs_id);
4865
3
                    }
4866
214
                    return std::make_pair(0, rs_id);
4867
217
                });
4868
217
    }
4869
4870
258
    bool finished = true;
4871
258
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
4872
258
    for (auto& r : rets) {
4873
217
        if (r.first != 0) {
4874
3
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
4875
3
            ret = -1;
4876
3
        }
4877
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
4878
217
    }
4879
258
    ret = finished ? ret : -1;
4880
4881
258
    if (ret != 0) { // failed recycle tablet data
4882
3
        LOG_WARNING("ret!=0")
4883
3
                .tag("finished", finished)
4884
3
                .tag("ret", ret)
4885
3
                .tag("instance_id", instance_id_)
4886
3
                .tag("tablet_id", tablet_id);
4887
3
        return ret;
4888
3
    }
4889
4890
255
    tablet_metrics_context_.total_recycled_data_size +=
4891
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4892
255
    tablet_metrics_context_.total_recycled_num += 1;
4893
255
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
4894
255
    segment_metrics_context_.total_recycled_data_size +=
4895
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4896
255
    metrics_context.total_recycled_data_size +=
4897
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4898
255
    tablet_metrics_context_.report();
4899
255
    segment_metrics_context_.report();
4900
255
    metrics_context.report();
4901
4902
255
    txn.reset();
4903
255
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4904
0
        LOG_WARNING("failed to recycle tablet ")
4905
0
                .tag("tablet id", tablet_id)
4906
0
                .tag("instance_id", instance_id_)
4907
0
                .tag("reason", "failed to create txn");
4908
0
        ret = -1;
4909
0
    }
4910
    // delete all rowset kv in this tablet
4911
255
    txn->remove(rs_key0, rs_key1);
4912
255
    txn->remove(recyc_rs_key0, recyc_rs_key1);
4913
255
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
4914
4915
    // remove delete bitmap for MoW table
4916
255
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
4917
255
    txn->remove(pending_key);
4918
255
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
4919
255
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
4920
255
    txn->remove(delete_bitmap_start, delete_bitmap_end);
4921
4922
255
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
4923
255
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
4924
255
    txn->remove(dbm_start_key, dbm_end_key);
4925
255
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
4926
255
              << " end=" << hex(dbm_end_key);
4927
4928
255
    TxnErrorCode err = txn->commit();
4929
255
    if (err != TxnErrorCode::TXN_OK) {
4930
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
4931
0
        ret = -1;
4932
0
    }
4933
4934
255
    if (ret == 0) {
4935
        // All object files under tablet have been deleted
4936
255
        std::lock_guard lock(recycled_tablets_mtx_);
4937
255
        recycled_tablets_.insert(tablet_id);
4938
255
    }
4939
4940
255
    return ret;
4941
258
}
4942
4943
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
4944
14
                                               RecyclerMetricsContext& metrics_context) {
4945
14
    int ret = 0;
4946
14
    auto start_time = steady_clock::now();
4947
4948
14
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4949
4950
    // collect resource ids
4951
11
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4952
11
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4953
11
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4954
11
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4955
4956
11
    int64_t recycle_rowsets_number = 0;
4957
11
    int64_t recycle_segments_number = 0;
4958
11
    int64_t recycle_rowsets_data_size = 0;
4959
11
    int64_t recycle_rowsets_index_size = 0;
4960
11
    int64_t max_rowset_version = 0;
4961
11
    int64_t min_rowset_creation_time = INT64_MAX;
4962
11
    int64_t max_rowset_creation_time = 0;
4963
11
    int64_t min_rowset_expiration_time = INT64_MAX;
4964
11
    int64_t max_rowset_expiration_time = 0;
4965
4966
11
    DORIS_CLOUD_DEFER {
4967
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4968
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4969
11
                .tag("instance_id", instance_id_)
4970
11
                .tag("tablet_id", tablet_id)
4971
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4972
11
                .tag("recycle segments number", recycle_segments_number)
4973
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4974
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4975
11
                .tag("max rowset version", max_rowset_version)
4976
11
                .tag("min rowset creation time", min_rowset_creation_time)
4977
11
                .tag("max rowset creation time", max_rowset_creation_time)
4978
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4979
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4980
11
                .tag("ret", ret);
4981
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4966
11
    DORIS_CLOUD_DEFER {
4967
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4968
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4969
11
                .tag("instance_id", instance_id_)
4970
11
                .tag("tablet_id", tablet_id)
4971
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4972
11
                .tag("recycle segments number", recycle_segments_number)
4973
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4974
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4975
11
                .tag("max rowset version", max_rowset_version)
4976
11
                .tag("min rowset creation time", min_rowset_creation_time)
4977
11
                .tag("max rowset creation time", max_rowset_creation_time)
4978
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4979
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4980
11
                .tag("ret", ret);
4981
11
    };
4982
4983
11
    std::unique_ptr<Transaction> txn;
4984
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4985
0
        LOG_WARNING("failed to recycle tablet ")
4986
0
                .tag("tablet id", tablet_id)
4987
0
                .tag("instance_id", instance_id_)
4988
0
                .tag("reason", "failed to create txn");
4989
0
        ret = -1;
4990
0
    }
4991
4992
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
4993
    // by the related operation logs.
4994
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
4995
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
4996
11
    MetaReader meta_reader(instance_id_);
4997
11
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
4998
11
    if (err == TxnErrorCode::TXN_OK) {
4999
11
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
5000
11
    }
5001
11
    if (err != TxnErrorCode::TXN_OK) {
5002
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5003
0
                .tag("tablet id", tablet_id)
5004
0
                .tag("err", err)
5005
0
                .tag("instance id", instance_id_);
5006
0
        ret = -1;
5007
0
    }
5008
5009
11
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
5010
11
             load_rowset_metas.size(), compact_rowset_metas.size())
5011
11
            .tag("instance_id", instance_id_)
5012
11
            .tag("tablet_id", tablet_id);
5013
5014
11
    SyncExecutor<int> concurrent_delete_executor(
5015
11
            _thread_pool_group.s3_producer_pool,
5016
11
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5017
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
5018
5019
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5020
60
        recycle_rowsets_number += 1;
5021
60
        recycle_segments_number += rs_meta.num_segments();
5022
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5023
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5024
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5025
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5026
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5027
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5028
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5029
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
5019
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5020
60
        recycle_rowsets_number += 1;
5021
60
        recycle_segments_number += rs_meta.num_segments();
5022
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5023
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5024
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5025
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5026
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5027
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5028
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5029
60
    };
5030
5031
11
    std::vector<RowsetDeleteTask> all_tasks;
5032
60
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
5033
60
        update_rowset_stats(rs_meta);
5034
        // Version 0-1 rowset has no resource_id and no actual data files,
5035
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5036
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5037
60
        RowsetDeleteTask task;
5038
60
        task.rowset_meta = rs_meta;
5039
60
        task.versioned_rowset_key =
5040
60
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
5041
60
        task.non_versioned_rowset_key =
5042
60
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5043
60
        task.versionstamp = versionstamp;
5044
60
        all_tasks.push_back(std::move(task));
5045
60
    }
5046
5047
11
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
5048
0
        update_rowset_stats(rs_meta);
5049
        // Version 0-1 rowset has no resource_id and no actual data files,
5050
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5051
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5052
0
        RowsetDeleteTask task;
5053
0
        task.rowset_meta = rs_meta;
5054
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
5055
0
                {instance_id_, tablet_id, rs_meta.end_version()});
5056
0
        task.non_versioned_rowset_key =
5057
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5058
0
        task.versionstamp = versionstamp;
5059
0
        all_tasks.push_back(std::move(task));
5060
0
    }
5061
5062
11
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
5063
0
        RecycleRowsetPB recycle_rowset;
5064
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
5065
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5066
0
            return -1;
5067
0
        }
5068
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
5069
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
5070
                // in old version, keep this key-value pair and it needs to be checked manually
5071
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5072
0
                return -1;
5073
0
            }
5074
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
5075
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5076
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5077
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
5078
0
                return -1;
5079
0
            }
5080
            // decode rowset_id
5081
0
            auto k1 = k;
5082
0
            k1.remove_prefix(1);
5083
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5084
0
            decode_key(&k1, &out);
5085
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5086
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5087
0
            LOG_INFO("delete old-version rowset data")
5088
0
                    .tag("instance_id", instance_id_)
5089
0
                    .tag("tablet_id", tablet_id)
5090
0
                    .tag("rowset_id", rowset_id);
5091
5092
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
5093
            // so we must use prefix deletion directly instead of batch delete.
5094
0
            concurrent_delete_executor.add(
5095
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
5096
                        // delete by prefix, the recycle rowset key will be deleted by range later.
5097
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
5098
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
5099
0
        } else {
5100
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
5101
            // Version 0-1 rowset has no resource_id and no actual data files,
5102
            // but still needs ref_count key cleanup, so we add it to all_tasks.
5103
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
5104
0
            RowsetDeleteTask task;
5105
0
            task.rowset_meta = rowset_meta;
5106
0
            task.recycle_rowset_key = k;
5107
0
            all_tasks.push_back(std::move(task));
5108
0
        }
5109
0
        return 0;
5110
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_
5111
5112
11
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
5113
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
5114
0
                .tag("tablet id", tablet_id)
5115
0
                .tag("instance_id", instance_id_)
5116
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
5117
0
        ret = -1;
5118
0
    }
5119
5120
    // Phase 1: Classify tasks by ref_count
5121
11
    std::vector<RowsetDeleteTask> batch_delete_tasks;
5122
60
    for (auto& task : all_tasks) {
5123
60
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
5124
60
        if (classify_ret < 0) {
5125
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
5126
0
                    .tag("instance_id", instance_id_)
5127
0
                    .tag("tablet_id", tablet_id)
5128
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5129
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
5130
0
                return recycle_rowset_meta_and_data(t);
5131
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_4clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_4clEv
5132
0
        }
5133
60
    }
5134
5135
11
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
5136
5137
11
    LOG_INFO("batch delete plan created")
5138
11
            .tag("instance_id", instance_id_)
5139
11
            .tag("tablet_id", tablet_id)
5140
11
            .tag("plan_count", batch_delete_tasks.size());
5141
5142
    // Phase 2: Execute batch delete using existing delete_rowset_data
5143
11
    if (!batch_delete_tasks.empty()) {
5144
10
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
5145
49
        for (const auto& task : batch_delete_tasks) {
5146
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
5147
49
            if (task.rowset_meta.resource_id().empty()) {
5148
10
                LOG_INFO("skip rowset with empty resource_id in batch delete")
5149
10
                        .tag("instance_id", instance_id_)
5150
10
                        .tag("tablet_id", tablet_id)
5151
10
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5152
10
                continue;
5153
10
            }
5154
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
5155
39
        }
5156
5157
        // Only call delete_rowset_data if there are rowsets with actual data to delete
5158
10
        bool delete_success = true;
5159
10
        if (!rowsets_to_delete.empty()) {
5160
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
5161
9
                                                         "batch_delete_versioned_tablet");
5162
9
            int delete_ret = delete_rowset_data(
5163
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
5164
9
            if (delete_ret != 0) {
5165
0
                LOG_WARNING("batch delete execution failed")
5166
0
                        .tag("instance_id", instance_id_)
5167
0
                        .tag("tablet_id", tablet_id);
5168
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
5169
0
                ret = -1;
5170
0
                delete_success = false;
5171
0
            }
5172
9
        }
5173
5174
        // Phase 3: Only cleanup metadata if data deletion succeeded.
5175
        // If deletion failed, keep recycle_rowset_key so next round will retry.
5176
10
        if (delete_success) {
5177
10
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
5178
10
            if (cleanup_ret != 0) {
5179
0
                LOG_WARNING("batch delete cleanup failed")
5180
0
                        .tag("instance_id", instance_id_)
5181
0
                        .tag("tablet_id", tablet_id);
5182
0
                ret = -1;
5183
0
            }
5184
10
        }
5185
10
    }
5186
5187
    // Always wait for fallback tasks to complete before returning
5188
11
    bool finished = true;
5189
11
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
5190
11
    for (int r : rets) {
5191
0
        if (r != 0) {
5192
0
            ret = -1;
5193
0
        }
5194
0
    }
5195
5196
11
    ret = finished ? ret : -1;
5197
5198
11
    if (ret != 0) { // failed recycle tablet data
5199
0
        LOG_WARNING("recycle versioned tablet failed")
5200
0
                .tag("finished", finished)
5201
0
                .tag("ret", ret)
5202
0
                .tag("instance_id", instance_id_)
5203
0
                .tag("tablet_id", tablet_id);
5204
0
        return ret;
5205
0
    }
5206
5207
11
    tablet_metrics_context_.total_recycled_data_size +=
5208
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5209
11
    tablet_metrics_context_.total_recycled_num += 1;
5210
11
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5211
11
    segment_metrics_context_.total_recycled_data_size +=
5212
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5213
11
    metrics_context.total_recycled_data_size +=
5214
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5215
11
    tablet_metrics_context_.report();
5216
11
    segment_metrics_context_.report();
5217
11
    metrics_context.report();
5218
5219
11
    txn.reset();
5220
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5221
0
        LOG_WARNING("failed to recycle tablet ")
5222
0
                .tag("tablet id", tablet_id)
5223
0
                .tag("instance_id", instance_id_)
5224
0
                .tag("reason", "failed to create txn");
5225
0
        ret = -1;
5226
0
    }
5227
    // delete all rowset kv in this tablet
5228
11
    txn->remove(rs_key0, rs_key1);
5229
11
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5230
5231
    // remove delete bitmap for MoW table
5232
11
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5233
11
    txn->remove(pending_key);
5234
11
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5235
11
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5236
11
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5237
5238
11
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5239
11
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5240
11
    txn->remove(dbm_start_key, dbm_end_key);
5241
11
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5242
11
              << " end=" << hex(dbm_end_key);
5243
5244
11
    std::string versioned_idx_key = versioned::tablet_index_key({instance_id_, tablet_id});
5245
11
    std::string tablet_index_val;
5246
11
    err = txn->get(versioned_idx_key, &tablet_index_val);
5247
11
    if (err != TxnErrorCode::TXN_KEY_NOT_FOUND && err != TxnErrorCode::TXN_OK) {
5248
0
        LOG_WARNING("failed to get tablet index kv")
5249
0
                .tag("instance_id", instance_id_)
5250
0
                .tag("tablet_id", tablet_id)
5251
0
                .tag("err", err);
5252
0
        ret = -1;
5253
11
    } else if (err == TxnErrorCode::TXN_OK) {
5254
        // If the tablet index kv exists, we need to delete it
5255
10
        TabletIndexPB tablet_index_pb;
5256
10
        if (!tablet_index_pb.ParseFromString(tablet_index_val)) {
5257
0
            LOG_WARNING("failed to parse tablet index pb")
5258
0
                    .tag("instance_id", instance_id_)
5259
0
                    .tag("tablet_id", tablet_id);
5260
0
            ret = -1;
5261
10
        } else {
5262
10
            std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
5263
10
                    {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
5264
10
                     tablet_index_pb.index_id(), tablet_index_pb.partition_id(), tablet_id});
5265
10
            txn->remove(versioned_inverted_idx_key);
5266
10
            txn->remove(versioned_idx_key);
5267
10
        }
5268
10
    }
5269
5270
11
    err = txn->commit();
5271
11
    if (err != TxnErrorCode::TXN_OK) {
5272
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5273
0
        ret = -1;
5274
0
    }
5275
5276
11
    if (ret == 0) {
5277
        // All object files under tablet have been deleted
5278
11
        std::lock_guard lock(recycled_tablets_mtx_);
5279
11
        recycled_tablets_.insert(tablet_id);
5280
11
    }
5281
5282
11
    return ret;
5283
11
}
5284
5285
68
int InstanceRecycler::recycle_rowsets() {
5286
68
    if (should_recycle_versioned_keys()) {
5287
5
        return recycle_versioned_rowsets();
5288
5
    }
5289
5290
63
    const std::string task_name = "recycle_rowsets";
5291
63
    int64_t num_scanned = 0;
5292
63
    int64_t num_expired = 0;
5293
63
    int64_t num_prepare = 0;
5294
63
    int64_t num_compacted = 0;
5295
63
    int64_t num_empty_rowset = 0;
5296
63
    size_t total_rowset_key_size = 0;
5297
63
    size_t total_rowset_value_size = 0;
5298
63
    size_t expired_rowset_size = 0;
5299
63
    std::atomic_long num_recycled = 0;
5300
63
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5301
5302
63
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5303
63
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5304
63
    std::string recyc_rs_key0;
5305
63
    std::string recyc_rs_key1;
5306
63
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5307
63
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5308
5309
63
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5310
5311
63
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5312
63
    register_recycle_task(task_name, start_time);
5313
5314
63
    DORIS_CLOUD_DEFER {
5315
63
        unregister_recycle_task(task_name);
5316
63
        int64_t cost =
5317
63
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5318
63
        metrics_context.finish_report();
5319
63
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5320
63
                .tag("instance_id", instance_id_)
5321
63
                .tag("num_scanned", num_scanned)
5322
63
                .tag("num_expired", num_expired)
5323
63
                .tag("num_recycled", num_recycled)
5324
63
                .tag("num_recycled.prepare", num_prepare)
5325
63
                .tag("num_recycled.compacted", num_compacted)
5326
63
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5327
63
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5328
63
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5329
63
                .tag("expired_rowset_meta_size", expired_rowset_size);
5330
63
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5314
7
    DORIS_CLOUD_DEFER {
5315
7
        unregister_recycle_task(task_name);
5316
7
        int64_t cost =
5317
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5318
7
        metrics_context.finish_report();
5319
7
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5320
7
                .tag("instance_id", instance_id_)
5321
7
                .tag("num_scanned", num_scanned)
5322
7
                .tag("num_expired", num_expired)
5323
7
                .tag("num_recycled", num_recycled)
5324
7
                .tag("num_recycled.prepare", num_prepare)
5325
7
                .tag("num_recycled.compacted", num_compacted)
5326
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5327
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5328
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5329
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
5330
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5314
56
    DORIS_CLOUD_DEFER {
5315
56
        unregister_recycle_task(task_name);
5316
56
        int64_t cost =
5317
56
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5318
56
        metrics_context.finish_report();
5319
56
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5320
56
                .tag("instance_id", instance_id_)
5321
56
                .tag("num_scanned", num_scanned)
5322
56
                .tag("num_expired", num_expired)
5323
56
                .tag("num_recycled", num_recycled)
5324
56
                .tag("num_recycled.prepare", num_prepare)
5325
56
                .tag("num_recycled.compacted", num_compacted)
5326
56
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5327
56
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5328
56
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5329
56
                .tag("expired_rowset_meta_size", expired_rowset_size);
5330
56
    };
5331
5332
63
    struct RecycleRowsetEntry {
5333
63
        std::string key;
5334
63
        doris::RowsetMetaCloudPB meta;
5335
63
    };
5336
63
    struct RecycleRowsetDeleteJob {
5337
63
        std::vector<std::string> keys;
5338
63
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
5339
63
    };
5340
    // Store the scanned recycle key with rowset meta. The scanned key is the actual KV key to delete.
5341
63
    std::vector<RecycleRowsetEntry> rowsets;
5342
63
    int64_t current_tablet_id = -1;
5343
63
    int64_t recycled_rowset_count_for_current_tablet = 0;
5344
63
    bool current_tablet_skip_logged = false;
5345
63
    std::string next_scan_begin;
5346
63
    const int64_t rowset_batch_size_per_tablet =
5347
63
            std::max(1, config::recycle_rowsets_per_tablet_batch_size);
5348
63
    const int64_t delete_rowset_batch_size =
5349
63
            std::min(500000, config::recycle_rowsets_delete_batch_size);
5350
4.05k
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5351
4.05k
        if (current_tablet_id != tablet_id) {
5352
27
            current_tablet_id = tablet_id;
5353
27
            recycled_rowset_count_for_current_tablet = 0;
5354
27
            current_tablet_skip_logged = false;
5355
27
        }
5356
4.05k
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5357
7
            if (!current_tablet_skip_logged) {
5358
7
                LOG_INFO(
5359
7
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5360
7
                        .tag("instance_id", instance_id_)
5361
7
                        .tag("tablet_id", tablet_id)
5362
7
                        .tag("limit", rowset_batch_size_per_tablet);
5363
7
                current_tablet_skip_logged = true;
5364
7
            }
5365
7
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5366
7
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5367
7
            return false;
5368
7
        }
5369
4.04k
        ++recycled_rowset_count_for_current_tablet;
5370
4.04k
        return true;
5371
4.05k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_8clEl
Line
Count
Source
5350
7
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5351
7
        if (current_tablet_id != tablet_id) {
5352
7
            current_tablet_id = tablet_id;
5353
7
            recycled_rowset_count_for_current_tablet = 0;
5354
7
            current_tablet_skip_logged = false;
5355
7
        }
5356
7
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5357
0
            if (!current_tablet_skip_logged) {
5358
0
                LOG_INFO(
5359
0
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5360
0
                        .tag("instance_id", instance_id_)
5361
0
                        .tag("tablet_id", tablet_id)
5362
0
                        .tag("limit", rowset_batch_size_per_tablet);
5363
0
                current_tablet_skip_logged = true;
5364
0
            }
5365
0
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5366
0
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5367
0
            return false;
5368
0
        }
5369
7
        ++recycled_rowset_count_for_current_tablet;
5370
7
        return true;
5371
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_8clEl
Line
Count
Source
5350
4.04k
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5351
4.04k
        if (current_tablet_id != tablet_id) {
5352
20
            current_tablet_id = tablet_id;
5353
20
            recycled_rowset_count_for_current_tablet = 0;
5354
20
            current_tablet_skip_logged = false;
5355
20
        }
5356
4.04k
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5357
7
            if (!current_tablet_skip_logged) {
5358
7
                LOG_INFO(
5359
7
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5360
7
                        .tag("instance_id", instance_id_)
5361
7
                        .tag("tablet_id", tablet_id)
5362
7
                        .tag("limit", rowset_batch_size_per_tablet);
5363
7
                current_tablet_skip_logged = true;
5364
7
            }
5365
7
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5366
7
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5367
7
            return false;
5368
7
        }
5369
4.04k
        ++recycled_rowset_count_for_current_tablet;
5370
4.04k
        return true;
5371
4.04k
    };
5372
4.05k
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5373
4.05k
        if (next_scan_begin.empty()) {
5374
4.04k
            return false;
5375
4.04k
        }
5376
7
        *begin = std::move(next_scan_begin);
5377
7
        next_scan_begin.clear();
5378
7
        return true;
5379
4.05k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clEPNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5372
7
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5373
7
        if (next_scan_begin.empty()) {
5374
7
            return false;
5375
7
        }
5376
0
        *begin = std::move(next_scan_begin);
5377
0
        next_scan_begin.clear();
5378
0
        return true;
5379
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clEPNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5372
4.04k
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5373
4.04k
        if (next_scan_begin.empty()) {
5374
4.04k
            return false;
5375
4.04k
        }
5376
7
        *begin = std::move(next_scan_begin);
5377
7
        next_scan_begin.clear();
5378
7
        return true;
5379
4.04k
    };
5380
5381
63
    std::vector<std::string> rowset_keys_to_mark_recycled;
5382
63
    std::vector<std::string> rowset_keys_to_abort;
5383
63
    std::vector<std::string> prepare_rowset_keys_to_delete;
5384
5385
    // Store keys of rowset recycled by background workers
5386
63
    std::mutex async_recycled_rowset_keys_mutex;
5387
63
    std::vector<std::string> async_recycled_rowset_keys;
5388
63
    std::vector<std::string> rowset_keys_without_data;
5389
63
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5390
63
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5391
63
    worker_pool->start();
5392
63
    auto mark_abort_worker_pool = std::make_unique<SimpleThreadPool>(
5393
63
            config::instance_recycler_worker_pool_size, "recycle_rs_mark_abort");
5394
63
    mark_abort_worker_pool->start();
5395
    // TODO bacth delete
5396
4.03k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5397
4.03k
        std::string dbm_start_key =
5398
4.03k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5399
4.03k
        std::string dbm_end_key = dbm_start_key;
5400
4.03k
        encode_int64(INT64_MAX, &dbm_end_key);
5401
4.03k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5402
4.03k
        if (ret != 0) {
5403
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5404
0
                         << instance_id_;
5405
0
        }
5406
4.03k
        return ret;
5407
4.03k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_7clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5396
3
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5397
3
        std::string dbm_start_key =
5398
3
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5399
3
        std::string dbm_end_key = dbm_start_key;
5400
3
        encode_int64(INT64_MAX, &dbm_end_key);
5401
3
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5402
3
        if (ret != 0) {
5403
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5404
0
                         << instance_id_;
5405
0
        }
5406
3
        return ret;
5407
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_7clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5396
4.03k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5397
4.03k
        std::string dbm_start_key =
5398
4.03k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5399
4.03k
        std::string dbm_end_key = dbm_start_key;
5400
4.03k
        encode_int64(INT64_MAX, &dbm_end_key);
5401
4.03k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5402
4.03k
        if (ret != 0) {
5403
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5404
0
                         << instance_id_;
5405
0
        }
5406
4.03k
        return ret;
5407
4.03k
    };
5408
63
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5409
903
                                            int64_t tablet_id, const std::string& rowset_id) {
5410
        // Try to delete rowset data in background thread
5411
903
        int ret = worker_pool->submit_with_timeout(
5412
903
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5413
827
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5414
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5415
0
                        return;
5416
0
                    }
5417
827
                    std::vector<std::string> keys;
5418
827
                    {
5419
827
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5420
827
                        async_recycled_rowset_keys.push_back(std::move(key));
5421
827
                        if (async_recycled_rowset_keys.size() > 100) {
5422
5
                            keys.swap(async_recycled_rowset_keys);
5423
5
                        }
5424
827
                    }
5425
827
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5426
827
                    if (keys.empty()) return;
5427
5
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5428
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5429
0
                                     << instance_id_;
5430
5
                    } else {
5431
5
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5432
5
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5433
5
                                           num_recycled, start_time);
5434
5
                    }
5435
5
                },
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
5412
3
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5413
3
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5414
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5415
0
                        return;
5416
0
                    }
5417
3
                    std::vector<std::string> keys;
5418
3
                    {
5419
3
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5420
3
                        async_recycled_rowset_keys.push_back(std::move(key));
5421
3
                        if (async_recycled_rowset_keys.size() > 100) {
5422
0
                            keys.swap(async_recycled_rowset_keys);
5423
0
                        }
5424
3
                    }
5425
3
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5426
3
                    if (keys.empty()) return;
5427
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5428
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5429
0
                                     << instance_id_;
5430
0
                    } else {
5431
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5432
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5433
0
                                           num_recycled, start_time);
5434
0
                    }
5435
0
                },
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
5412
824
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5413
824
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5414
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5415
0
                        return;
5416
0
                    }
5417
824
                    std::vector<std::string> keys;
5418
824
                    {
5419
824
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5420
824
                        async_recycled_rowset_keys.push_back(std::move(key));
5421
824
                        if (async_recycled_rowset_keys.size() > 100) {
5422
5
                            keys.swap(async_recycled_rowset_keys);
5423
5
                        }
5424
824
                    }
5425
824
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5426
824
                    if (keys.empty()) return;
5427
5
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5428
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5429
0
                                     << instance_id_;
5430
5
                    } else {
5431
5
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5432
5
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5433
5
                                           num_recycled, start_time);
5434
5
                    }
5435
5
                },
5436
903
                0);
5437
903
        if (ret == 0) return 0;
5438
        // Submit task failed, delete rowset data in current thread
5439
76
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5440
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5441
0
            return -1;
5442
0
        }
5443
76
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5444
0
            return -1;
5445
0
        }
5446
76
        rowset_keys_without_data.push_back(std::move(key));
5447
76
        return 0;
5448
76
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
5409
3
                                            int64_t tablet_id, const std::string& rowset_id) {
5410
        // Try to delete rowset data in background thread
5411
3
        int ret = worker_pool->submit_with_timeout(
5412
3
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5413
3
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5414
3
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5415
3
                        return;
5416
3
                    }
5417
3
                    std::vector<std::string> keys;
5418
3
                    {
5419
3
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5420
3
                        async_recycled_rowset_keys.push_back(std::move(key));
5421
3
                        if (async_recycled_rowset_keys.size() > 100) {
5422
3
                            keys.swap(async_recycled_rowset_keys);
5423
3
                        }
5424
3
                    }
5425
3
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5426
3
                    if (keys.empty()) return;
5427
3
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5428
3
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5429
3
                                     << instance_id_;
5430
3
                    } else {
5431
3
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5432
3
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5433
3
                                           num_recycled, start_time);
5434
3
                    }
5435
3
                },
5436
3
                0);
5437
3
        if (ret == 0) return 0;
5438
        // Submit task failed, delete rowset data in current thread
5439
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5440
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5441
0
            return -1;
5442
0
        }
5443
0
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5444
0
            return -1;
5445
0
        }
5446
0
        rowset_keys_without_data.push_back(std::move(key));
5447
0
        return 0;
5448
0
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
5409
900
                                            int64_t tablet_id, const std::string& rowset_id) {
5410
        // Try to delete rowset data in background thread
5411
900
        int ret = worker_pool->submit_with_timeout(
5412
900
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5413
900
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5414
900
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5415
900
                        return;
5416
900
                    }
5417
900
                    std::vector<std::string> keys;
5418
900
                    {
5419
900
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5420
900
                        async_recycled_rowset_keys.push_back(std::move(key));
5421
900
                        if (async_recycled_rowset_keys.size() > 100) {
5422
900
                            keys.swap(async_recycled_rowset_keys);
5423
900
                        }
5424
900
                    }
5425
900
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5426
900
                    if (keys.empty()) return;
5427
900
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5428
900
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5429
900
                                     << instance_id_;
5430
900
                    } else {
5431
900
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5432
900
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5433
900
                                           num_recycled, start_time);
5434
900
                    }
5435
900
                },
5436
900
                0);
5437
900
        if (ret == 0) return 0;
5438
        // Submit task failed, delete rowset data in current thread
5439
76
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5440
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5441
0
            return -1;
5442
0
        }
5443
76
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5444
0
            return -1;
5445
0
        }
5446
76
        rowset_keys_without_data.push_back(std::move(key));
5447
76
        return 0;
5448
76
    };
5449
5450
63
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5451
5452
4.05k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5453
4.05k
        ++num_scanned;
5454
4.05k
        total_rowset_key_size += k.size();
5455
4.05k
        total_rowset_value_size += v.size();
5456
4.05k
        RecycleRowsetPB rowset;
5457
4.05k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5458
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5459
0
            return -1;
5460
0
        }
5461
5462
4.05k
        int64_t current_time = ::time(nullptr);
5463
4.05k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5464
5465
4.05k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5466
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5467
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5468
4.05k
        if (current_time < expiration) { // not expired
5469
0
            return 0;
5470
0
        }
5471
4.05k
        ++num_expired;
5472
4.05k
        expired_rowset_size += v.size();
5473
5474
4.05k
        int64_t tablet_id =
5475
4.05k
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5476
4.05k
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5477
7
            return 0;
5478
7
        }
5479
5480
4.04k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5481
252
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5482
                // in old version, keep this key-value pair and it needs to be checked manually
5483
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5484
0
                return -1;
5485
0
            }
5486
252
            if (rowset.resource_id().empty()) [[unlikely]] {
5487
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5488
2
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5489
2
                          << hex(k) << " value=" << proto_to_json(rowset);
5490
2
                rowset_keys_without_data.emplace_back(k);
5491
2
                return 0;
5492
2
            }
5493
            // decode rowset_id
5494
250
            auto k1 = k;
5495
250
            k1.remove_prefix(1);
5496
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5497
250
            decode_key(&k1, &out);
5498
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5499
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5500
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5501
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5502
250
                      << " task_type=" << metrics_context.operation_type;
5503
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5504
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5505
0
                return -1;
5506
0
            }
5507
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5508
250
            metrics_context.total_recycled_num++;
5509
250
            segment_metrics_context_.total_recycled_data_size +=
5510
250
                    rowset.rowset_meta().total_disk_size();
5511
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5512
250
            return 0;
5513
250
        }
5514
5515
3.79k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5516
3.79k
        if (config::enable_mark_delete_rowset_before_recycle) {
5517
6
            if (need_mark_rowset_as_recycled(rowset)) {
5518
4
                rowset_keys_to_mark_recycled.emplace_back(k);
5519
4
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5520
4
                             "at next turn, instance_id="
5521
4
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5522
4
                          << " version=[" << rowset_meta->start_version() << '-'
5523
4
                          << rowset_meta->end_version() << "]";
5524
4
                return 0;
5525
4
            }
5526
6
        }
5527
5528
3.79k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5529
3.79k
            rowset_meta->end_version() != 1) {
5530
2
            if (make_deferred_abort_task(rowset).has_value()) {
5531
2
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5532
2
                             "instance_id="
5533
2
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5534
2
                          << " version=[" << rowset_meta->start_version() << '-'
5535
2
                          << rowset_meta->end_version() << "]";
5536
2
                rowset_keys_to_abort.emplace_back(k);
5537
2
            }
5538
2
        }
5539
5540
        // TODO(plat1ko): check rowset not referenced
5541
3.79k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5542
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5543
0
                LOG_INFO("recycle rowset that has empty resource id");
5544
0
            } else {
5545
                // other situations, keep this key-value pair and it needs to be checked manually
5546
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5547
0
                return -1;
5548
0
            }
5549
0
        }
5550
3.79k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5551
3.79k
                  << " tablet_id=" << rowset_meta->tablet_id()
5552
3.79k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5553
3.79k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5554
3.79k
                  << "] txn_id=" << rowset_meta->txn_id()
5555
3.79k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5556
3.79k
                  << " rowset_meta_size=" << v.size()
5557
3.79k
                  << " creation_time=" << rowset_meta->creation_time()
5558
3.79k
                  << " task_type=" << metrics_context.operation_type;
5559
3.79k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5560
            // unable to calculate file path, can only be deleted by rowset id prefix
5561
653
            num_prepare += 1;
5562
653
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5563
653
                                             rowset_meta->tablet_id(),
5564
653
                                             rowset_meta->rowset_id_v2()) != 0) {
5565
0
                return -1;
5566
0
            }
5567
3.13k
        } else {
5568
3.13k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5569
3.13k
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
5570
3.13k
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
5571
3.13k
            } else {
5572
3
                ++num_empty_rowset;
5573
3
                rowset_keys_without_data.emplace_back(k);
5574
3
            }
5575
3.13k
        }
5576
3.79k
        return 0;
5577
3.79k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5452
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5453
7
        ++num_scanned;
5454
7
        total_rowset_key_size += k.size();
5455
7
        total_rowset_value_size += v.size();
5456
7
        RecycleRowsetPB rowset;
5457
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5458
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5459
0
            return -1;
5460
0
        }
5461
5462
7
        int64_t current_time = ::time(nullptr);
5463
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5464
5465
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5466
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5467
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5468
7
        if (current_time < expiration) { // not expired
5469
0
            return 0;
5470
0
        }
5471
7
        ++num_expired;
5472
7
        expired_rowset_size += v.size();
5473
5474
7
        int64_t tablet_id =
5475
7
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5476
7
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5477
0
            return 0;
5478
0
        }
5479
5480
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5481
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5482
                // in old version, keep this key-value pair and it needs to be checked manually
5483
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5484
0
                return -1;
5485
0
            }
5486
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5487
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5488
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5489
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5490
0
                rowset_keys_without_data.emplace_back(k);
5491
0
                return 0;
5492
0
            }
5493
            // decode rowset_id
5494
0
            auto k1 = k;
5495
0
            k1.remove_prefix(1);
5496
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5497
0
            decode_key(&k1, &out);
5498
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5499
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5500
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5501
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5502
0
                      << " task_type=" << metrics_context.operation_type;
5503
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5504
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5505
0
                return -1;
5506
0
            }
5507
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5508
0
            metrics_context.total_recycled_num++;
5509
0
            segment_metrics_context_.total_recycled_data_size +=
5510
0
                    rowset.rowset_meta().total_disk_size();
5511
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5512
0
            return 0;
5513
0
        }
5514
5515
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
5516
7
        if (config::enable_mark_delete_rowset_before_recycle) {
5517
6
            if (need_mark_rowset_as_recycled(rowset)) {
5518
4
                rowset_keys_to_mark_recycled.emplace_back(k);
5519
4
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5520
4
                             "at next turn, instance_id="
5521
4
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5522
4
                          << " version=[" << rowset_meta->start_version() << '-'
5523
4
                          << rowset_meta->end_version() << "]";
5524
4
                return 0;
5525
4
            }
5526
6
        }
5527
5528
3
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5529
3
            rowset_meta->end_version() != 1) {
5530
2
            if (make_deferred_abort_task(rowset).has_value()) {
5531
2
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5532
2
                             "instance_id="
5533
2
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5534
2
                          << " version=[" << rowset_meta->start_version() << '-'
5535
2
                          << rowset_meta->end_version() << "]";
5536
2
                rowset_keys_to_abort.emplace_back(k);
5537
2
            }
5538
2
        }
5539
5540
        // TODO(plat1ko): check rowset not referenced
5541
3
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5542
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5543
0
                LOG_INFO("recycle rowset that has empty resource id");
5544
0
            } else {
5545
                // other situations, keep this key-value pair and it needs to be checked manually
5546
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5547
0
                return -1;
5548
0
            }
5549
0
        }
5550
3
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5551
3
                  << " tablet_id=" << rowset_meta->tablet_id()
5552
3
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5553
3
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5554
3
                  << "] txn_id=" << rowset_meta->txn_id()
5555
3
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5556
3
                  << " rowset_meta_size=" << v.size()
5557
3
                  << " creation_time=" << rowset_meta->creation_time()
5558
3
                  << " task_type=" << metrics_context.operation_type;
5559
3
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5560
            // unable to calculate file path, can only be deleted by rowset id prefix
5561
3
            num_prepare += 1;
5562
3
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5563
3
                                             rowset_meta->tablet_id(),
5564
3
                                             rowset_meta->rowset_id_v2()) != 0) {
5565
0
                return -1;
5566
0
            }
5567
3
        } else {
5568
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5569
0
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
5570
0
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
5571
0
            } else {
5572
0
                ++num_empty_rowset;
5573
0
                rowset_keys_without_data.emplace_back(k);
5574
0
            }
5575
0
        }
5576
3
        return 0;
5577
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5452
4.04k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5453
4.04k
        ++num_scanned;
5454
4.04k
        total_rowset_key_size += k.size();
5455
4.04k
        total_rowset_value_size += v.size();
5456
4.04k
        RecycleRowsetPB rowset;
5457
4.04k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5458
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5459
0
            return -1;
5460
0
        }
5461
5462
4.04k
        int64_t current_time = ::time(nullptr);
5463
4.04k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5464
5465
4.04k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5466
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5467
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5468
4.04k
        if (current_time < expiration) { // not expired
5469
0
            return 0;
5470
0
        }
5471
4.04k
        ++num_expired;
5472
4.04k
        expired_rowset_size += v.size();
5473
5474
4.04k
        int64_t tablet_id =
5475
4.04k
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5476
4.04k
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5477
7
            return 0;
5478
7
        }
5479
5480
4.04k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5481
252
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5482
                // in old version, keep this key-value pair and it needs to be checked manually
5483
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5484
0
                return -1;
5485
0
            }
5486
252
            if (rowset.resource_id().empty()) [[unlikely]] {
5487
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5488
2
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5489
2
                          << hex(k) << " value=" << proto_to_json(rowset);
5490
2
                rowset_keys_without_data.emplace_back(k);
5491
2
                return 0;
5492
2
            }
5493
            // decode rowset_id
5494
250
            auto k1 = k;
5495
250
            k1.remove_prefix(1);
5496
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5497
250
            decode_key(&k1, &out);
5498
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5499
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5500
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5501
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5502
250
                      << " task_type=" << metrics_context.operation_type;
5503
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5504
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5505
0
                return -1;
5506
0
            }
5507
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5508
250
            metrics_context.total_recycled_num++;
5509
250
            segment_metrics_context_.total_recycled_data_size +=
5510
250
                    rowset.rowset_meta().total_disk_size();
5511
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5512
250
            return 0;
5513
250
        }
5514
5515
3.78k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5516
3.78k
        if (config::enable_mark_delete_rowset_before_recycle) {
5517
0
            if (need_mark_rowset_as_recycled(rowset)) {
5518
0
                rowset_keys_to_mark_recycled.emplace_back(k);
5519
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5520
0
                             "at next turn, instance_id="
5521
0
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5522
0
                          << " version=[" << rowset_meta->start_version() << '-'
5523
0
                          << rowset_meta->end_version() << "]";
5524
0
                return 0;
5525
0
            }
5526
0
        }
5527
5528
3.78k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5529
3.78k
            rowset_meta->end_version() != 1) {
5530
0
            if (make_deferred_abort_task(rowset).has_value()) {
5531
0
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5532
0
                             "instance_id="
5533
0
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5534
0
                          << " version=[" << rowset_meta->start_version() << '-'
5535
0
                          << rowset_meta->end_version() << "]";
5536
0
                rowset_keys_to_abort.emplace_back(k);
5537
0
            }
5538
0
        }
5539
5540
        // TODO(plat1ko): check rowset not referenced
5541
3.78k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5542
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5543
0
                LOG_INFO("recycle rowset that has empty resource id");
5544
0
            } else {
5545
                // other situations, keep this key-value pair and it needs to be checked manually
5546
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5547
0
                return -1;
5548
0
            }
5549
0
        }
5550
3.78k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5551
3.78k
                  << " tablet_id=" << rowset_meta->tablet_id()
5552
3.78k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5553
3.78k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5554
3.78k
                  << "] txn_id=" << rowset_meta->txn_id()
5555
3.78k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5556
3.78k
                  << " rowset_meta_size=" << v.size()
5557
3.78k
                  << " creation_time=" << rowset_meta->creation_time()
5558
3.78k
                  << " task_type=" << metrics_context.operation_type;
5559
3.78k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5560
            // unable to calculate file path, can only be deleted by rowset id prefix
5561
650
            num_prepare += 1;
5562
650
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5563
650
                                             rowset_meta->tablet_id(),
5564
650
                                             rowset_meta->rowset_id_v2()) != 0) {
5565
0
                return -1;
5566
0
            }
5567
3.13k
        } else {
5568
3.13k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5569
3.13k
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
5570
3.13k
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
5571
3.13k
            } else {
5572
3
                ++num_empty_rowset;
5573
3
                rowset_keys_without_data.emplace_back(k);
5574
3
            }
5575
3.13k
        }
5576
3.78k
        return 0;
5577
3.78k
    };
5578
5579
63
    auto submit_delete_rowset_data_job = [&](std::vector<std::string> rowset_keys,
5580
63
                                             std::map<std::string, RowsetMetaCloudPB> rowsets) {
5581
22
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys),
5582
22
                             rowsets_to_delete = std::move(rowsets)]() {
5583
22
            if (!rowsets_to_delete.empty() &&
5584
22
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5585
17
                                   metrics_context) != 0) {
5586
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5587
0
                return;
5588
0
            }
5589
3.13k
            for (const auto& [_, rs] : rowsets_to_delete) {
5590
3.13k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5591
0
                    return;
5592
0
                }
5593
3.13k
            }
5594
22
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5595
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5596
0
                return;
5597
0
            }
5598
5599
22
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5600
22
        });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_6clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESt3mapIS9_NS_17RowsetMetaCloudPBESt4lessIS9_ESaISt4pairIKS9_SD_EEEENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_6clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESt3mapIS9_NS_17RowsetMetaCloudPBESt4lessIS9_ESaISt4pairIKS9_SD_EEEENKUlvE_clEv
Line
Count
Source
5582
22
                             rowsets_to_delete = std::move(rowsets)]() {
5583
22
            if (!rowsets_to_delete.empty() &&
5584
22
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5585
17
                                   metrics_context) != 0) {
5586
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5587
0
                return;
5588
0
            }
5589
3.13k
            for (const auto& [_, rs] : rowsets_to_delete) {
5590
3.13k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5591
0
                    return;
5592
0
                }
5593
3.13k
            }
5594
22
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5595
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5596
0
                return;
5597
0
            }
5598
5599
22
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5600
22
        });
5601
22
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_6clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESt3mapIS9_NS_17RowsetMetaCloudPBESt4lessIS9_ESaISt4pairIKS9_SD_EEE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_6clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESt3mapIS9_NS_17RowsetMetaCloudPBESt4lessIS9_ESaISt4pairIKS9_SD_EEE
Line
Count
Source
5580
22
                                             std::map<std::string, RowsetMetaCloudPB> rowsets) {
5581
22
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys),
5582
22
                             rowsets_to_delete = std::move(rowsets)]() {
5583
22
            if (!rowsets_to_delete.empty() &&
5584
22
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5585
22
                                   metrics_context) != 0) {
5586
22
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5587
22
                return;
5588
22
            }
5589
22
            for (const auto& [_, rs] : rowsets_to_delete) {
5590
22
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5591
22
                    return;
5592
22
                }
5593
22
            }
5594
22
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5595
22
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5596
22
                return;
5597
22
            }
5598
5599
22
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5600
22
        });
5601
22
    };
5602
5603
63
    auto submit_mark_abort_rowset_job = [&](std::vector<std::string> rowset_keys_to_mark,
5604
105
                                            std::vector<std::string> rowset_keys_to_abort) {
5605
105
        if (rowset_keys_to_mark.empty() && rowset_keys_to_abort.empty()) {
5606
99
            return;
5607
99
        }
5608
6
        mark_abort_worker_pool->submit([&, rowset_keys_to_mark = std::move(rowset_keys_to_mark),
5609
6
                                        rowset_keys_to_abort =
5610
6
                                                std::move(rowset_keys_to_abort)]() mutable {
5611
6
            auto start = steady_clock::now();
5612
6
            DORIS_CLOUD_DEFER {
5613
6
                auto cost = duration_cast<milliseconds>(steady_clock::now() - start).count();
5614
6
                LOG(INFO) << "finish mark and abort rowset job, instance_id=" << instance_id_ << ' '
5615
6
                          << "cost_ms=" << cost << ' '
5616
6
                          << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size() << ' '
5617
6
                          << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5618
6
            };
recycler.cpp:_ZZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_ENUlvE_clEvENKUlvE_clEv
Line
Count
Source
5612
6
            DORIS_CLOUD_DEFER {
5613
6
                auto cost = duration_cast<milliseconds>(steady_clock::now() - start).count();
5614
6
                LOG(INFO) << "finish mark and abort rowset job, instance_id=" << instance_id_ << ' '
5615
6
                          << "cost_ms=" << cost << ' '
5616
6
                          << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size() << ' '
5617
6
                          << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5618
6
            };
Unexecuted instantiation: recycler_test.cpp:_ZZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_ENUlvE_clEvENKUlvE_clEv
5619
6
            if (!rowset_keys_to_mark.empty() &&
5620
6
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5621
4
                                                                rowset_keys_to_mark) != 0) {
5622
0
                LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id="
5623
0
                             << instance_id_ << ' '
5624
0
                             << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size();
5625
0
                return;
5626
0
            }
5627
6
            if (!rowset_keys_to_abort.empty() &&
5628
6
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort, true) !=
5629
2
                        0) {
5630
0
                LOG(WARNING) << "failed to batch abort txn or job for related rowset, "
5631
0
                                "instance_id="
5632
0
                             << instance_id_ << ' '
5633
0
                             << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5634
0
                return;
5635
0
            }
5636
6
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_ENUlvE_clEv
Line
Count
Source
5610
6
                                                std::move(rowset_keys_to_abort)]() mutable {
5611
6
            auto start = steady_clock::now();
5612
6
            DORIS_CLOUD_DEFER {
5613
6
                auto cost = duration_cast<milliseconds>(steady_clock::now() - start).count();
5614
6
                LOG(INFO) << "finish mark and abort rowset job, instance_id=" << instance_id_ << ' '
5615
6
                          << "cost_ms=" << cost << ' '
5616
6
                          << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size() << ' '
5617
6
                          << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5618
6
            };
5619
6
            if (!rowset_keys_to_mark.empty() &&
5620
6
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5621
4
                                                                rowset_keys_to_mark) != 0) {
5622
0
                LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id="
5623
0
                             << instance_id_ << ' '
5624
0
                             << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size();
5625
0
                return;
5626
0
            }
5627
6
            if (!rowset_keys_to_abort.empty() &&
5628
6
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort, true) !=
5629
2
                        0) {
5630
0
                LOG(WARNING) << "failed to batch abort txn or job for related rowset, "
5631
0
                                "instance_id="
5632
0
                             << instance_id_ << ' '
5633
0
                             << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5634
0
                return;
5635
0
            }
5636
6
        });
Unexecuted instantiation: recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_ENUlvE_clEv
5637
6
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_
Line
Count
Source
5604
14
                                            std::vector<std::string> rowset_keys_to_abort) {
5605
14
        if (rowset_keys_to_mark.empty() && rowset_keys_to_abort.empty()) {
5606
8
            return;
5607
8
        }
5608
6
        mark_abort_worker_pool->submit([&, rowset_keys_to_mark = std::move(rowset_keys_to_mark),
5609
6
                                        rowset_keys_to_abort =
5610
6
                                                std::move(rowset_keys_to_abort)]() mutable {
5611
6
            auto start = steady_clock::now();
5612
6
            DORIS_CLOUD_DEFER {
5613
6
                auto cost = duration_cast<milliseconds>(steady_clock::now() - start).count();
5614
6
                LOG(INFO) << "finish mark and abort rowset job, instance_id=" << instance_id_ << ' '
5615
6
                          << "cost_ms=" << cost << ' '
5616
6
                          << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size() << ' '
5617
6
                          << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5618
6
            };
5619
6
            if (!rowset_keys_to_mark.empty() &&
5620
6
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5621
6
                                                                rowset_keys_to_mark) != 0) {
5622
6
                LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id="
5623
6
                             << instance_id_ << ' '
5624
6
                             << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size();
5625
6
                return;
5626
6
            }
5627
6
            if (!rowset_keys_to_abort.empty() &&
5628
6
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort, true) !=
5629
6
                        0) {
5630
6
                LOG(WARNING) << "failed to batch abort txn or job for related rowset, "
5631
6
                                "instance_id="
5632
6
                             << instance_id_ << ' '
5633
6
                             << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5634
6
                return;
5635
6
            }
5636
6
        });
5637
6
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_
Line
Count
Source
5604
91
                                            std::vector<std::string> rowset_keys_to_abort) {
5605
91
        if (rowset_keys_to_mark.empty() && rowset_keys_to_abort.empty()) {
5606
91
            return;
5607
91
        }
5608
0
        mark_abort_worker_pool->submit([&, rowset_keys_to_mark = std::move(rowset_keys_to_mark),
5609
0
                                        rowset_keys_to_abort =
5610
0
                                                std::move(rowset_keys_to_abort)]() mutable {
5611
0
            auto start = steady_clock::now();
5612
0
            DORIS_CLOUD_DEFER {
5613
0
                auto cost = duration_cast<milliseconds>(steady_clock::now() - start).count();
5614
0
                LOG(INFO) << "finish mark and abort rowset job, instance_id=" << instance_id_ << ' '
5615
0
                          << "cost_ms=" << cost << ' '
5616
0
                          << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size() << ' '
5617
0
                          << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5618
0
            };
5619
0
            if (!rowset_keys_to_mark.empty() &&
5620
0
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5621
0
                                                                rowset_keys_to_mark) != 0) {
5622
0
                LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id="
5623
0
                             << instance_id_ << ' '
5624
0
                             << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size();
5625
0
                return;
5626
0
            }
5627
0
            if (!rowset_keys_to_abort.empty() &&
5628
0
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort, true) !=
5629
0
                        0) {
5630
0
                LOG(WARNING) << "failed to batch abort txn or job for related rowset, "
5631
0
                                "instance_id="
5632
0
                             << instance_id_ << ' '
5633
0
                             << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5634
0
                return;
5635
0
            }
5636
0
        });
5637
0
    };
5638
5639
63
    bool scan_finished = false;
5640
105
    auto loop_done = [&]() -> int {
5641
105
        std::vector<std::string> mark_keys_to_process;
5642
105
        std::vector<std::string> abort_keys_to_process;
5643
105
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5644
105
        abort_keys_to_process.swap(rowset_keys_to_abort);
5645
105
        submit_mark_abort_rowset_job(std::move(mark_keys_to_process),
5646
105
                                     std::move(abort_keys_to_process));
5647
105
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
5648
42
            return 0;
5649
42
        }
5650
5651
63
        DORIS_CLOUD_DEFER {
5652
            // if return -1 in loop done, rowset info in memory is not cleared,
5653
            // it can lead to memory accumulation
5654
63
            rowset_keys_without_data.clear();
5655
63
            rowsets.clear();
5656
63
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
5651
7
        DORIS_CLOUD_DEFER {
5652
            // if return -1 in loop done, rowset info in memory is not cleared,
5653
            // it can lead to memory accumulation
5654
7
            rowset_keys_without_data.clear();
5655
7
            rowsets.clear();
5656
7
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
5651
56
        DORIS_CLOUD_DEFER {
5652
            // if return -1 in loop done, rowset info in memory is not cleared,
5653
            // it can lead to memory accumulation
5654
56
            rowset_keys_without_data.clear();
5655
56
            rowsets.clear();
5656
56
        };
5657
63
        std::random_device rd;
5658
63
        std::mt19937 g(rd());
5659
63
        std::ranges::shuffle(rowsets, g);
5660
5661
63
        std::vector<std::string> rowset_keys_to_delete;
5662
63
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
5663
        // rowset_id -> rowset_meta
5664
        // store rowset id and meta for statistics rs size when delete
5665
63
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5666
5667
63
        size_t rowsets_per_batch_size = 0;
5668
3.13k
        for (auto& rowset : rowsets) {
5669
3.13k
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
5670
3.13k
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
5671
3.13k
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
5672
3.12k
                continue;
5673
3.12k
            }
5674
5675
8
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5676
8
                                          std::move(rowsets_to_delete));
5677
8
            rowsets_per_batch_size = 0;
5678
8
            rowset_keys_to_delete.clear();
5679
8
            rowsets_to_delete.clear();
5680
8
        }
5681
5682
63
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
5683
9
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5684
9
                                          std::move(rowsets_to_delete));
5685
9
        }
5686
5687
68
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
5688
5
            auto begin = rowset_keys_without_data.begin() + i;
5689
5
            auto end = rowset_keys_without_data.begin() +
5690
5
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
5691
5
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
5692
5
                                                           std::make_move_iterator(end));
5693
5
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
5694
5
        }
5695
5696
63
        return 0;
5697
105
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5640
14
    auto loop_done = [&]() -> int {
5641
14
        std::vector<std::string> mark_keys_to_process;
5642
14
        std::vector<std::string> abort_keys_to_process;
5643
14
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5644
14
        abort_keys_to_process.swap(rowset_keys_to_abort);
5645
14
        submit_mark_abort_rowset_job(std::move(mark_keys_to_process),
5646
14
                                     std::move(abort_keys_to_process));
5647
14
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
5648
7
            return 0;
5649
7
        }
5650
5651
7
        DORIS_CLOUD_DEFER {
5652
            // if return -1 in loop done, rowset info in memory is not cleared,
5653
            // it can lead to memory accumulation
5654
7
            rowset_keys_without_data.clear();
5655
7
            rowsets.clear();
5656
7
        };
5657
7
        std::random_device rd;
5658
7
        std::mt19937 g(rd());
5659
7
        std::ranges::shuffle(rowsets, g);
5660
5661
7
        std::vector<std::string> rowset_keys_to_delete;
5662
7
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
5663
        // rowset_id -> rowset_meta
5664
        // store rowset id and meta for statistics rs size when delete
5665
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5666
5667
7
        size_t rowsets_per_batch_size = 0;
5668
7
        for (auto& rowset : rowsets) {
5669
0
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
5670
0
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
5671
0
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
5672
0
                continue;
5673
0
            }
5674
5675
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5676
0
                                          std::move(rowsets_to_delete));
5677
0
            rowsets_per_batch_size = 0;
5678
0
            rowset_keys_to_delete.clear();
5679
0
            rowsets_to_delete.clear();
5680
0
        }
5681
5682
7
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
5683
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5684
0
                                          std::move(rowsets_to_delete));
5685
0
        }
5686
5687
7
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
5688
0
            auto begin = rowset_keys_without_data.begin() + i;
5689
0
            auto end = rowset_keys_without_data.begin() +
5690
0
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
5691
0
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
5692
0
                                                           std::make_move_iterator(end));
5693
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
5694
0
        }
5695
5696
7
        return 0;
5697
14
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5640
91
    auto loop_done = [&]() -> int {
5641
91
        std::vector<std::string> mark_keys_to_process;
5642
91
        std::vector<std::string> abort_keys_to_process;
5643
91
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5644
91
        abort_keys_to_process.swap(rowset_keys_to_abort);
5645
91
        submit_mark_abort_rowset_job(std::move(mark_keys_to_process),
5646
91
                                     std::move(abort_keys_to_process));
5647
91
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
5648
35
            return 0;
5649
35
        }
5650
5651
56
        DORIS_CLOUD_DEFER {
5652
            // if return -1 in loop done, rowset info in memory is not cleared,
5653
            // it can lead to memory accumulation
5654
56
            rowset_keys_without_data.clear();
5655
56
            rowsets.clear();
5656
56
        };
5657
56
        std::random_device rd;
5658
56
        std::mt19937 g(rd());
5659
56
        std::ranges::shuffle(rowsets, g);
5660
5661
56
        std::vector<std::string> rowset_keys_to_delete;
5662
56
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
5663
        // rowset_id -> rowset_meta
5664
        // store rowset id and meta for statistics rs size when delete
5665
56
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5666
5667
56
        size_t rowsets_per_batch_size = 0;
5668
3.13k
        for (auto& rowset : rowsets) {
5669
3.13k
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
5670
3.13k
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
5671
3.13k
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
5672
3.12k
                continue;
5673
3.12k
            }
5674
5675
8
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5676
8
                                          std::move(rowsets_to_delete));
5677
8
            rowsets_per_batch_size = 0;
5678
8
            rowset_keys_to_delete.clear();
5679
8
            rowsets_to_delete.clear();
5680
8
        }
5681
5682
56
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
5683
9
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5684
9
                                          std::move(rowsets_to_delete));
5685
9
        }
5686
5687
61
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
5688
5
            auto begin = rowset_keys_without_data.begin() + i;
5689
5
            auto end = rowset_keys_without_data.begin() +
5690
5
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
5691
5
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
5692
5
                                                           std::make_move_iterator(end));
5693
5
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
5694
5
        }
5695
5696
56
        return 0;
5697
91
    };
5698
5699
63
    if (config::enable_recycler_stats_metrics) {
5700
0
        scan_and_statistics_rowsets();
5701
0
    }
5702
    // recycle_func and loop_done for scan and recycle
5703
63
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv), loop_done,
5704
63
                               std::move(next_scan_begin_getter));
5705
63
    scan_finished = true;
5706
    // if the size of rowsets is always less than delete_rowset_batch_size
5707
    // it need to submit the task directly
5708
    // else if the size of rowsets is greater than delete_rowset_batch_size,
5709
    // but there are residual, whether due to failed or unsuccessful cleanup, this behavior is idempotent
5710
63
    if (loop_done() != 0) {
5711
0
        ret = -1;
5712
0
    }
5713
5714
63
    mark_abort_worker_pool->stop();
5715
63
    worker_pool->stop();
5716
5717
63
    if (!async_recycled_rowset_keys.empty()) {
5718
7
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5719
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5720
0
            return -1;
5721
7
        } else {
5722
7
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5723
7
        }
5724
7
    }
5725
5726
    // Report final metrics after all concurrent tasks completed
5727
63
    segment_metrics_context_.report();
5728
63
    metrics_context.report();
5729
5730
63
    return ret;
5731
63
}
5732
5733
int InstanceRecycler::next_recycle_rowset_tablet_key(const std::string& instance_id,
5734
1
                                                     int64_t tablet_id, std::string* next_key) {
5735
1
    DCHECK(next_key != nullptr);
5736
1
    if (tablet_id == std::numeric_limits<int64_t>::max()) {
5737
0
        return -1;
5738
0
    }
5739
1
    *next_key = recycle_rowset_key({instance_id, tablet_id + 1, ""});
5740
1
    return 0;
5741
1
}
5742
5743
13
int InstanceRecycler::recycle_restore_jobs() {
5744
13
    const std::string task_name = "recycle_restore_jobs";
5745
13
    int64_t num_scanned = 0;
5746
13
    int64_t num_expired = 0;
5747
13
    int64_t num_recycled = 0;
5748
13
    int64_t num_aborted = 0;
5749
5750
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5751
5752
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
5753
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
5754
13
    std::string restore_job_key0;
5755
13
    std::string restore_job_key1;
5756
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
5757
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
5758
5759
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
5760
5761
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5762
13
    register_recycle_task(task_name, start_time);
5763
5764
13
    DORIS_CLOUD_DEFER {
5765
13
        unregister_recycle_task(task_name);
5766
13
        int64_t cost =
5767
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5768
13
        metrics_context.finish_report();
5769
5770
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5771
13
                .tag("instance_id", instance_id_)
5772
13
                .tag("num_scanned", num_scanned)
5773
13
                .tag("num_expired", num_expired)
5774
13
                .tag("num_recycled", num_recycled)
5775
13
                .tag("num_aborted", num_aborted);
5776
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
5764
13
    DORIS_CLOUD_DEFER {
5765
13
        unregister_recycle_task(task_name);
5766
13
        int64_t cost =
5767
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5768
13
        metrics_context.finish_report();
5769
5770
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5771
13
                .tag("instance_id", instance_id_)
5772
13
                .tag("num_scanned", num_scanned)
5773
13
                .tag("num_expired", num_expired)
5774
13
                .tag("num_recycled", num_recycled)
5775
13
                .tag("num_aborted", num_aborted);
5776
13
    };
5777
5778
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5779
5780
13
    std::vector<std::string_view> restore_job_keys;
5781
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5782
41
        ++num_scanned;
5783
41
        RestoreJobCloudPB restore_job_pb;
5784
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5785
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5786
0
            return -1;
5787
0
        }
5788
41
        int64_t expiration =
5789
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5790
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5791
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5792
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5793
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5794
0
                   << " state=" << restore_job_pb.state();
5795
41
        int64_t current_time = ::time(nullptr);
5796
41
        if (current_time < expiration) { // not expired
5797
0
            return 0;
5798
0
        }
5799
41
        ++num_expired;
5800
5801
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5802
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5803
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5804
5805
41
        std::unique_ptr<Transaction> txn;
5806
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5807
41
        if (err != TxnErrorCode::TXN_OK) {
5808
0
            LOG_WARNING("failed to recycle restore job")
5809
0
                    .tag("err", err)
5810
0
                    .tag("tablet id", tablet_id)
5811
0
                    .tag("instance_id", instance_id_)
5812
0
                    .tag("reason", "failed to create txn");
5813
0
            return -1;
5814
0
        }
5815
5816
41
        std::string val;
5817
41
        err = txn->get(k, &val);
5818
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5819
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5820
0
            return 0;
5821
0
        }
5822
41
        if (err != TxnErrorCode::TXN_OK) {
5823
0
            LOG_WARNING("failed to get kv");
5824
0
            return -1;
5825
0
        }
5826
41
        restore_job_pb.Clear();
5827
41
        if (!restore_job_pb.ParseFromString(val)) {
5828
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5829
0
            return -1;
5830
0
        }
5831
5832
        // PREPARED or COMMITTED, change state to DROPPED and return
5833
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5834
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5835
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5836
0
            restore_job_pb.set_need_recycle_data(true);
5837
0
            txn->put(k, restore_job_pb.SerializeAsString());
5838
0
            err = txn->commit();
5839
0
            if (err != TxnErrorCode::TXN_OK) {
5840
0
                LOG_WARNING("failed to commit txn: {}", err);
5841
0
                return -1;
5842
0
            }
5843
0
            num_aborted++;
5844
0
            return 0;
5845
0
        }
5846
5847
        // Change state to RECYCLING
5848
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5849
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5850
21
            txn->put(k, restore_job_pb.SerializeAsString());
5851
21
            err = txn->commit();
5852
21
            if (err != TxnErrorCode::TXN_OK) {
5853
0
                LOG_WARNING("failed to commit txn: {}", err);
5854
0
                return -1;
5855
0
            }
5856
21
            return 0;
5857
21
        }
5858
5859
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5860
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5861
5862
        // Recycle all data associated with the restore job.
5863
        // This includes rowsets, segments, and related resources.
5864
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5865
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5866
0
            LOG_WARNING("failed to recycle tablet")
5867
0
                    .tag("tablet_id", tablet_id)
5868
0
                    .tag("instance_id", instance_id_);
5869
0
            return -1;
5870
0
        }
5871
5872
        // delete all restore job rowset kv
5873
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5874
5875
20
        err = txn->commit();
5876
20
        if (err != TxnErrorCode::TXN_OK) {
5877
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5878
0
                    .tag("err", err)
5879
0
                    .tag("tablet id", tablet_id)
5880
0
                    .tag("instance_id", instance_id_)
5881
0
                    .tag("reason", "failed to commit txn");
5882
0
            return -1;
5883
0
        }
5884
5885
20
        metrics_context.total_recycled_num = ++num_recycled;
5886
20
        metrics_context.report();
5887
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5888
20
        restore_job_keys.push_back(k);
5889
5890
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5891
20
                  << " tablet_id=" << tablet_id;
5892
20
        return 0;
5893
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
5781
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5782
41
        ++num_scanned;
5783
41
        RestoreJobCloudPB restore_job_pb;
5784
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5785
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5786
0
            return -1;
5787
0
        }
5788
41
        int64_t expiration =
5789
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5790
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5791
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5792
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5793
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5794
0
                   << " state=" << restore_job_pb.state();
5795
41
        int64_t current_time = ::time(nullptr);
5796
41
        if (current_time < expiration) { // not expired
5797
0
            return 0;
5798
0
        }
5799
41
        ++num_expired;
5800
5801
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5802
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5803
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5804
5805
41
        std::unique_ptr<Transaction> txn;
5806
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5807
41
        if (err != TxnErrorCode::TXN_OK) {
5808
0
            LOG_WARNING("failed to recycle restore job")
5809
0
                    .tag("err", err)
5810
0
                    .tag("tablet id", tablet_id)
5811
0
                    .tag("instance_id", instance_id_)
5812
0
                    .tag("reason", "failed to create txn");
5813
0
            return -1;
5814
0
        }
5815
5816
41
        std::string val;
5817
41
        err = txn->get(k, &val);
5818
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5819
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5820
0
            return 0;
5821
0
        }
5822
41
        if (err != TxnErrorCode::TXN_OK) {
5823
0
            LOG_WARNING("failed to get kv");
5824
0
            return -1;
5825
0
        }
5826
41
        restore_job_pb.Clear();
5827
41
        if (!restore_job_pb.ParseFromString(val)) {
5828
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5829
0
            return -1;
5830
0
        }
5831
5832
        // PREPARED or COMMITTED, change state to DROPPED and return
5833
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5834
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5835
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5836
0
            restore_job_pb.set_need_recycle_data(true);
5837
0
            txn->put(k, restore_job_pb.SerializeAsString());
5838
0
            err = txn->commit();
5839
0
            if (err != TxnErrorCode::TXN_OK) {
5840
0
                LOG_WARNING("failed to commit txn: {}", err);
5841
0
                return -1;
5842
0
            }
5843
0
            num_aborted++;
5844
0
            return 0;
5845
0
        }
5846
5847
        // Change state to RECYCLING
5848
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5849
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5850
21
            txn->put(k, restore_job_pb.SerializeAsString());
5851
21
            err = txn->commit();
5852
21
            if (err != TxnErrorCode::TXN_OK) {
5853
0
                LOG_WARNING("failed to commit txn: {}", err);
5854
0
                return -1;
5855
0
            }
5856
21
            return 0;
5857
21
        }
5858
5859
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5860
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5861
5862
        // Recycle all data associated with the restore job.
5863
        // This includes rowsets, segments, and related resources.
5864
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5865
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5866
0
            LOG_WARNING("failed to recycle tablet")
5867
0
                    .tag("tablet_id", tablet_id)
5868
0
                    .tag("instance_id", instance_id_);
5869
0
            return -1;
5870
0
        }
5871
5872
        // delete all restore job rowset kv
5873
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5874
5875
20
        err = txn->commit();
5876
20
        if (err != TxnErrorCode::TXN_OK) {
5877
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5878
0
                    .tag("err", err)
5879
0
                    .tag("tablet id", tablet_id)
5880
0
                    .tag("instance_id", instance_id_)
5881
0
                    .tag("reason", "failed to commit txn");
5882
0
            return -1;
5883
0
        }
5884
5885
20
        metrics_context.total_recycled_num = ++num_recycled;
5886
20
        metrics_context.report();
5887
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5888
20
        restore_job_keys.push_back(k);
5889
5890
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5891
20
                  << " tablet_id=" << tablet_id;
5892
20
        return 0;
5893
20
    };
5894
5895
13
    auto loop_done = [&restore_job_keys, this]() -> int {
5896
3
        if (restore_job_keys.empty()) return 0;
5897
1
        DORIS_CLOUD_DEFER {
5898
1
            restore_job_keys.clear();
5899
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5897
1
        DORIS_CLOUD_DEFER {
5898
1
            restore_job_keys.clear();
5899
1
        };
5900
5901
1
        std::unique_ptr<Transaction> txn;
5902
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5903
1
        if (err != TxnErrorCode::TXN_OK) {
5904
0
            LOG_WARNING("failed to recycle restore job")
5905
0
                    .tag("err", err)
5906
0
                    .tag("instance_id", instance_id_)
5907
0
                    .tag("reason", "failed to create txn");
5908
0
            return -1;
5909
0
        }
5910
20
        for (auto& k : restore_job_keys) {
5911
20
            txn->remove(k);
5912
20
        }
5913
1
        err = txn->commit();
5914
1
        if (err != TxnErrorCode::TXN_OK) {
5915
0
            LOG_WARNING("failed to recycle restore job")
5916
0
                    .tag("err", err)
5917
0
                    .tag("instance_id", instance_id_)
5918
0
                    .tag("reason", "failed to commit txn");
5919
0
            return -1;
5920
0
        }
5921
1
        return 0;
5922
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
5895
3
    auto loop_done = [&restore_job_keys, this]() -> int {
5896
3
        if (restore_job_keys.empty()) return 0;
5897
1
        DORIS_CLOUD_DEFER {
5898
1
            restore_job_keys.clear();
5899
1
        };
5900
5901
1
        std::unique_ptr<Transaction> txn;
5902
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5903
1
        if (err != TxnErrorCode::TXN_OK) {
5904
0
            LOG_WARNING("failed to recycle restore job")
5905
0
                    .tag("err", err)
5906
0
                    .tag("instance_id", instance_id_)
5907
0
                    .tag("reason", "failed to create txn");
5908
0
            return -1;
5909
0
        }
5910
20
        for (auto& k : restore_job_keys) {
5911
20
            txn->remove(k);
5912
20
        }
5913
1
        err = txn->commit();
5914
1
        if (err != TxnErrorCode::TXN_OK) {
5915
0
            LOG_WARNING("failed to recycle restore job")
5916
0
                    .tag("err", err)
5917
0
                    .tag("instance_id", instance_id_)
5918
0
                    .tag("reason", "failed to commit txn");
5919
0
            return -1;
5920
0
        }
5921
1
        return 0;
5922
1
    };
5923
5924
13
    if (config::enable_recycler_stats_metrics) {
5925
0
        scan_and_statistics_restore_jobs();
5926
0
    }
5927
5928
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
5929
13
                            std::move(loop_done));
5930
13
}
5931
5932
11
int InstanceRecycler::recycle_versioned_rowsets() {
5933
11
    const std::string task_name = "recycle_rowsets";
5934
11
    int64_t num_scanned = 0;
5935
11
    int64_t num_expired = 0;
5936
11
    int64_t num_prepare = 0;
5937
11
    int64_t num_compacted = 0;
5938
11
    int64_t num_empty_rowset = 0;
5939
11
    size_t total_rowset_key_size = 0;
5940
11
    size_t total_rowset_value_size = 0;
5941
11
    size_t expired_rowset_size = 0;
5942
11
    std::atomic_long num_recycled = 0;
5943
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5944
5945
11
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5946
11
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5947
11
    std::string recyc_rs_key0;
5948
11
    std::string recyc_rs_key1;
5949
11
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5950
11
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5951
5952
11
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5953
5954
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5955
11
    register_recycle_task(task_name, start_time);
5956
5957
11
    DORIS_CLOUD_DEFER {
5958
11
        unregister_recycle_task(task_name);
5959
11
        int64_t cost =
5960
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5961
11
        metrics_context.finish_report();
5962
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5963
11
                .tag("instance_id", instance_id_)
5964
11
                .tag("num_scanned", num_scanned)
5965
11
                .tag("num_expired", num_expired)
5966
11
                .tag("num_recycled", num_recycled)
5967
11
                .tag("num_recycled.prepare", num_prepare)
5968
11
                .tag("num_recycled.compacted", num_compacted)
5969
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5970
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5971
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5972
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
5973
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
5957
11
    DORIS_CLOUD_DEFER {
5958
11
        unregister_recycle_task(task_name);
5959
11
        int64_t cost =
5960
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5961
11
        metrics_context.finish_report();
5962
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5963
11
                .tag("instance_id", instance_id_)
5964
11
                .tag("num_scanned", num_scanned)
5965
11
                .tag("num_expired", num_expired)
5966
11
                .tag("num_recycled", num_recycled)
5967
11
                .tag("num_recycled.prepare", num_prepare)
5968
11
                .tag("num_recycled.compacted", num_compacted)
5969
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5970
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5971
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5972
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
5973
11
    };
5974
5975
11
    std::vector<std::string> orphan_rowset_keys;
5976
5977
    // Store keys of rowset recycled by background workers
5978
11
    std::mutex async_recycled_rowset_keys_mutex;
5979
11
    std::vector<std::string> async_recycled_rowset_keys;
5980
11
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5981
11
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5982
11
    worker_pool->start();
5983
11
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5984
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5985
        // Try to delete rowset data in background thread
5986
400
        int ret = worker_pool->submit_with_timeout(
5987
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5988
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5989
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5990
400
                        return;
5991
400
                    }
5992
                    // The async recycled rowsets are staled format or has not been used,
5993
                    // so we don't need to check the rowset ref count key.
5994
0
                    std::vector<std::string> keys;
5995
0
                    {
5996
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5997
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5998
0
                        if (async_recycled_rowset_keys.size() > 100) {
5999
0
                            keys.swap(async_recycled_rowset_keys);
6000
0
                        }
6001
0
                    }
6002
0
                    if (keys.empty()) return;
6003
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6004
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6005
0
                                     << instance_id_;
6006
0
                    } else {
6007
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6008
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6009
0
                                           num_recycled, start_time);
6010
0
                    }
6011
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
5987
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5988
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5989
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5990
400
                        return;
5991
400
                    }
5992
                    // The async recycled rowsets are staled format or has not been used,
5993
                    // so we don't need to check the rowset ref count key.
5994
0
                    std::vector<std::string> keys;
5995
0
                    {
5996
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5997
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5998
0
                        if (async_recycled_rowset_keys.size() > 100) {
5999
0
                            keys.swap(async_recycled_rowset_keys);
6000
0
                        }
6001
0
                    }
6002
0
                    if (keys.empty()) return;
6003
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6004
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6005
0
                                     << instance_id_;
6006
0
                    } else {
6007
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6008
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6009
0
                                           num_recycled, start_time);
6010
0
                    }
6011
0
                },
6012
400
                0);
6013
400
        if (ret == 0) return 0;
6014
        // Submit task failed, delete rowset data in current thread
6015
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6016
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6017
0
            return -1;
6018
0
        }
6019
0
        orphan_rowset_keys.push_back(std::move(key));
6020
0
        return 0;
6021
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
5984
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5985
        // Try to delete rowset data in background thread
5986
400
        int ret = worker_pool->submit_with_timeout(
5987
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5988
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5989
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5990
400
                        return;
5991
400
                    }
5992
                    // The async recycled rowsets are staled format or has not been used,
5993
                    // so we don't need to check the rowset ref count key.
5994
400
                    std::vector<std::string> keys;
5995
400
                    {
5996
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5997
400
                        async_recycled_rowset_keys.push_back(std::move(key));
5998
400
                        if (async_recycled_rowset_keys.size() > 100) {
5999
400
                            keys.swap(async_recycled_rowset_keys);
6000
400
                        }
6001
400
                    }
6002
400
                    if (keys.empty()) return;
6003
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6004
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6005
400
                                     << instance_id_;
6006
400
                    } else {
6007
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6008
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6009
400
                                           num_recycled, start_time);
6010
400
                    }
6011
400
                },
6012
400
                0);
6013
400
        if (ret == 0) return 0;
6014
        // Submit task failed, delete rowset data in current thread
6015
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6016
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6017
0
            return -1;
6018
0
        }
6019
0
        orphan_rowset_keys.push_back(std::move(key));
6020
0
        return 0;
6021
0
    };
6022
6023
11
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6024
6025
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6026
2.01k
        ++num_scanned;
6027
2.01k
        total_rowset_key_size += k.size();
6028
2.01k
        total_rowset_value_size += v.size();
6029
2.01k
        RecycleRowsetPB rowset;
6030
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6031
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6032
0
            return -1;
6033
0
        }
6034
6035
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6036
6037
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6038
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6039
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6040
2.01k
        int64_t current_time = ::time(nullptr);
6041
2.01k
        if (current_time < final_expiration) { // not expired
6042
0
            return 0;
6043
0
        }
6044
2.01k
        ++num_expired;
6045
2.01k
        expired_rowset_size += v.size();
6046
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6047
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6048
                // in old version, keep this key-value pair and it needs to be checked manually
6049
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6050
0
                return -1;
6051
0
            }
6052
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6053
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6054
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6055
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6056
0
                orphan_rowset_keys.emplace_back(k);
6057
0
                return -1;
6058
0
            }
6059
            // decode rowset_id
6060
0
            auto k1 = k;
6061
0
            k1.remove_prefix(1);
6062
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6063
0
            decode_key(&k1, &out);
6064
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6065
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6066
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6067
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6068
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6069
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6070
0
                return -1;
6071
0
            }
6072
0
            return 0;
6073
0
        }
6074
        // TODO(plat1ko): check rowset not referenced
6075
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6076
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6077
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6078
0
                LOG_INFO("recycle rowset that has empty resource id");
6079
0
            } else {
6080
                // other situations, keep this key-value pair and it needs to be checked manually
6081
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6082
0
                return -1;
6083
0
            }
6084
0
        }
6085
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6086
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6087
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6088
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6089
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6090
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6091
2.01k
                  << " rowset_meta_size=" << v.size()
6092
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6093
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6094
            // unable to calculate file path, can only be deleted by rowset id prefix
6095
400
            num_prepare += 1;
6096
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6097
400
                                             rowset_meta->tablet_id(),
6098
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6099
0
                return -1;
6100
0
            }
6101
1.61k
        } else {
6102
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6103
1.61k
            worker_pool->submit(
6104
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6105
                        // The load & compact rowset keys are recycled during recycling operation logs.
6106
1.61k
                        RowsetDeleteTask task;
6107
1.61k
                        task.rowset_meta = rowset_meta;
6108
1.61k
                        task.recycle_rowset_key = k;
6109
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6110
1.59k
                            return;
6111
1.59k
                        }
6112
14
                        num_compacted += is_compacted;
6113
14
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6114
14
                        if (rowset_meta.num_segments() == 0) {
6115
0
                            ++num_empty_rowset;
6116
0
                        }
6117
14
                    });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlvE_clEv
Line
Count
Source
6104
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6105
                        // The load & compact rowset keys are recycled during recycling operation logs.
6106
1.61k
                        RowsetDeleteTask task;
6107
1.61k
                        task.rowset_meta = rowset_meta;
6108
1.61k
                        task.recycle_rowset_key = k;
6109
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6110
1.59k
                            return;
6111
1.59k
                        }
6112
14
                        num_compacted += is_compacted;
6113
14
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6114
14
                        if (rowset_meta.num_segments() == 0) {
6115
0
                            ++num_empty_rowset;
6116
0
                        }
6117
14
                    });
6118
1.61k
        }
6119
2.01k
        return 0;
6120
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
6025
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6026
2.01k
        ++num_scanned;
6027
2.01k
        total_rowset_key_size += k.size();
6028
2.01k
        total_rowset_value_size += v.size();
6029
2.01k
        RecycleRowsetPB rowset;
6030
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6031
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6032
0
            return -1;
6033
0
        }
6034
6035
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6036
6037
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6038
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6039
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6040
2.01k
        int64_t current_time = ::time(nullptr);
6041
2.01k
        if (current_time < final_expiration) { // not expired
6042
0
            return 0;
6043
0
        }
6044
2.01k
        ++num_expired;
6045
2.01k
        expired_rowset_size += v.size();
6046
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6047
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6048
                // in old version, keep this key-value pair and it needs to be checked manually
6049
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6050
0
                return -1;
6051
0
            }
6052
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6053
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6054
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6055
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6056
0
                orphan_rowset_keys.emplace_back(k);
6057
0
                return -1;
6058
0
            }
6059
            // decode rowset_id
6060
0
            auto k1 = k;
6061
0
            k1.remove_prefix(1);
6062
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6063
0
            decode_key(&k1, &out);
6064
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6065
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6066
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6067
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6068
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6069
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6070
0
                return -1;
6071
0
            }
6072
0
            return 0;
6073
0
        }
6074
        // TODO(plat1ko): check rowset not referenced
6075
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6076
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6077
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6078
0
                LOG_INFO("recycle rowset that has empty resource id");
6079
0
            } else {
6080
                // other situations, keep this key-value pair and it needs to be checked manually
6081
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6082
0
                return -1;
6083
0
            }
6084
0
        }
6085
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6086
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6087
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6088
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6089
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6090
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6091
2.01k
                  << " rowset_meta_size=" << v.size()
6092
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6093
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6094
            // unable to calculate file path, can only be deleted by rowset id prefix
6095
400
            num_prepare += 1;
6096
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6097
400
                                             rowset_meta->tablet_id(),
6098
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6099
0
                return -1;
6100
0
            }
6101
1.61k
        } else {
6102
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6103
1.61k
            worker_pool->submit(
6104
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6105
                        // The load & compact rowset keys are recycled during recycling operation logs.
6106
1.61k
                        RowsetDeleteTask task;
6107
1.61k
                        task.rowset_meta = rowset_meta;
6108
1.61k
                        task.recycle_rowset_key = k;
6109
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6110
1.61k
                            return;
6111
1.61k
                        }
6112
1.61k
                        num_compacted += is_compacted;
6113
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6114
1.61k
                        if (rowset_meta.num_segments() == 0) {
6115
1.61k
                            ++num_empty_rowset;
6116
1.61k
                        }
6117
1.61k
                    });
6118
1.61k
        }
6119
2.01k
        return 0;
6120
2.01k
    };
6121
6122
11
    if (config::enable_recycler_stats_metrics) {
6123
0
        scan_and_statistics_rowsets();
6124
0
    }
6125
6126
11
    auto loop_done = [&]() -> int {
6127
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6128
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6129
0
        }
6130
6
        orphan_rowset_keys.clear();
6131
6
        return 0;
6132
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
Line
Count
Source
6126
6
    auto loop_done = [&]() -> int {
6127
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6128
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6129
0
        }
6130
6
        orphan_rowset_keys.clear();
6131
6
        return 0;
6132
6
    };
6133
6134
    // recycle_func and loop_done for scan and recycle
6135
11
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
6136
11
                               std::move(loop_done));
6137
6138
11
    worker_pool->stop();
6139
6140
11
    if (!async_recycled_rowset_keys.empty()) {
6141
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
6142
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6143
0
            return -1;
6144
0
        } else {
6145
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
6146
0
        }
6147
0
    }
6148
6149
    // Report final metrics after all concurrent tasks completed
6150
11
    segment_metrics_context_.report();
6151
11
    metrics_context.report();
6152
6153
11
    return ret;
6154
11
}
6155
6156
1.61k
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task) {
6157
1.61k
    constexpr int MAX_RETRY = 10;
6158
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
6159
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
6160
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
6161
1.61k
    std::string_view reference_instance_id = instance_id_;
6162
1.61k
    if (rowset_meta.has_reference_instance_id()) {
6163
8
        reference_instance_id = rowset_meta.reference_instance_id();
6164
8
    }
6165
6166
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
6167
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
6168
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
6169
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
6170
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
6171
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
6172
1.61k
        std::unique_ptr<Transaction> txn;
6173
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6174
1.61k
        if (err != TxnErrorCode::TXN_OK) {
6175
0
            LOG_WARNING("failed to create txn").tag("err", err);
6176
0
            return -1;
6177
0
        }
6178
6179
1.61k
        std::string rowset_ref_count_key =
6180
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
6181
1.61k
        int64_t ref_count = 0;
6182
1.61k
        {
6183
1.61k
            std::string value;
6184
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
6185
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6186
                // This is the old version rowset, we could recycle it directly.
6187
1.60k
                ref_count = 1;
6188
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
6189
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
6190
0
                return -1;
6191
11
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
6192
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
6193
0
                return -1;
6194
0
            }
6195
1.61k
        }
6196
6197
1.61k
        if (ref_count == 1) {
6198
            // It would not be added since it is recycling.
6199
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
6200
1.60k
                LOG_WARNING("failed to delete rowset data");
6201
1.60k
                return -1;
6202
1.60k
            }
6203
6204
            // Reset the transaction to avoid timeout.
6205
10
            err = txn_kv_->create_txn(&txn);
6206
10
            if (err != TxnErrorCode::TXN_OK) {
6207
0
                LOG_WARNING("failed to create txn").tag("err", err);
6208
0
                return -1;
6209
0
            }
6210
10
            txn->remove(rowset_ref_count_key);
6211
10
            LOG_INFO("delete rowset data ref count key")
6212
10
                    .tag("txn_id", rowset_meta.txn_id())
6213
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6214
6215
10
            std::string dbm_start_key =
6216
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
6217
10
            std::string dbm_end_key = meta_delete_bitmap_key(
6218
10
                    {reference_instance_id, tablet_id, rowset_id,
6219
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
6220
10
            txn->remove(dbm_start_key, dbm_end_key);
6221
10
            LOG_INFO("remove delete bitmap kv")
6222
10
                    .tag("begin", hex(dbm_start_key))
6223
10
                    .tag("end", hex(dbm_end_key));
6224
6225
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
6226
10
                    {reference_instance_id, tablet_id, rowset_id});
6227
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
6228
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
6229
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
6230
10
            LOG_INFO("remove versioned delete bitmap kv")
6231
10
                    .tag("begin", hex(versioned_dbm_start_key))
6232
10
                    .tag("end", hex(versioned_dbm_end_key));
6233
10
        } else {
6234
            // Decrease the rowset ref count.
6235
            //
6236
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
6237
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
6238
3
            txn->atomic_add(rowset_ref_count_key, -1);
6239
3
            LOG_INFO("decrease rowset data ref count")
6240
3
                    .tag("txn_id", rowset_meta.txn_id())
6241
3
                    .tag("ref_count", ref_count - 1)
6242
3
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6243
3
        }
6244
6245
13
        if (!task.versioned_rowset_key.empty()) {
6246
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
6247
0
                                                          task.versionstamp);
6248
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
6249
0
        }
6250
6251
13
        if (!task.non_versioned_rowset_key.empty()) {
6252
0
            txn->remove(task.non_versioned_rowset_key);
6253
0
            LOG_INFO("remove non versioned rowset key")
6254
0
                    .tag("key", hex(task.non_versioned_rowset_key));
6255
0
        }
6256
6257
        // empty when recycle ref rowsets for deleted instance
6258
13
        if (!task.recycle_rowset_key.empty()) {
6259
13
            txn->remove(task.recycle_rowset_key);
6260
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
6261
13
        }
6262
6263
13
        err = txn->commit();
6264
13
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
6265
            // The rowset ref count key has been changed, we need to retry.
6266
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
6267
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
6268
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
6269
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6270
0
            continue;
6271
13
        } else if (err != TxnErrorCode::TXN_OK) {
6272
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
6273
0
            return -1;
6274
0
        }
6275
13
        LOG_INFO("recycle rowset meta and data success");
6276
13
        return 0;
6277
13
    }
6278
0
    LOG_WARNING("failed to recycle rowset meta and data after retry")
6279
0
            .tag("tablet_id", tablet_id)
6280
0
            .tag("rowset_id", rowset_id)
6281
0
            .tag("retry", MAX_RETRY);
6282
0
    return -1;
6283
1.61k
}
6284
6285
35
int InstanceRecycler::recycle_tmp_rowsets() {
6286
35
    const std::string task_name = "recycle_tmp_rowsets";
6287
35
    int64_t num_scanned = 0;
6288
35
    int64_t num_expired = 0;
6289
35
    std::atomic_long num_recycled = 0;
6290
35
    size_t expired_rowset_size = 0;
6291
35
    size_t total_rowset_key_size = 0;
6292
35
    size_t total_rowset_value_size = 0;
6293
35
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6294
6295
35
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
6296
35
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
6297
35
    std::string tmp_rs_key0;
6298
35
    std::string tmp_rs_key1;
6299
35
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
6300
35
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
6301
6302
35
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
6303
6304
35
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6305
35
    register_recycle_task(task_name, start_time);
6306
6307
35
    DORIS_CLOUD_DEFER {
6308
35
        unregister_recycle_task(task_name);
6309
35
        int64_t cost =
6310
35
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6311
35
        metrics_context.finish_report();
6312
35
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6313
35
                .tag("instance_id", instance_id_)
6314
35
                .tag("num_scanned", num_scanned)
6315
35
                .tag("num_expired", num_expired)
6316
35
                .tag("num_recycled", num_recycled)
6317
35
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6318
35
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6319
35
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6320
35
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6307
12
    DORIS_CLOUD_DEFER {
6308
12
        unregister_recycle_task(task_name);
6309
12
        int64_t cost =
6310
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6311
12
        metrics_context.finish_report();
6312
12
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6313
12
                .tag("instance_id", instance_id_)
6314
12
                .tag("num_scanned", num_scanned)
6315
12
                .tag("num_expired", num_expired)
6316
12
                .tag("num_recycled", num_recycled)
6317
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6318
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6319
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6320
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6307
23
    DORIS_CLOUD_DEFER {
6308
23
        unregister_recycle_task(task_name);
6309
23
        int64_t cost =
6310
23
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6311
23
        metrics_context.finish_report();
6312
23
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6313
23
                .tag("instance_id", instance_id_)
6314
23
                .tag("num_scanned", num_scanned)
6315
23
                .tag("num_expired", num_expired)
6316
23
                .tag("num_recycled", num_recycled)
6317
23
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6318
23
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6319
23
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6320
23
    };
6321
6322
    // Elements in `tmp_rowset_keys` has the same lifetime as `it`
6323
6324
35
    std::vector<std::string> tmp_rowset_keys;
6325
35
    std::vector<std::string> tmp_rowset_ref_count_keys;
6326
35
    std::vector<std::string> tmp_rowset_keys_to_mark_recycled;
6327
35
    std::vector<std::string> tmp_rowset_keys_to_abort;
6328
6329
    // rowset_id -> rowset_meta
6330
    // store tmp_rowset id and meta for statistics rs size when delete
6331
35
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
6332
35
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6333
35
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
6334
35
    worker_pool->start();
6335
6336
35
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6337
6338
35
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &tmp_rowsets,
6339
35
                             &expired_rowset_size, &total_rowset_key_size, &total_rowset_value_size,
6340
35
                             &earlest_ts, &tmp_rowset_ref_count_keys,
6341
35
                             &tmp_rowset_keys_to_mark_recycled, &tmp_rowset_keys_to_abort, this,
6342
53.0k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
6343
53.0k
        ++num_scanned;
6344
53.0k
        total_rowset_key_size += k.size();
6345
53.0k
        total_rowset_value_size += v.size();
6346
53.0k
        doris::RowsetMetaCloudPB rowset;
6347
53.0k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6348
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6349
0
            return -1;
6350
0
        }
6351
53.0k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6352
53.0k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6353
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6354
0
                   << " txn_expiration=" << rowset.txn_expiration()
6355
0
                   << " rowset_creation_time=" << rowset.creation_time();
6356
53.0k
        int64_t current_time = ::time(nullptr);
6357
53.0k
        if (current_time < expiration) { // not expired
6358
0
            return 0;
6359
0
        }
6360
6361
53.0k
        if (config::enable_mark_delete_rowset_before_recycle) {
6362
16
            if (need_mark_rowset_as_recycled(rowset)) {
6363
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6364
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6365
9
                             "at next turn, instance_id="
6366
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6367
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6368
9
                return 0;
6369
9
            }
6370
16
        }
6371
6372
53.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6373
7
            if (make_deferred_abort_task(rowset).has_value()) {
6374
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6375
3
                             "instance_id="
6376
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6377
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6378
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6379
3
            }
6380
7
        }
6381
6382
53.0k
        ++num_expired;
6383
53.0k
        expired_rowset_size += v.size();
6384
53.0k
        if (!rowset.has_resource_id()) {
6385
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6386
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6387
0
                return -1;
6388
0
            }
6389
            // might be a delete pred rowset
6390
0
            tmp_rowset_keys.emplace_back(k);
6391
0
            return 0;
6392
0
        }
6393
        // TODO(plat1ko): check rowset not referenced
6394
53.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6395
53.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6396
53.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6397
53.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6398
53.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6399
53.0k
                  << " num_expired=" << num_expired
6400
53.0k
                  << " task_type=" << metrics_context.operation_type;
6401
6402
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6403
        // Remove the rowset ref count key directly since it has not been used.
6404
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6405
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6406
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6407
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6408
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6409
6410
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6411
53.0k
        return 0;
6412
53.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6342
16
                             &metrics_context](std::string_view k, std::string_view v) -> int {
6343
16
        ++num_scanned;
6344
16
        total_rowset_key_size += k.size();
6345
16
        total_rowset_value_size += v.size();
6346
16
        doris::RowsetMetaCloudPB rowset;
6347
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6348
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6349
0
            return -1;
6350
0
        }
6351
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6352
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6353
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6354
0
                   << " txn_expiration=" << rowset.txn_expiration()
6355
0
                   << " rowset_creation_time=" << rowset.creation_time();
6356
16
        int64_t current_time = ::time(nullptr);
6357
16
        if (current_time < expiration) { // not expired
6358
0
            return 0;
6359
0
        }
6360
6361
16
        if (config::enable_mark_delete_rowset_before_recycle) {
6362
16
            if (need_mark_rowset_as_recycled(rowset)) {
6363
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6364
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6365
9
                             "at next turn, instance_id="
6366
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6367
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6368
9
                return 0;
6369
9
            }
6370
16
        }
6371
6372
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6373
7
            if (make_deferred_abort_task(rowset).has_value()) {
6374
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6375
3
                             "instance_id="
6376
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6377
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6378
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6379
3
            }
6380
7
        }
6381
6382
7
        ++num_expired;
6383
7
        expired_rowset_size += v.size();
6384
7
        if (!rowset.has_resource_id()) {
6385
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6386
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6387
0
                return -1;
6388
0
            }
6389
            // might be a delete pred rowset
6390
0
            tmp_rowset_keys.emplace_back(k);
6391
0
            return 0;
6392
0
        }
6393
        // TODO(plat1ko): check rowset not referenced
6394
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6395
7
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6396
7
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6397
7
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6398
7
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6399
7
                  << " num_expired=" << num_expired
6400
7
                  << " task_type=" << metrics_context.operation_type;
6401
6402
7
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6403
        // Remove the rowset ref count key directly since it has not been used.
6404
7
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6405
7
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6406
7
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6407
7
                  << "key=" << hex(rowset_ref_count_key);
6408
7
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6409
6410
7
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6411
7
        return 0;
6412
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6342
53.0k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
6343
53.0k
        ++num_scanned;
6344
53.0k
        total_rowset_key_size += k.size();
6345
53.0k
        total_rowset_value_size += v.size();
6346
53.0k
        doris::RowsetMetaCloudPB rowset;
6347
53.0k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6348
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6349
0
            return -1;
6350
0
        }
6351
53.0k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6352
53.0k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6353
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6354
0
                   << " txn_expiration=" << rowset.txn_expiration()
6355
0
                   << " rowset_creation_time=" << rowset.creation_time();
6356
53.0k
        int64_t current_time = ::time(nullptr);
6357
53.0k
        if (current_time < expiration) { // not expired
6358
0
            return 0;
6359
0
        }
6360
6361
53.0k
        if (config::enable_mark_delete_rowset_before_recycle) {
6362
0
            if (need_mark_rowset_as_recycled(rowset)) {
6363
0
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6364
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6365
0
                             "at next turn, instance_id="
6366
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6367
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6368
0
                return 0;
6369
0
            }
6370
0
        }
6371
6372
53.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6373
0
            if (make_deferred_abort_task(rowset).has_value()) {
6374
0
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6375
0
                             "instance_id="
6376
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6377
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6378
0
                tmp_rowset_keys_to_abort.emplace_back(k);
6379
0
            }
6380
0
        }
6381
6382
53.0k
        ++num_expired;
6383
53.0k
        expired_rowset_size += v.size();
6384
53.0k
        if (!rowset.has_resource_id()) {
6385
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6386
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6387
0
                return -1;
6388
0
            }
6389
            // might be a delete pred rowset
6390
0
            tmp_rowset_keys.emplace_back(k);
6391
0
            return 0;
6392
0
        }
6393
        // TODO(plat1ko): check rowset not referenced
6394
53.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6395
53.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6396
53.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6397
53.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6398
53.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6399
53.0k
                  << " num_expired=" << num_expired
6400
53.0k
                  << " task_type=" << metrics_context.operation_type;
6401
6402
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6403
        // Remove the rowset ref count key directly since it has not been used.
6404
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6405
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6406
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6407
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6408
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6409
6410
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6411
53.0k
        return 0;
6412
53.0k
    };
6413
6414
    // TODO bacth delete
6415
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6416
51.0k
        std::string dbm_start_key =
6417
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
6418
51.0k
        std::string dbm_end_key = dbm_start_key;
6419
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
6420
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
6421
51.0k
        if (ret != 0) {
6422
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6423
0
                         << instance_id_ << ", tablet_id=" << tablet_id
6424
0
                         << ", rowset_id=" << rowset_id;
6425
0
        }
6426
51.0k
        return ret;
6427
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6415
7
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6416
7
        std::string dbm_start_key =
6417
7
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
6418
7
        std::string dbm_end_key = dbm_start_key;
6419
7
        encode_int64(INT64_MAX, &dbm_end_key);
6420
7
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
6421
7
        if (ret != 0) {
6422
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6423
0
                         << instance_id_ << ", tablet_id=" << tablet_id
6424
0
                         << ", rowset_id=" << rowset_id;
6425
0
        }
6426
7
        return ret;
6427
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6415
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6416
51.0k
        std::string dbm_start_key =
6417
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
6418
51.0k
        std::string dbm_end_key = dbm_start_key;
6419
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
6420
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
6421
51.0k
        if (ret != 0) {
6422
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6423
0
                         << instance_id_ << ", tablet_id=" << tablet_id
6424
0
                         << ", rowset_id=" << rowset_id;
6425
0
        }
6426
51.0k
        return ret;
6427
51.0k
    };
6428
6429
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6430
51.0k
        auto delete_bitmap_start =
6431
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
6432
51.0k
        auto delete_bitmap_end =
6433
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
6434
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
6435
51.0k
        if (ret != 0) {
6436
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
6437
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
6438
0
        }
6439
51.0k
        return ret;
6440
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6429
7
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6430
7
        auto delete_bitmap_start =
6431
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
6432
7
        auto delete_bitmap_end =
6433
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
6434
7
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
6435
7
        if (ret != 0) {
6436
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
6437
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
6438
0
        }
6439
7
        return ret;
6440
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6429
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6430
51.0k
        auto delete_bitmap_start =
6431
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
6432
51.0k
        auto delete_bitmap_end =
6433
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
6434
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
6435
51.0k
        if (ret != 0) {
6436
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
6437
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
6438
0
        }
6439
51.0k
        return ret;
6440
51.0k
    };
6441
6442
35
    auto loop_done = [&]() -> int {
6443
22
        std::vector<std::string> tmp_rowset_keys_to_delete;
6444
22
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6445
22
        std::vector<std::string> mark_keys_to_process;
6446
22
        std::vector<std::string> abort_keys_to_process;
6447
22
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6448
22
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6449
22
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6450
22
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6451
22
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6452
22
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6453
22
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6454
22
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6455
22
                             tmp_rowset_ref_count_keys_to_delete =
6456
22
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6457
22
                             mark_keys_to_process = std::move(mark_keys_to_process),
6458
22
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6459
22
            if (!mark_keys_to_process.empty() &&
6460
22
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6461
7
                                                                  mark_keys_to_process) != 0) {
6462
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6463
0
                             << instance_id_;
6464
0
                return;
6465
0
            }
6466
22
            if (!abort_keys_to_process.empty() &&
6467
22
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6468
3
                                                                      false) != 0) {
6469
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6470
0
                             << instance_id_;
6471
0
                return;
6472
0
            }
6473
22
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6474
22
                                   metrics_context) != 0) {
6475
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6476
2
                return;
6477
2
            }
6478
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6479
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6480
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6481
0
                                 << rs.ShortDebugString();
6482
0
                    return;
6483
0
                }
6484
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6485
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6486
0
                                 << rs.ShortDebugString();
6487
0
                    return;
6488
0
                }
6489
51.0k
            }
6490
20
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6491
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6492
0
                return;
6493
0
            }
6494
20
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6495
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6496
0
                return;
6497
0
            }
6498
20
            num_recycled += tmp_rowset_keys_to_delete.size();
6499
20
            return;
6500
20
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
6458
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6459
12
            if (!mark_keys_to_process.empty() &&
6460
12
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6461
7
                                                                  mark_keys_to_process) != 0) {
6462
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6463
0
                             << instance_id_;
6464
0
                return;
6465
0
            }
6466
12
            if (!abort_keys_to_process.empty() &&
6467
12
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6468
3
                                                                      false) != 0) {
6469
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6470
0
                             << instance_id_;
6471
0
                return;
6472
0
            }
6473
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6474
12
                                   metrics_context) != 0) {
6475
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6476
0
                return;
6477
0
            }
6478
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6479
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6480
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6481
0
                                 << rs.ShortDebugString();
6482
0
                    return;
6483
0
                }
6484
7
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6485
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6486
0
                                 << rs.ShortDebugString();
6487
0
                    return;
6488
0
                }
6489
7
            }
6490
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6491
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6492
0
                return;
6493
0
            }
6494
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6495
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6496
0
                return;
6497
0
            }
6498
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6499
12
            return;
6500
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
6458
10
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6459
10
            if (!mark_keys_to_process.empty() &&
6460
10
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6461
0
                                                                  mark_keys_to_process) != 0) {
6462
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6463
0
                             << instance_id_;
6464
0
                return;
6465
0
            }
6466
10
            if (!abort_keys_to_process.empty() &&
6467
10
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6468
0
                                                                      false) != 0) {
6469
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6470
0
                             << instance_id_;
6471
0
                return;
6472
0
            }
6473
10
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6474
10
                                   metrics_context) != 0) {
6475
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6476
2
                return;
6477
2
            }
6478
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6479
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6480
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6481
0
                                 << rs.ShortDebugString();
6482
0
                    return;
6483
0
                }
6484
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6485
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6486
0
                                 << rs.ShortDebugString();
6487
0
                    return;
6488
0
                }
6489
51.0k
            }
6490
8
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6491
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6492
0
                return;
6493
0
            }
6494
8
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6495
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6496
0
                return;
6497
0
            }
6498
8
            num_recycled += tmp_rowset_keys_to_delete.size();
6499
8
            return;
6500
8
        });
6501
22
        return 0;
6502
22
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEv
Line
Count
Source
6442
12
    auto loop_done = [&]() -> int {
6443
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6444
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6445
12
        std::vector<std::string> mark_keys_to_process;
6446
12
        std::vector<std::string> abort_keys_to_process;
6447
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6448
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6449
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6450
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6451
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6452
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6453
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6454
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6455
12
                             tmp_rowset_ref_count_keys_to_delete =
6456
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6457
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6458
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6459
12
            if (!mark_keys_to_process.empty() &&
6460
12
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6461
12
                                                                  mark_keys_to_process) != 0) {
6462
12
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6463
12
                             << instance_id_;
6464
12
                return;
6465
12
            }
6466
12
            if (!abort_keys_to_process.empty() &&
6467
12
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6468
12
                                                                      false) != 0) {
6469
12
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6470
12
                             << instance_id_;
6471
12
                return;
6472
12
            }
6473
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6474
12
                                   metrics_context) != 0) {
6475
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6476
12
                return;
6477
12
            }
6478
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6479
12
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6480
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6481
12
                                 << rs.ShortDebugString();
6482
12
                    return;
6483
12
                }
6484
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6485
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6486
12
                                 << rs.ShortDebugString();
6487
12
                    return;
6488
12
                }
6489
12
            }
6490
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6491
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6492
12
                return;
6493
12
            }
6494
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6495
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6496
12
                return;
6497
12
            }
6498
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6499
12
            return;
6500
12
        });
6501
12
        return 0;
6502
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEv
Line
Count
Source
6442
10
    auto loop_done = [&]() -> int {
6443
10
        std::vector<std::string> tmp_rowset_keys_to_delete;
6444
10
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6445
10
        std::vector<std::string> mark_keys_to_process;
6446
10
        std::vector<std::string> abort_keys_to_process;
6447
10
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6448
10
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6449
10
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6450
10
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6451
10
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6452
10
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6453
10
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6454
10
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6455
10
                             tmp_rowset_ref_count_keys_to_delete =
6456
10
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6457
10
                             mark_keys_to_process = std::move(mark_keys_to_process),
6458
10
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6459
10
            if (!mark_keys_to_process.empty() &&
6460
10
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6461
10
                                                                  mark_keys_to_process) != 0) {
6462
10
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6463
10
                             << instance_id_;
6464
10
                return;
6465
10
            }
6466
10
            if (!abort_keys_to_process.empty() &&
6467
10
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6468
10
                                                                      false) != 0) {
6469
10
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6470
10
                             << instance_id_;
6471
10
                return;
6472
10
            }
6473
10
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6474
10
                                   metrics_context) != 0) {
6475
10
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6476
10
                return;
6477
10
            }
6478
10
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6479
10
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6480
10
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6481
10
                                 << rs.ShortDebugString();
6482
10
                    return;
6483
10
                }
6484
10
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6485
10
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6486
10
                                 << rs.ShortDebugString();
6487
10
                    return;
6488
10
                }
6489
10
            }
6490
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6491
10
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6492
10
                return;
6493
10
            }
6494
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6495
10
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6496
10
                return;
6497
10
            }
6498
10
            num_recycled += tmp_rowset_keys_to_delete.size();
6499
10
            return;
6500
10
        });
6501
10
        return 0;
6502
10
    };
6503
6504
35
    if (config::enable_recycler_stats_metrics) {
6505
0
        scan_and_statistics_tmp_rowsets();
6506
0
    }
6507
    // recycle_func and loop_done for scan and recycle
6508
35
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
6509
35
                               std::move(loop_done));
6510
6511
35
    worker_pool->stop();
6512
6513
    // Report final metrics after all concurrent tasks completed
6514
35
    segment_metrics_context_.report();
6515
35
    metrics_context.report();
6516
6517
35
    return ret;
6518
35
}
6519
6520
int InstanceRecycler::scan_and_recycle(
6521
        std::string begin, std::string_view end,
6522
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
6523
324
        std::function<int()> loop_done, std::function<bool(std::string*)> next_begin_getter) {
6524
324
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
6525
324
    int ret = 0;
6526
324
    int64_t cnt = 0;
6527
324
    int get_range_retried = 0;
6528
324
    std::string err;
6529
324
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6530
324
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6531
324
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6532
324
                  << " ret=" << ret << " err=" << err;
6533
324
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6529
36
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6530
36
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6531
36
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6532
36
                  << " ret=" << ret << " err=" << err;
6533
36
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6529
288
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6530
288
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6531
288
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6532
288
                  << " ret=" << ret << " err=" << err;
6533
288
    };
6534
6535
324
    std::unique_ptr<RangeGetIterator> it;
6536
502
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
6537
359
        if (get_range_retried > 1000) {
6538
0
            err = "txn_get exceeds max retry(1000), may not scan all keys";
6539
0
            ret = -3;
6540
0
            return ret;
6541
0
        }
6542
359
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
6543
359
        if (get_ret != 0) { // txn kv may complain "Request for future version"
6544
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
6545
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
6546
0
                         << " get_range_retried=" << get_range_retried;
6547
0
            ++get_range_retried;
6548
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6549
0
            continue; // try again
6550
0
        }
6551
359
        if (!it->has_next()) {
6552
181
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
6553
181
            break; // scan finished
6554
181
        }
6555
178
        bool begin_updated = false;
6556
178
        LOG(INFO) << "scan_and_recycle iterator key_range=[" << hex(begin) << "," << hex(end)
6557
178
                  << ") iterator->size()=" << it->size();
6558
97.6k
        while (it->has_next()) {
6559
97.4k
            ++cnt;
6560
            // recycle corresponding resources
6561
97.4k
            auto [k, v] = it->next();
6562
97.4k
            if (!it->has_next()) {
6563
172
                begin = k;
6564
172
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
6565
172
            }
6566
            // FIXME(gavin): if we want to continue scanning, the recycle_func should not return non-zero
6567
97.4k
            if (recycle_func(k, v) != 0) {
6568
4.00k
                err = "recycle_func error";
6569
4.00k
                ret = -1;
6570
4.00k
            }
6571
97.4k
            if (next_begin_getter) {
6572
4.05k
                std::string next_begin;
6573
4.05k
                if (next_begin_getter(&next_begin)) {
6574
7
                    if (next_begin > k) {
6575
7
                        begin = std::move(next_begin);
6576
7
                        begin_updated = true;
6577
7
                        VLOG_DEBUG << "scan_and_recycle updates begin to " << hex(begin)
6578
0
                                   << " after key=" << hex(k);
6579
7
                        break;
6580
7
                    }
6581
0
                    LOG_WARNING("ignore invalid next begin in scan_and_recycle")
6582
0
                            .tag("next_begin", hex(next_begin))
6583
0
                            .tag("current_key", hex(k));
6584
0
                }
6585
4.05k
            }
6586
97.4k
        }
6587
178
        if (!begin_updated) {
6588
171
            begin.push_back('\x00'); // Update to next smallest key for iteration
6589
171
        } else {
6590
7
            it.reset();
6591
7
        }
6592
6593
        // FIXME(gavin): if we want to continue scanning, the loop_done should not return non-zero
6594
        // if we want to continue scanning, the recycle_func should not return non-zero
6595
178
        if (loop_done && loop_done() != 0) {
6596
5
            err = "loop_done error";
6597
5
            ret = -1;
6598
5
        }
6599
178
    }
6600
324
    return ret;
6601
324
}
6602
6603
19
int InstanceRecycler::abort_timeout_txn() {
6604
19
    const std::string task_name = "abort_timeout_txn";
6605
19
    int64_t num_scanned = 0;
6606
19
    int64_t num_timeout = 0;
6607
19
    int64_t num_abort = 0;
6608
19
    int64_t num_advance = 0;
6609
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6610
6611
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6612
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6613
19
    std::string begin_txn_running_key;
6614
19
    std::string end_txn_running_key;
6615
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6616
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6617
6618
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
6619
6620
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6621
19
    register_recycle_task(task_name, start_time);
6622
6623
19
    DORIS_CLOUD_DEFER {
6624
19
        unregister_recycle_task(task_name);
6625
19
        int64_t cost =
6626
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6627
19
        metrics_context.finish_report();
6628
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6629
19
                .tag("instance_id", instance_id_)
6630
19
                .tag("num_scanned", num_scanned)
6631
19
                .tag("num_timeout", num_timeout)
6632
19
                .tag("num_abort", num_abort)
6633
19
                .tag("num_advance", num_advance);
6634
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6623
3
    DORIS_CLOUD_DEFER {
6624
3
        unregister_recycle_task(task_name);
6625
3
        int64_t cost =
6626
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6627
3
        metrics_context.finish_report();
6628
3
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6629
3
                .tag("instance_id", instance_id_)
6630
3
                .tag("num_scanned", num_scanned)
6631
3
                .tag("num_timeout", num_timeout)
6632
3
                .tag("num_abort", num_abort)
6633
3
                .tag("num_advance", num_advance);
6634
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6623
16
    DORIS_CLOUD_DEFER {
6624
16
        unregister_recycle_task(task_name);
6625
16
        int64_t cost =
6626
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6627
16
        metrics_context.finish_report();
6628
16
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6629
16
                .tag("instance_id", instance_id_)
6630
16
                .tag("num_scanned", num_scanned)
6631
16
                .tag("num_timeout", num_timeout)
6632
16
                .tag("num_abort", num_abort)
6633
16
                .tag("num_advance", num_advance);
6634
16
    };
6635
6636
19
    int64_t current_time =
6637
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6638
6639
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
6640
19
                                  &current_time, &metrics_context,
6641
19
                                  this](std::string_view k, std::string_view v) -> int {
6642
9
        ++num_scanned;
6643
6644
9
        std::unique_ptr<Transaction> txn;
6645
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6646
9
        if (err != TxnErrorCode::TXN_OK) {
6647
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6648
0
            return -1;
6649
0
        }
6650
9
        std::string_view k1 = k;
6651
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6652
9
        k1.remove_prefix(1); // Remove key space
6653
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6654
9
        if (decode_key(&k1, &out) != 0) {
6655
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6656
0
            return -1;
6657
0
        }
6658
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6659
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6660
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6661
        // Update txn_info
6662
9
        std::string txn_inf_key, txn_inf_val;
6663
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6664
9
        err = txn->get(txn_inf_key, &txn_inf_val);
6665
9
        if (err != TxnErrorCode::TXN_OK) {
6666
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6667
0
            return -1;
6668
0
        }
6669
9
        TxnInfoPB txn_info;
6670
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
6671
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6672
0
            return -1;
6673
0
        }
6674
6675
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6676
3
            txn.reset();
6677
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6678
3
            std::shared_ptr<TxnLazyCommitTask> task =
6679
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6680
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6681
3
            if (ret.first != MetaServiceCode::OK) {
6682
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6683
0
                             << "msg=" << ret.second;
6684
0
                return -1;
6685
0
            }
6686
3
            ++num_advance;
6687
3
            return 0;
6688
6
        } else {
6689
6
            TxnRunningPB txn_running_pb;
6690
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6691
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6692
0
                return -1;
6693
0
            }
6694
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6695
4
                return 0;
6696
4
            }
6697
2
            ++num_timeout;
6698
6699
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6700
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6701
2
            txn_info.set_finish_time(current_time);
6702
2
            txn_info.set_reason("timeout");
6703
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6704
2
            txn_inf_val.clear();
6705
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6706
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6707
0
                return -1;
6708
0
            }
6709
2
            txn->put(txn_inf_key, txn_inf_val);
6710
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6711
            // Put recycle txn key
6712
2
            std::string recyc_txn_key, recyc_txn_val;
6713
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6714
2
            RecycleTxnPB recycle_txn_pb;
6715
2
            recycle_txn_pb.set_creation_time(current_time);
6716
2
            recycle_txn_pb.set_label(txn_info.label());
6717
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6718
0
                LOG_WARNING("failed to serialize txn recycle info")
6719
0
                        .tag("key", hex(k))
6720
0
                        .tag("db_id", db_id)
6721
0
                        .tag("txn_id", txn_id);
6722
0
                return -1;
6723
0
            }
6724
2
            txn->put(recyc_txn_key, recyc_txn_val);
6725
            // Remove txn running key
6726
2
            txn->remove(k);
6727
2
            err = txn->commit();
6728
2
            if (err != TxnErrorCode::TXN_OK) {
6729
0
                LOG_WARNING("failed to commit txn err={}", err)
6730
0
                        .tag("key", hex(k))
6731
0
                        .tag("db_id", db_id)
6732
0
                        .tag("txn_id", txn_id);
6733
0
                return -1;
6734
0
            }
6735
2
            metrics_context.total_recycled_num = ++num_abort;
6736
2
            metrics_context.report();
6737
2
        }
6738
6739
2
        return 0;
6740
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6641
3
                                  this](std::string_view k, std::string_view v) -> int {
6642
3
        ++num_scanned;
6643
6644
3
        std::unique_ptr<Transaction> txn;
6645
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6646
3
        if (err != TxnErrorCode::TXN_OK) {
6647
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6648
0
            return -1;
6649
0
        }
6650
3
        std::string_view k1 = k;
6651
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6652
3
        k1.remove_prefix(1); // Remove key space
6653
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6654
3
        if (decode_key(&k1, &out) != 0) {
6655
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6656
0
            return -1;
6657
0
        }
6658
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6659
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6660
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6661
        // Update txn_info
6662
3
        std::string txn_inf_key, txn_inf_val;
6663
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6664
3
        err = txn->get(txn_inf_key, &txn_inf_val);
6665
3
        if (err != TxnErrorCode::TXN_OK) {
6666
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6667
0
            return -1;
6668
0
        }
6669
3
        TxnInfoPB txn_info;
6670
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
6671
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6672
0
            return -1;
6673
0
        }
6674
6675
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6676
3
            txn.reset();
6677
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6678
3
            std::shared_ptr<TxnLazyCommitTask> task =
6679
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6680
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6681
3
            if (ret.first != MetaServiceCode::OK) {
6682
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6683
0
                             << "msg=" << ret.second;
6684
0
                return -1;
6685
0
            }
6686
3
            ++num_advance;
6687
3
            return 0;
6688
3
        } else {
6689
0
            TxnRunningPB txn_running_pb;
6690
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6691
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6692
0
                return -1;
6693
0
            }
6694
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6695
0
                return 0;
6696
0
            }
6697
0
            ++num_timeout;
6698
6699
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6700
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6701
0
            txn_info.set_finish_time(current_time);
6702
0
            txn_info.set_reason("timeout");
6703
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6704
0
            txn_inf_val.clear();
6705
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6706
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6707
0
                return -1;
6708
0
            }
6709
0
            txn->put(txn_inf_key, txn_inf_val);
6710
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6711
            // Put recycle txn key
6712
0
            std::string recyc_txn_key, recyc_txn_val;
6713
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6714
0
            RecycleTxnPB recycle_txn_pb;
6715
0
            recycle_txn_pb.set_creation_time(current_time);
6716
0
            recycle_txn_pb.set_label(txn_info.label());
6717
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6718
0
                LOG_WARNING("failed to serialize txn recycle info")
6719
0
                        .tag("key", hex(k))
6720
0
                        .tag("db_id", db_id)
6721
0
                        .tag("txn_id", txn_id);
6722
0
                return -1;
6723
0
            }
6724
0
            txn->put(recyc_txn_key, recyc_txn_val);
6725
            // Remove txn running key
6726
0
            txn->remove(k);
6727
0
            err = txn->commit();
6728
0
            if (err != TxnErrorCode::TXN_OK) {
6729
0
                LOG_WARNING("failed to commit txn err={}", err)
6730
0
                        .tag("key", hex(k))
6731
0
                        .tag("db_id", db_id)
6732
0
                        .tag("txn_id", txn_id);
6733
0
                return -1;
6734
0
            }
6735
0
            metrics_context.total_recycled_num = ++num_abort;
6736
0
            metrics_context.report();
6737
0
        }
6738
6739
0
        return 0;
6740
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6641
6
                                  this](std::string_view k, std::string_view v) -> int {
6642
6
        ++num_scanned;
6643
6644
6
        std::unique_ptr<Transaction> txn;
6645
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6646
6
        if (err != TxnErrorCode::TXN_OK) {
6647
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6648
0
            return -1;
6649
0
        }
6650
6
        std::string_view k1 = k;
6651
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6652
6
        k1.remove_prefix(1); // Remove key space
6653
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6654
6
        if (decode_key(&k1, &out) != 0) {
6655
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6656
0
            return -1;
6657
0
        }
6658
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6659
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6660
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6661
        // Update txn_info
6662
6
        std::string txn_inf_key, txn_inf_val;
6663
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6664
6
        err = txn->get(txn_inf_key, &txn_inf_val);
6665
6
        if (err != TxnErrorCode::TXN_OK) {
6666
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6667
0
            return -1;
6668
0
        }
6669
6
        TxnInfoPB txn_info;
6670
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
6671
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6672
0
            return -1;
6673
0
        }
6674
6675
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6676
0
            txn.reset();
6677
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6678
0
            std::shared_ptr<TxnLazyCommitTask> task =
6679
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6680
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6681
0
            if (ret.first != MetaServiceCode::OK) {
6682
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6683
0
                             << "msg=" << ret.second;
6684
0
                return -1;
6685
0
            }
6686
0
            ++num_advance;
6687
0
            return 0;
6688
6
        } else {
6689
6
            TxnRunningPB txn_running_pb;
6690
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6691
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6692
0
                return -1;
6693
0
            }
6694
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6695
4
                return 0;
6696
4
            }
6697
2
            ++num_timeout;
6698
6699
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6700
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6701
2
            txn_info.set_finish_time(current_time);
6702
2
            txn_info.set_reason("timeout");
6703
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6704
2
            txn_inf_val.clear();
6705
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6706
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6707
0
                return -1;
6708
0
            }
6709
2
            txn->put(txn_inf_key, txn_inf_val);
6710
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6711
            // Put recycle txn key
6712
2
            std::string recyc_txn_key, recyc_txn_val;
6713
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6714
2
            RecycleTxnPB recycle_txn_pb;
6715
2
            recycle_txn_pb.set_creation_time(current_time);
6716
2
            recycle_txn_pb.set_label(txn_info.label());
6717
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6718
0
                LOG_WARNING("failed to serialize txn recycle info")
6719
0
                        .tag("key", hex(k))
6720
0
                        .tag("db_id", db_id)
6721
0
                        .tag("txn_id", txn_id);
6722
0
                return -1;
6723
0
            }
6724
2
            txn->put(recyc_txn_key, recyc_txn_val);
6725
            // Remove txn running key
6726
2
            txn->remove(k);
6727
2
            err = txn->commit();
6728
2
            if (err != TxnErrorCode::TXN_OK) {
6729
0
                LOG_WARNING("failed to commit txn err={}", err)
6730
0
                        .tag("key", hex(k))
6731
0
                        .tag("db_id", db_id)
6732
0
                        .tag("txn_id", txn_id);
6733
0
                return -1;
6734
0
            }
6735
2
            metrics_context.total_recycled_num = ++num_abort;
6736
2
            metrics_context.report();
6737
2
        }
6738
6739
2
        return 0;
6740
6
    };
6741
6742
19
    if (config::enable_recycler_stats_metrics) {
6743
0
        scan_and_statistics_abort_timeout_txn();
6744
0
    }
6745
    // recycle_func and loop_done for scan and recycle
6746
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
6747
19
                            std::move(handle_txn_running_kv));
6748
19
}
6749
6750
19
int InstanceRecycler::recycle_expired_txn_label() {
6751
19
    const std::string task_name = "recycle_expired_txn_label";
6752
19
    int64_t num_scanned = 0;
6753
19
    int64_t num_expired = 0;
6754
19
    std::atomic_long num_recycled = 0;
6755
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6756
19
    int ret = 0;
6757
6758
19
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
6759
19
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6760
19
    std::string begin_recycle_txn_key;
6761
19
    std::string end_recycle_txn_key;
6762
19
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
6763
19
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
6764
19
    std::vector<std::string> recycle_txn_info_keys;
6765
6766
19
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
6767
6768
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6769
19
    register_recycle_task(task_name, start_time);
6770
19
    DORIS_CLOUD_DEFER {
6771
19
        unregister_recycle_task(task_name);
6772
19
        int64_t cost =
6773
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6774
19
        metrics_context.finish_report();
6775
19
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6776
19
                .tag("instance_id", instance_id_)
6777
19
                .tag("num_scanned", num_scanned)
6778
19
                .tag("num_expired", num_expired)
6779
19
                .tag("num_recycled", num_recycled);
6780
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6770
1
    DORIS_CLOUD_DEFER {
6771
1
        unregister_recycle_task(task_name);
6772
1
        int64_t cost =
6773
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6774
1
        metrics_context.finish_report();
6775
1
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6776
1
                .tag("instance_id", instance_id_)
6777
1
                .tag("num_scanned", num_scanned)
6778
1
                .tag("num_expired", num_expired)
6779
1
                .tag("num_recycled", num_recycled);
6780
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6770
18
    DORIS_CLOUD_DEFER {
6771
18
        unregister_recycle_task(task_name);
6772
18
        int64_t cost =
6773
18
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6774
18
        metrics_context.finish_report();
6775
18
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6776
18
                .tag("instance_id", instance_id_)
6777
18
                .tag("num_scanned", num_scanned)
6778
18
                .tag("num_expired", num_expired)
6779
18
                .tag("num_recycled", num_recycled);
6780
18
    };
6781
6782
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6783
6784
19
    SyncExecutor<int> concurrent_delete_executor(
6785
19
            _thread_pool_group.s3_producer_pool,
6786
19
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
6787
23.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
6787
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
6787
23.0k
            [](const int& ret) { return ret != 0; });
6788
6789
19
    int64_t current_time_ms =
6790
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6791
6792
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6793
30.0k
        ++num_scanned;
6794
30.0k
        RecycleTxnPB recycle_txn_pb;
6795
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6796
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6797
0
            return -1;
6798
0
        }
6799
30.0k
        if ((config::force_immediate_recycle) ||
6800
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6801
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6802
30.0k
             current_time_ms)) {
6803
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6804
23.0k
            num_expired++;
6805
23.0k
            recycle_txn_info_keys.emplace_back(k);
6806
23.0k
        }
6807
30.0k
        return 0;
6808
30.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6792
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6793
1
        ++num_scanned;
6794
1
        RecycleTxnPB recycle_txn_pb;
6795
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6796
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6797
0
            return -1;
6798
0
        }
6799
1
        if ((config::force_immediate_recycle) ||
6800
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6801
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6802
1
             current_time_ms)) {
6803
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6804
1
            num_expired++;
6805
1
            recycle_txn_info_keys.emplace_back(k);
6806
1
        }
6807
1
        return 0;
6808
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6792
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6793
30.0k
        ++num_scanned;
6794
30.0k
        RecycleTxnPB recycle_txn_pb;
6795
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6796
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6797
0
            return -1;
6798
0
        }
6799
30.0k
        if ((config::force_immediate_recycle) ||
6800
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6801
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6802
30.0k
             current_time_ms)) {
6803
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6804
23.0k
            num_expired++;
6805
23.0k
            recycle_txn_info_keys.emplace_back(k);
6806
23.0k
        }
6807
30.0k
        return 0;
6808
30.0k
    };
6809
6810
    // int 0 for success, 1 for conflict, -1 for error
6811
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6812
23.0k
        std::string_view k1 = k;
6813
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6814
23.0k
        k1.remove_prefix(1); // Remove key space
6815
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6816
23.0k
        int ret = decode_key(&k1, &out);
6817
23.0k
        if (ret != 0) {
6818
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6819
0
            return -1;
6820
0
        }
6821
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6822
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6823
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6824
23.0k
        std::unique_ptr<Transaction> txn;
6825
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6826
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6827
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6828
0
            return -1;
6829
0
        }
6830
        // Remove txn index kv
6831
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6832
23.0k
        txn->remove(index_key);
6833
        // Remove txn info kv
6834
23.0k
        std::string info_key, info_val;
6835
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6836
23.0k
        err = txn->get(info_key, &info_val);
6837
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6838
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6839
0
            return -1;
6840
0
        }
6841
23.0k
        TxnInfoPB txn_info;
6842
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6843
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6844
0
            return -1;
6845
0
        }
6846
23.0k
        txn->remove(info_key);
6847
        // Remove sub txn index kvs
6848
23.0k
        std::vector<std::string> sub_txn_index_keys;
6849
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6850
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6851
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6852
22.9k
        }
6853
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6854
22.9k
            txn->remove(sub_txn_index_key);
6855
22.9k
        }
6856
        // Update txn label
6857
23.0k
        std::string label_key, label_val;
6858
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6859
23.0k
        err = txn->get(label_key, &label_val);
6860
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6861
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6862
0
                         << " err=" << err;
6863
0
            return -1;
6864
0
        }
6865
23.0k
        TxnLabelPB txn_label;
6866
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6867
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6868
0
            return -1;
6869
0
        }
6870
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6871
23.0k
        if (it != txn_label.txn_ids().end()) {
6872
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6873
23.0k
        }
6874
23.0k
        if (txn_label.txn_ids().empty()) {
6875
23.0k
            txn->remove(label_key);
6876
23.0k
            TEST_SYNC_POINT_CALLBACK(
6877
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6878
23.0k
        } else {
6879
73
            if (!txn_label.SerializeToString(&label_val)) {
6880
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6881
0
                return -1;
6882
0
            }
6883
73
            TEST_SYNC_POINT_CALLBACK(
6884
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6885
73
            txn->atomic_set_ver_value(label_key, label_val);
6886
73
            TEST_SYNC_POINT_CALLBACK(
6887
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6888
73
        }
6889
        // Remove recycle txn kv
6890
23.0k
        txn->remove(k);
6891
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6892
23.0k
        err = txn->commit();
6893
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6894
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6895
62
                TEST_SYNC_POINT_CALLBACK(
6896
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6897
                // log the txn_id and label
6898
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6899
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6900
62
                             << " txn_label=" << txn_info.label();
6901
62
                return 1;
6902
62
            }
6903
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6904
0
            return -1;
6905
62
        }
6906
23.0k
        ++num_recycled;
6907
6908
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6909
23.0k
        return 0;
6910
23.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6811
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6812
1
        std::string_view k1 = k;
6813
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6814
1
        k1.remove_prefix(1); // Remove key space
6815
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6816
1
        int ret = decode_key(&k1, &out);
6817
1
        if (ret != 0) {
6818
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6819
0
            return -1;
6820
0
        }
6821
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6822
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6823
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6824
1
        std::unique_ptr<Transaction> txn;
6825
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6826
1
        if (err != TxnErrorCode::TXN_OK) {
6827
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6828
0
            return -1;
6829
0
        }
6830
        // Remove txn index kv
6831
1
        auto index_key = txn_index_key({instance_id_, txn_id});
6832
1
        txn->remove(index_key);
6833
        // Remove txn info kv
6834
1
        std::string info_key, info_val;
6835
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6836
1
        err = txn->get(info_key, &info_val);
6837
1
        if (err != TxnErrorCode::TXN_OK) {
6838
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6839
0
            return -1;
6840
0
        }
6841
1
        TxnInfoPB txn_info;
6842
1
        if (!txn_info.ParseFromString(info_val)) {
6843
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6844
0
            return -1;
6845
0
        }
6846
1
        txn->remove(info_key);
6847
        // Remove sub txn index kvs
6848
1
        std::vector<std::string> sub_txn_index_keys;
6849
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6850
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6851
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
6852
0
        }
6853
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6854
0
            txn->remove(sub_txn_index_key);
6855
0
        }
6856
        // Update txn label
6857
1
        std::string label_key, label_val;
6858
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6859
1
        err = txn->get(label_key, &label_val);
6860
1
        if (err != TxnErrorCode::TXN_OK) {
6861
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6862
0
                         << " err=" << err;
6863
0
            return -1;
6864
0
        }
6865
1
        TxnLabelPB txn_label;
6866
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6867
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6868
0
            return -1;
6869
0
        }
6870
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6871
1
        if (it != txn_label.txn_ids().end()) {
6872
1
            txn_label.mutable_txn_ids()->erase(it);
6873
1
        }
6874
1
        if (txn_label.txn_ids().empty()) {
6875
1
            txn->remove(label_key);
6876
1
            TEST_SYNC_POINT_CALLBACK(
6877
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6878
1
        } else {
6879
0
            if (!txn_label.SerializeToString(&label_val)) {
6880
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6881
0
                return -1;
6882
0
            }
6883
0
            TEST_SYNC_POINT_CALLBACK(
6884
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6885
0
            txn->atomic_set_ver_value(label_key, label_val);
6886
0
            TEST_SYNC_POINT_CALLBACK(
6887
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6888
0
        }
6889
        // Remove recycle txn kv
6890
1
        txn->remove(k);
6891
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6892
1
        err = txn->commit();
6893
1
        if (err != TxnErrorCode::TXN_OK) {
6894
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
6895
0
                TEST_SYNC_POINT_CALLBACK(
6896
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6897
                // log the txn_id and label
6898
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6899
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6900
0
                             << " txn_label=" << txn_info.label();
6901
0
                return 1;
6902
0
            }
6903
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6904
0
            return -1;
6905
0
        }
6906
1
        ++num_recycled;
6907
6908
1
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6909
1
        return 0;
6910
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6811
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6812
23.0k
        std::string_view k1 = k;
6813
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6814
23.0k
        k1.remove_prefix(1); // Remove key space
6815
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6816
23.0k
        int ret = decode_key(&k1, &out);
6817
23.0k
        if (ret != 0) {
6818
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6819
0
            return -1;
6820
0
        }
6821
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6822
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6823
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6824
23.0k
        std::unique_ptr<Transaction> txn;
6825
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6826
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6827
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6828
0
            return -1;
6829
0
        }
6830
        // Remove txn index kv
6831
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6832
23.0k
        txn->remove(index_key);
6833
        // Remove txn info kv
6834
23.0k
        std::string info_key, info_val;
6835
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6836
23.0k
        err = txn->get(info_key, &info_val);
6837
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6838
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6839
0
            return -1;
6840
0
        }
6841
23.0k
        TxnInfoPB txn_info;
6842
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6843
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6844
0
            return -1;
6845
0
        }
6846
23.0k
        txn->remove(info_key);
6847
        // Remove sub txn index kvs
6848
23.0k
        std::vector<std::string> sub_txn_index_keys;
6849
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6850
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6851
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6852
22.9k
        }
6853
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6854
22.9k
            txn->remove(sub_txn_index_key);
6855
22.9k
        }
6856
        // Update txn label
6857
23.0k
        std::string label_key, label_val;
6858
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6859
23.0k
        err = txn->get(label_key, &label_val);
6860
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6861
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6862
0
                         << " err=" << err;
6863
0
            return -1;
6864
0
        }
6865
23.0k
        TxnLabelPB txn_label;
6866
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6867
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6868
0
            return -1;
6869
0
        }
6870
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6871
23.0k
        if (it != txn_label.txn_ids().end()) {
6872
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6873
23.0k
        }
6874
23.0k
        if (txn_label.txn_ids().empty()) {
6875
23.0k
            txn->remove(label_key);
6876
23.0k
            TEST_SYNC_POINT_CALLBACK(
6877
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6878
23.0k
        } else {
6879
73
            if (!txn_label.SerializeToString(&label_val)) {
6880
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6881
0
                return -1;
6882
0
            }
6883
73
            TEST_SYNC_POINT_CALLBACK(
6884
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6885
73
            txn->atomic_set_ver_value(label_key, label_val);
6886
73
            TEST_SYNC_POINT_CALLBACK(
6887
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6888
73
        }
6889
        // Remove recycle txn kv
6890
23.0k
        txn->remove(k);
6891
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6892
23.0k
        err = txn->commit();
6893
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6894
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6895
62
                TEST_SYNC_POINT_CALLBACK(
6896
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6897
                // log the txn_id and label
6898
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6899
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6900
62
                             << " txn_label=" << txn_info.label();
6901
62
                return 1;
6902
62
            }
6903
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6904
0
            return -1;
6905
62
        }
6906
23.0k
        ++num_recycled;
6907
6908
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6909
23.0k
        return 0;
6910
23.0k
    };
6911
6912
19
    auto loop_done = [&]() -> int {
6913
10
        DORIS_CLOUD_DEFER {
6914
10
            recycle_txn_info_keys.clear();
6915
10
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6913
1
        DORIS_CLOUD_DEFER {
6914
1
            recycle_txn_info_keys.clear();
6915
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6913
9
        DORIS_CLOUD_DEFER {
6914
9
            recycle_txn_info_keys.clear();
6915
9
        };
6916
10
        TEST_SYNC_POINT_CALLBACK(
6917
10
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6918
10
                &recycle_txn_info_keys);
6919
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6920
23.0k
            concurrent_delete_executor.add([&]() {
6921
23.0k
                int ret = delete_recycle_txn_kv(k);
6922
23.0k
                if (ret == 1) {
6923
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6924
54
                    for (int i = 1; i <= max_retry; ++i) {
6925
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6926
54
                        ret = delete_recycle_txn_kv(k);
6927
                        // clang-format off
6928
54
                        TEST_SYNC_POINT_CALLBACK(
6929
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6930
                        // clang-format off
6931
54
                        if (ret != 1) {
6932
18
                            break;
6933
18
                        }
6934
                        // random sleep 0-100 ms to retry
6935
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6936
36
                    }
6937
18
                }
6938
23.0k
                if (ret != 0) {
6939
9
                    LOG_WARNING("failed to delete recycle txn kv")
6940
9
                            .tag("instance id", instance_id_)
6941
9
                            .tag("key", hex(k));
6942
9
                    return -1;
6943
9
                }
6944
23.0k
                return 0;
6945
23.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6920
1
            concurrent_delete_executor.add([&]() {
6921
1
                int ret = delete_recycle_txn_kv(k);
6922
1
                if (ret == 1) {
6923
0
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6924
0
                    for (int i = 1; i <= max_retry; ++i) {
6925
0
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6926
0
                        ret = delete_recycle_txn_kv(k);
6927
                        // clang-format off
6928
0
                        TEST_SYNC_POINT_CALLBACK(
6929
0
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6930
                        // clang-format off
6931
0
                        if (ret != 1) {
6932
0
                            break;
6933
0
                        }
6934
                        // random sleep 0-100 ms to retry
6935
0
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6936
0
                    }
6937
0
                }
6938
1
                if (ret != 0) {
6939
0
                    LOG_WARNING("failed to delete recycle txn kv")
6940
0
                            .tag("instance id", instance_id_)
6941
0
                            .tag("key", hex(k));
6942
0
                    return -1;
6943
0
                }
6944
1
                return 0;
6945
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6920
23.0k
            concurrent_delete_executor.add([&]() {
6921
23.0k
                int ret = delete_recycle_txn_kv(k);
6922
23.0k
                if (ret == 1) {
6923
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6924
54
                    for (int i = 1; i <= max_retry; ++i) {
6925
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6926
54
                        ret = delete_recycle_txn_kv(k);
6927
                        // clang-format off
6928
54
                        TEST_SYNC_POINT_CALLBACK(
6929
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6930
                        // clang-format off
6931
54
                        if (ret != 1) {
6932
18
                            break;
6933
18
                        }
6934
                        // random sleep 0-100 ms to retry
6935
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6936
36
                    }
6937
18
                }
6938
23.0k
                if (ret != 0) {
6939
9
                    LOG_WARNING("failed to delete recycle txn kv")
6940
9
                            .tag("instance id", instance_id_)
6941
9
                            .tag("key", hex(k));
6942
9
                    return -1;
6943
9
                }
6944
23.0k
                return 0;
6945
23.0k
            });
6946
23.0k
        }
6947
10
        bool finished = true;
6948
10
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6949
23.0k
        for (int r : rets) {
6950
23.0k
            if (r != 0) {
6951
9
                ret = -1;
6952
9
            }
6953
23.0k
        }
6954
6955
10
        ret = finished ? ret : -1;
6956
6957
        // Update metrics after all concurrent tasks completed
6958
10
        metrics_context.total_recycled_num = num_recycled.load();
6959
10
        metrics_context.report();
6960
6961
10
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6962
6963
10
        if (ret != 0) {
6964
3
            LOG_WARNING("recycle txn kv ret!=0")
6965
3
                    .tag("finished", finished)
6966
3
                    .tag("ret", ret)
6967
3
                    .tag("instance_id", instance_id_);
6968
3
            return ret;
6969
3
        }
6970
7
        return ret;
6971
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6912
1
    auto loop_done = [&]() -> int {
6913
1
        DORIS_CLOUD_DEFER {
6914
1
            recycle_txn_info_keys.clear();
6915
1
        };
6916
1
        TEST_SYNC_POINT_CALLBACK(
6917
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6918
1
                &recycle_txn_info_keys);
6919
1
        for (const auto& k : recycle_txn_info_keys) {
6920
1
            concurrent_delete_executor.add([&]() {
6921
1
                int ret = delete_recycle_txn_kv(k);
6922
1
                if (ret == 1) {
6923
1
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6924
1
                    for (int i = 1; i <= max_retry; ++i) {
6925
1
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6926
1
                        ret = delete_recycle_txn_kv(k);
6927
                        // clang-format off
6928
1
                        TEST_SYNC_POINT_CALLBACK(
6929
1
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6930
                        // clang-format off
6931
1
                        if (ret != 1) {
6932
1
                            break;
6933
1
                        }
6934
                        // random sleep 0-100 ms to retry
6935
1
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6936
1
                    }
6937
1
                }
6938
1
                if (ret != 0) {
6939
1
                    LOG_WARNING("failed to delete recycle txn kv")
6940
1
                            .tag("instance id", instance_id_)
6941
1
                            .tag("key", hex(k));
6942
1
                    return -1;
6943
1
                }
6944
1
                return 0;
6945
1
            });
6946
1
        }
6947
1
        bool finished = true;
6948
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6949
1
        for (int r : rets) {
6950
1
            if (r != 0) {
6951
0
                ret = -1;
6952
0
            }
6953
1
        }
6954
6955
1
        ret = finished ? ret : -1;
6956
6957
        // Update metrics after all concurrent tasks completed
6958
1
        metrics_context.total_recycled_num = num_recycled.load();
6959
1
        metrics_context.report();
6960
6961
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6962
6963
1
        if (ret != 0) {
6964
0
            LOG_WARNING("recycle txn kv ret!=0")
6965
0
                    .tag("finished", finished)
6966
0
                    .tag("ret", ret)
6967
0
                    .tag("instance_id", instance_id_);
6968
0
            return ret;
6969
0
        }
6970
1
        return ret;
6971
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6912
9
    auto loop_done = [&]() -> int {
6913
9
        DORIS_CLOUD_DEFER {
6914
9
            recycle_txn_info_keys.clear();
6915
9
        };
6916
9
        TEST_SYNC_POINT_CALLBACK(
6917
9
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6918
9
                &recycle_txn_info_keys);
6919
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6920
23.0k
            concurrent_delete_executor.add([&]() {
6921
23.0k
                int ret = delete_recycle_txn_kv(k);
6922
23.0k
                if (ret == 1) {
6923
23.0k
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6924
23.0k
                    for (int i = 1; i <= max_retry; ++i) {
6925
23.0k
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6926
23.0k
                        ret = delete_recycle_txn_kv(k);
6927
                        // clang-format off
6928
23.0k
                        TEST_SYNC_POINT_CALLBACK(
6929
23.0k
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6930
                        // clang-format off
6931
23.0k
                        if (ret != 1) {
6932
23.0k
                            break;
6933
23.0k
                        }
6934
                        // random sleep 0-100 ms to retry
6935
23.0k
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6936
23.0k
                    }
6937
23.0k
                }
6938
23.0k
                if (ret != 0) {
6939
23.0k
                    LOG_WARNING("failed to delete recycle txn kv")
6940
23.0k
                            .tag("instance id", instance_id_)
6941
23.0k
                            .tag("key", hex(k));
6942
23.0k
                    return -1;
6943
23.0k
                }
6944
23.0k
                return 0;
6945
23.0k
            });
6946
23.0k
        }
6947
9
        bool finished = true;
6948
9
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6949
23.0k
        for (int r : rets) {
6950
23.0k
            if (r != 0) {
6951
9
                ret = -1;
6952
9
            }
6953
23.0k
        }
6954
6955
9
        ret = finished ? ret : -1;
6956
6957
        // Update metrics after all concurrent tasks completed
6958
9
        metrics_context.total_recycled_num = num_recycled.load();
6959
9
        metrics_context.report();
6960
6961
9
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6962
6963
9
        if (ret != 0) {
6964
3
            LOG_WARNING("recycle txn kv ret!=0")
6965
3
                    .tag("finished", finished)
6966
3
                    .tag("ret", ret)
6967
3
                    .tag("instance_id", instance_id_);
6968
3
            return ret;
6969
3
        }
6970
6
        return ret;
6971
9
    };
6972
6973
19
    if (config::enable_recycler_stats_metrics) {
6974
0
        scan_and_statistics_expired_txn_label();
6975
0
    }
6976
    // recycle_func and loop_done for scan and recycle
6977
19
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
6978
19
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
6979
19
}
6980
6981
struct CopyJobIdTuple {
6982
    std::string instance_id;
6983
    std::string stage_id;
6984
    long table_id;
6985
    std::string copy_id;
6986
    std::string stage_path;
6987
};
6988
struct BatchObjStoreAccessor {
6989
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
6990
                          TxnKv* txn_kv)
6991
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
6992
3
    ~BatchObjStoreAccessor() {
6993
3
        if (!paths_.empty()) {
6994
3
            consume();
6995
3
        }
6996
3
    }
6997
6998
    /**
6999
    * To implicitely do batch work and submit the batch delete task to s3
7000
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
7001
    *
7002
    * @param copy_job The protubuf struct consists of the copy job files.
7003
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
7004
    *            it would last until we finish the delete task, here we need pass one string value
7005
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
7006
    */
7007
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
7008
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
7009
5
        auto& file_keys = copy_file_keys_[key];
7010
5
        file_keys.log_trace =
7011
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
7012
5
                            instance_id, stage_id, table_id, copy_id, path);
7013
5
        std::string_view log_trace = file_keys.log_trace;
7014
2.03k
        for (const auto& file : copy_job.object_files()) {
7015
2.03k
            auto relative_path = file.relative_path();
7016
2.03k
            paths_.push_back(relative_path);
7017
2.03k
            file_keys.keys.push_back(copy_file_key(
7018
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
7019
2.03k
            LOG_INFO(log_trace)
7020
2.03k
                    .tag("relative_path", relative_path)
7021
2.03k
                    .tag("batch_count", batch_count_);
7022
2.03k
        }
7023
5
        LOG_INFO(log_trace)
7024
5
                .tag("objects_num", copy_job.object_files().size())
7025
5
                .tag("batch_count", batch_count_);
7026
        // 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
7027
        // recommend using delete objects when objects num is less than 10)
7028
5
        if (paths_.size() < 1000) {
7029
3
            return;
7030
3
        }
7031
2
        consume();
7032
2
    }
7033
7034
private:
7035
5
    void consume() {
7036
5
        DORIS_CLOUD_DEFER {
7037
5
            paths_.clear();
7038
5
            copy_file_keys_.clear();
7039
5
            batch_count_++;
7040
7041
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
7042
5
                        batch_count_);
7043
5
        };
7044
7045
5
        StopWatch sw;
7046
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
7047
5
        if (0 != accessor_->delete_files(paths_)) {
7048
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
7049
2
                        paths_.size(), batch_count_, sw.elapsed_us());
7050
2
            return;
7051
2
        }
7052
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
7053
3
                    paths_.size(), batch_count_, sw.elapsed_us());
7054
        // delete fdb's keys
7055
3
        for (auto& file_keys : copy_file_keys_) {
7056
3
            auto& [log_trace, keys] = file_keys.second;
7057
3
            std::unique_ptr<Transaction> txn;
7058
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
7059
0
                LOG(WARNING) << "failed to create txn";
7060
0
                continue;
7061
0
            }
7062
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7063
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7064
            // limited, should not cause the txn commit failed.
7065
1.02k
            for (const auto& key : keys) {
7066
1.02k
                txn->remove(key);
7067
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
7068
1.02k
            }
7069
3
            txn->remove(file_keys.first);
7070
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
7071
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
7072
0
                continue;
7073
0
            }
7074
3
        }
7075
3
    }
7076
    std::shared_ptr<StorageVaultAccessor> accessor_;
7077
    // the path of the s3 files to be deleted
7078
    std::vector<std::string> paths_;
7079
    struct CopyFiles {
7080
        std::string log_trace;
7081
        std::vector<std::string> keys;
7082
    };
7083
    // pair<std::string, std::vector<std::string>>
7084
    // first: instance_id_ stage_id table_id query_id
7085
    // second: keys to be deleted
7086
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
7087
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
7088
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
7089
    // which can together uniquely identifies different tasks for tracing log
7090
    uint64_t& batch_count_;
7091
    TxnKv* txn_kv_;
7092
};
7093
7094
13
int InstanceRecycler::recycle_copy_jobs() {
7095
13
    int64_t num_scanned = 0;
7096
13
    int64_t num_finished = 0;
7097
13
    int64_t num_expired = 0;
7098
13
    int64_t num_recycled = 0;
7099
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
7100
13
    uint64_t batch_count = 0;
7101
13
    const std::string task_name = "recycle_copy_jobs";
7102
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7103
7104
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
7105
7106
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7107
13
    register_recycle_task(task_name, start_time);
7108
7109
13
    DORIS_CLOUD_DEFER {
7110
13
        unregister_recycle_task(task_name);
7111
13
        int64_t cost =
7112
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7113
13
        metrics_context.finish_report();
7114
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7115
13
                .tag("instance_id", instance_id_)
7116
13
                .tag("num_scanned", num_scanned)
7117
13
                .tag("num_finished", num_finished)
7118
13
                .tag("num_expired", num_expired)
7119
13
                .tag("num_recycled", num_recycled);
7120
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
7109
13
    DORIS_CLOUD_DEFER {
7110
13
        unregister_recycle_task(task_name);
7111
13
        int64_t cost =
7112
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7113
13
        metrics_context.finish_report();
7114
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7115
13
                .tag("instance_id", instance_id_)
7116
13
                .tag("num_scanned", num_scanned)
7117
13
                .tag("num_finished", num_finished)
7118
13
                .tag("num_expired", num_expired)
7119
13
                .tag("num_recycled", num_recycled);
7120
13
    };
7121
7122
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7123
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7124
13
    std::string key0;
7125
13
    std::string key1;
7126
13
    copy_job_key(key_info0, &key0);
7127
13
    copy_job_key(key_info1, &key1);
7128
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
7129
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
7130
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
7131
16
                         this](std::string_view k, std::string_view v) -> int {
7132
16
        ++num_scanned;
7133
16
        CopyJobPB copy_job;
7134
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7135
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7136
0
            return -1;
7137
0
        }
7138
7139
        // decode copy job key
7140
16
        auto k1 = k;
7141
16
        k1.remove_prefix(1);
7142
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7143
16
        decode_key(&k1, &out);
7144
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7145
        // -> CopyJobPB
7146
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7147
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7148
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7149
7150
16
        bool check_storage = true;
7151
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7152
12
            ++num_finished;
7153
7154
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7155
7
                auto it = stage_accessor_map.find(stage_id);
7156
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7157
7
                std::string_view path;
7158
7
                if (it != stage_accessor_map.end()) {
7159
2
                    accessor = it->second;
7160
5
                } else {
7161
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7162
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7163
5
                                                      &inner_accessor);
7164
5
                    if (ret < 0) { // error
7165
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7166
0
                        return -1;
7167
5
                    } else if (ret == 0) {
7168
3
                        path = inner_accessor->uri();
7169
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7170
3
                                inner_accessor, batch_count, txn_kv_.get());
7171
3
                        stage_accessor_map.emplace(stage_id, accessor);
7172
3
                    } else { // stage not found, skip check storage
7173
2
                        check_storage = false;
7174
2
                    }
7175
5
                }
7176
7
                if (check_storage) {
7177
                    // TODO delete objects with key and etag is not supported
7178
5
                    accessor->add(std::move(copy_job), std::string(k),
7179
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7180
5
                    return 0;
7181
5
                }
7182
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7183
5
                int64_t current_time =
7184
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7185
5
                if (copy_job.finish_time_ms() > 0) {
7186
2
                    if (!config::force_immediate_recycle &&
7187
2
                        current_time < copy_job.finish_time_ms() +
7188
2
                                               config::copy_job_max_retention_second * 1000) {
7189
1
                        return 0;
7190
1
                    }
7191
3
                } else {
7192
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7193
3
                    if (!config::force_immediate_recycle &&
7194
3
                        current_time < copy_job.start_time_ms() +
7195
3
                                               config::copy_job_max_retention_second * 1000) {
7196
1
                        return 0;
7197
1
                    }
7198
3
                }
7199
5
            }
7200
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7201
4
            int64_t current_time =
7202
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7203
            // if copy job is timeout: delete all copy file kvs and copy job kv
7204
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7205
2
                return 0;
7206
2
            }
7207
2
            ++num_expired;
7208
2
        }
7209
7210
        // delete all copy files
7211
7
        std::vector<std::string> copy_file_keys;
7212
70
        for (auto& file : copy_job.object_files()) {
7213
70
            copy_file_keys.push_back(copy_file_key(
7214
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7215
70
        }
7216
7
        std::unique_ptr<Transaction> txn;
7217
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7218
0
            LOG(WARNING) << "failed to create txn";
7219
0
            return -1;
7220
0
        }
7221
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7222
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7223
        // limited, should not cause the txn commit failed.
7224
70
        for (const auto& key : copy_file_keys) {
7225
70
            txn->remove(key);
7226
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7227
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7228
70
                      << ", query_id=" << copy_id;
7229
70
        }
7230
7
        txn->remove(k);
7231
7
        TxnErrorCode err = txn->commit();
7232
7
        if (err != TxnErrorCode::TXN_OK) {
7233
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7234
0
            return -1;
7235
0
        }
7236
7237
7
        metrics_context.total_recycled_num = ++num_recycled;
7238
7
        metrics_context.report();
7239
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7240
7
        return 0;
7241
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
7131
16
                         this](std::string_view k, std::string_view v) -> int {
7132
16
        ++num_scanned;
7133
16
        CopyJobPB copy_job;
7134
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7135
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7136
0
            return -1;
7137
0
        }
7138
7139
        // decode copy job key
7140
16
        auto k1 = k;
7141
16
        k1.remove_prefix(1);
7142
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7143
16
        decode_key(&k1, &out);
7144
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7145
        // -> CopyJobPB
7146
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7147
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7148
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7149
7150
16
        bool check_storage = true;
7151
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7152
12
            ++num_finished;
7153
7154
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7155
7
                auto it = stage_accessor_map.find(stage_id);
7156
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7157
7
                std::string_view path;
7158
7
                if (it != stage_accessor_map.end()) {
7159
2
                    accessor = it->second;
7160
5
                } else {
7161
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7162
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7163
5
                                                      &inner_accessor);
7164
5
                    if (ret < 0) { // error
7165
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7166
0
                        return -1;
7167
5
                    } else if (ret == 0) {
7168
3
                        path = inner_accessor->uri();
7169
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7170
3
                                inner_accessor, batch_count, txn_kv_.get());
7171
3
                        stage_accessor_map.emplace(stage_id, accessor);
7172
3
                    } else { // stage not found, skip check storage
7173
2
                        check_storage = false;
7174
2
                    }
7175
5
                }
7176
7
                if (check_storage) {
7177
                    // TODO delete objects with key and etag is not supported
7178
5
                    accessor->add(std::move(copy_job), std::string(k),
7179
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7180
5
                    return 0;
7181
5
                }
7182
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7183
5
                int64_t current_time =
7184
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7185
5
                if (copy_job.finish_time_ms() > 0) {
7186
2
                    if (!config::force_immediate_recycle &&
7187
2
                        current_time < copy_job.finish_time_ms() +
7188
2
                                               config::copy_job_max_retention_second * 1000) {
7189
1
                        return 0;
7190
1
                    }
7191
3
                } else {
7192
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7193
3
                    if (!config::force_immediate_recycle &&
7194
3
                        current_time < copy_job.start_time_ms() +
7195
3
                                               config::copy_job_max_retention_second * 1000) {
7196
1
                        return 0;
7197
1
                    }
7198
3
                }
7199
5
            }
7200
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7201
4
            int64_t current_time =
7202
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7203
            // if copy job is timeout: delete all copy file kvs and copy job kv
7204
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7205
2
                return 0;
7206
2
            }
7207
2
            ++num_expired;
7208
2
        }
7209
7210
        // delete all copy files
7211
7
        std::vector<std::string> copy_file_keys;
7212
70
        for (auto& file : copy_job.object_files()) {
7213
70
            copy_file_keys.push_back(copy_file_key(
7214
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7215
70
        }
7216
7
        std::unique_ptr<Transaction> txn;
7217
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7218
0
            LOG(WARNING) << "failed to create txn";
7219
0
            return -1;
7220
0
        }
7221
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7222
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7223
        // limited, should not cause the txn commit failed.
7224
70
        for (const auto& key : copy_file_keys) {
7225
70
            txn->remove(key);
7226
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7227
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7228
70
                      << ", query_id=" << copy_id;
7229
70
        }
7230
7
        txn->remove(k);
7231
7
        TxnErrorCode err = txn->commit();
7232
7
        if (err != TxnErrorCode::TXN_OK) {
7233
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7234
0
            return -1;
7235
0
        }
7236
7237
7
        metrics_context.total_recycled_num = ++num_recycled;
7238
7
        metrics_context.report();
7239
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7240
7
        return 0;
7241
7
    };
7242
7243
13
    if (config::enable_recycler_stats_metrics) {
7244
0
        scan_and_statistics_copy_jobs();
7245
0
    }
7246
    // recycle_func and loop_done for scan and recycle
7247
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
7248
13
}
7249
7250
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
7251
                                             const StagePB::StageType& stage_type,
7252
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
7253
5
#ifdef UNIT_TEST
7254
    // In unit test, external use the same accessor as the internal stage
7255
5
    auto it = accessor_map_.find(stage_id);
7256
5
    if (it != accessor_map_.end()) {
7257
3
        *accessor = it->second;
7258
3
    } else {
7259
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
7260
2
        return 1;
7261
2
    }
7262
#else
7263
    // init s3 accessor and add to accessor map
7264
    auto stage_it =
7265
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
7266
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
7267
7268
    if (stage_it == instance_info_.stages().end()) {
7269
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
7270
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
7271
        return 1;
7272
    }
7273
7274
    const auto& object_store_info = stage_it->obj_info();
7275
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
7276
7277
    S3Conf s3_conf;
7278
    if (stage_type == StagePB::EXTERNAL) {
7279
        if (stage_access_type == StagePB::AKSK) {
7280
            auto conf = S3Conf::from_obj_store_info(object_store_info);
7281
            if (!conf) {
7282
                return -1;
7283
            }
7284
7285
            s3_conf = std::move(*conf);
7286
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
7287
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
7288
            if (!conf) {
7289
                return -1;
7290
            }
7291
7292
            s3_conf = std::move(*conf);
7293
            if (instance_info_.ram_user().has_encryption_info()) {
7294
                AkSkPair plain_ak_sk_pair;
7295
                int ret = decrypt_ak_sk_helper(
7296
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
7297
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
7298
                if (ret != 0) {
7299
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
7300
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
7301
                    return -1;
7302
                }
7303
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
7304
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
7305
            } else {
7306
                s3_conf.ak = instance_info_.ram_user().ak();
7307
                s3_conf.sk = instance_info_.ram_user().sk();
7308
            }
7309
        } else {
7310
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
7311
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
7312
            return -1;
7313
        }
7314
    } else if (stage_type == StagePB::INTERNAL) {
7315
        int idx = stoi(object_store_info.id());
7316
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7317
            LOG(WARNING) << "invalid idx: " << idx;
7318
            return -1;
7319
        }
7320
7321
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7322
        auto conf = S3Conf::from_obj_store_info(old_obj);
7323
        if (!conf) {
7324
            return -1;
7325
        }
7326
7327
        s3_conf = std::move(*conf);
7328
        s3_conf.prefix = object_store_info.prefix();
7329
    } else {
7330
        LOG(WARNING) << "unknown stage type " << stage_type;
7331
        return -1;
7332
    }
7333
7334
    std::shared_ptr<S3Accessor> s3_accessor;
7335
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
7336
    if (ret != 0) {
7337
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
7338
        return -1;
7339
    }
7340
7341
    *accessor = std::move(s3_accessor);
7342
#endif
7343
3
    return 0;
7344
5
}
7345
7346
11
int InstanceRecycler::recycle_stage() {
7347
11
    int64_t num_scanned = 0;
7348
11
    int64_t num_recycled = 0;
7349
11
    const std::string task_name = "recycle_stage";
7350
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7351
7352
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
7353
7354
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7355
11
    register_recycle_task(task_name, start_time);
7356
7357
11
    DORIS_CLOUD_DEFER {
7358
11
        unregister_recycle_task(task_name);
7359
11
        int64_t cost =
7360
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7361
11
        metrics_context.finish_report();
7362
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7363
11
                .tag("instance_id", instance_id_)
7364
11
                .tag("num_scanned", num_scanned)
7365
11
                .tag("num_recycled", num_recycled);
7366
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
7357
11
    DORIS_CLOUD_DEFER {
7358
11
        unregister_recycle_task(task_name);
7359
11
        int64_t cost =
7360
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7361
11
        metrics_context.finish_report();
7362
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7363
11
                .tag("instance_id", instance_id_)
7364
11
                .tag("num_scanned", num_scanned)
7365
11
                .tag("num_recycled", num_recycled);
7366
11
    };
7367
7368
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7369
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7370
11
    std::string key0 = recycle_stage_key(key_info0);
7371
11
    std::string key1 = recycle_stage_key(key_info1);
7372
7373
11
    std::vector<std::string_view> stage_keys;
7374
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
7375
11
                         this](std::string_view k, std::string_view v) -> int {
7376
1
        ++num_scanned;
7377
1
        RecycleStagePB recycle_stage;
7378
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7379
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7380
0
            return -1;
7381
0
        }
7382
7383
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7384
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7385
0
            LOG(WARNING) << "invalid idx: " << idx;
7386
0
            return -1;
7387
0
        }
7388
7389
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7390
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7391
1
                [&] {
7392
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7393
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7394
1
                    if (!s3_conf) {
7395
1
                        return -1;
7396
1
                    }
7397
7398
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7399
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7400
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7401
1
                    if (ret != 0) {
7402
1
                        return -1;
7403
1
                    }
7404
7405
1
                    accessor = std::move(s3_accessor);
7406
1
                    return 0;
7407
1
                }(),
7408
1
                "recycle_stage:get_accessor", &accessor);
7409
7410
1
        if (ret != 0) {
7411
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7412
0
            return ret;
7413
0
        }
7414
7415
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7416
1
                .tag("instance_id", instance_id_)
7417
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7418
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7419
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7420
1
                .tag("obj_info_id", idx)
7421
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7422
1
        ret = accessor->delete_all();
7423
1
        if (ret != 0) {
7424
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7425
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7426
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7427
0
                         << ", ret=" << ret;
7428
0
            return -1;
7429
0
        }
7430
1
        metrics_context.total_recycled_num = ++num_recycled;
7431
1
        metrics_context.report();
7432
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7433
1
        stage_keys.push_back(k);
7434
1
        return 0;
7435
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7375
1
                         this](std::string_view k, std::string_view v) -> int {
7376
1
        ++num_scanned;
7377
1
        RecycleStagePB recycle_stage;
7378
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7379
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7380
0
            return -1;
7381
0
        }
7382
7383
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7384
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7385
0
            LOG(WARNING) << "invalid idx: " << idx;
7386
0
            return -1;
7387
0
        }
7388
7389
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7390
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7391
1
                [&] {
7392
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7393
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7394
1
                    if (!s3_conf) {
7395
1
                        return -1;
7396
1
                    }
7397
7398
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7399
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7400
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7401
1
                    if (ret != 0) {
7402
1
                        return -1;
7403
1
                    }
7404
7405
1
                    accessor = std::move(s3_accessor);
7406
1
                    return 0;
7407
1
                }(),
7408
1
                "recycle_stage:get_accessor", &accessor);
7409
7410
1
        if (ret != 0) {
7411
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7412
0
            return ret;
7413
0
        }
7414
7415
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7416
1
                .tag("instance_id", instance_id_)
7417
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7418
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7419
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7420
1
                .tag("obj_info_id", idx)
7421
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7422
1
        ret = accessor->delete_all();
7423
1
        if (ret != 0) {
7424
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7425
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7426
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7427
0
                         << ", ret=" << ret;
7428
0
            return -1;
7429
0
        }
7430
1
        metrics_context.total_recycled_num = ++num_recycled;
7431
1
        metrics_context.report();
7432
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7433
1
        stage_keys.push_back(k);
7434
1
        return 0;
7435
1
    };
7436
7437
11
    auto loop_done = [&stage_keys, this]() -> int {
7438
1
        if (stage_keys.empty()) return 0;
7439
1
        DORIS_CLOUD_DEFER {
7440
1
            stage_keys.clear();
7441
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
7439
1
        DORIS_CLOUD_DEFER {
7440
1
            stage_keys.clear();
7441
1
        };
7442
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7443
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7444
0
            return -1;
7445
0
        }
7446
1
        return 0;
7447
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
7437
1
    auto loop_done = [&stage_keys, this]() -> int {
7438
1
        if (stage_keys.empty()) return 0;
7439
1
        DORIS_CLOUD_DEFER {
7440
1
            stage_keys.clear();
7441
1
        };
7442
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7443
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7444
0
            return -1;
7445
0
        }
7446
1
        return 0;
7447
1
    };
7448
11
    if (config::enable_recycler_stats_metrics) {
7449
0
        scan_and_statistics_stage();
7450
0
    }
7451
    // recycle_func and loop_done for scan and recycle
7452
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
7453
11
}
7454
7455
10
int InstanceRecycler::recycle_expired_stage_objects() {
7456
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
7457
7458
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7459
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7460
7461
10
    DORIS_CLOUD_DEFER {
7462
10
        int64_t cost =
7463
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7464
10
        metrics_context.finish_report();
7465
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7466
10
                .tag("instance_id", instance_id_);
7467
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
7461
10
    DORIS_CLOUD_DEFER {
7462
10
        int64_t cost =
7463
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7464
10
        metrics_context.finish_report();
7465
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7466
10
                .tag("instance_id", instance_id_);
7467
10
    };
7468
7469
10
    int ret = 0;
7470
7471
10
    if (config::enable_recycler_stats_metrics) {
7472
0
        scan_and_statistics_expired_stage_objects();
7473
0
    }
7474
7475
10
    for (const auto& stage : instance_info_.stages()) {
7476
0
        std::stringstream ss;
7477
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
7478
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
7479
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
7480
0
           << ", prefix=" << stage.obj_info().prefix();
7481
7482
0
        if (stopped()) {
7483
0
            break;
7484
0
        }
7485
0
        if (stage.type() == StagePB::EXTERNAL) {
7486
0
            continue;
7487
0
        }
7488
0
        int idx = stoi(stage.obj_info().id());
7489
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7490
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
7491
0
            continue;
7492
0
        }
7493
7494
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7495
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7496
0
        if (!s3_conf) {
7497
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
7498
0
            continue;
7499
0
        }
7500
7501
0
        s3_conf->prefix = stage.obj_info().prefix();
7502
0
        std::shared_ptr<S3Accessor> accessor;
7503
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
7504
0
        if (ret1 != 0) {
7505
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
7506
0
            ret = -1;
7507
0
            continue;
7508
0
        }
7509
7510
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7511
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
7512
0
            ret = -1;
7513
0
            continue;
7514
0
        }
7515
7516
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
7517
0
        int64_t expiration_time =
7518
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
7519
0
                config::internal_stage_objects_expire_time_second;
7520
0
        if (config::force_immediate_recycle) {
7521
0
            expiration_time = INT64_MAX;
7522
0
        }
7523
0
        ret1 = accessor->delete_all(expiration_time);
7524
0
        if (ret1 != 0) {
7525
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
7526
0
                         << ss.str();
7527
0
            ret = -1;
7528
0
            continue;
7529
0
        }
7530
0
        metrics_context.total_recycled_num++;
7531
0
        metrics_context.report();
7532
0
    }
7533
10
    return ret;
7534
10
}
7535
7536
235
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
7537
235
    std::lock_guard lock(recycle_tasks_mutex);
7538
235
    running_recycle_tasks[task_name] = start_time;
7539
235
}
7540
7541
235
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
7542
235
    std::lock_guard lock(recycle_tasks_mutex);
7543
235
    DCHECK(running_recycle_tasks[task_name] > 0);
7544
235
    running_recycle_tasks.erase(task_name);
7545
235
}
7546
7547
3
bool InstanceRecycler::check_recycle_tasks() {
7548
3
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
7549
3
    {
7550
3
        std::lock_guard lock(recycle_tasks_mutex);
7551
3
        tmp_running_recycle_tasks = running_recycle_tasks;
7552
3
    }
7553
7554
3
    bool found = false;
7555
3
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7556
3
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
7557
2
        int64_t cost = now - start_time;
7558
2
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
7559
2
            LOG_INFO("recycle task cost too much time cost={}s", cost)
7560
2
                    .tag("instance_id", instance_id_)
7561
2
                    .tag("task", task_name);
7562
2
            found = true;
7563
2
        }
7564
2
    }
7565
7566
3
    return found;
7567
3
}
7568
7569
// Scan and statistics indexes that need to be recycled
7570
1
int InstanceRecycler::scan_and_statistics_indexes() {
7571
1
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
7572
1
    RecyclerMetricsContext stream_metrics_context(instance_id_, "recycle_stream");
7573
7574
1
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
7575
1
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
7576
1
    std::string index_key0;
7577
1
    std::string index_key1;
7578
1
    recycle_index_key(index_key_info0, &index_key0);
7579
1
    recycle_index_key(index_key_info1, &index_key1);
7580
1
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7581
7582
1
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7583
1
        RecycleIndexPB index_pb;
7584
1
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7585
0
            return 0;
7586
0
        }
7587
1
        int64_t current_time = ::time(nullptr);
7588
1
        if (current_time <
7589
1
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7590
0
            return 0;
7591
0
        }
7592
        // decode index_id
7593
1
        auto k1 = k;
7594
1
        k1.remove_prefix(1);
7595
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7596
1
        decode_key(&k1, &out);
7597
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7598
1
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7599
1
        std::unique_ptr<Transaction> txn;
7600
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7601
1
        if (err != TxnErrorCode::TXN_OK) {
7602
0
            return 0;
7603
0
        }
7604
1
        std::string val;
7605
1
        err = txn->get(k, &val);
7606
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7607
0
            return 0;
7608
0
        }
7609
1
        if (err != TxnErrorCode::TXN_OK) {
7610
0
            return 0;
7611
0
        }
7612
1
        index_pb.Clear();
7613
1
        if (!index_pb.ParseFromString(val)) {
7614
0
            return 0;
7615
0
        }
7616
1
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
7617
1
            if (!index_pb.has_db_id() || !index_pb.has_stream_db_id()) {
7618
0
                LOG_WARNING("table stream recycle index is missing binding")
7619
0
                        .tag("instance_id", instance_id_)
7620
0
                        .tag("stream_id", index_id);
7621
0
                return 0;
7622
0
            }
7623
2
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7624
2
                std::string end = prefix;
7625
2
                end.push_back('\xff');
7626
2
                auto count_offset = [&stream_metrics_context](std::string_view key,
7627
6
                                                              std::string_view value) {
7628
6
                    stream_metrics_context.total_need_recycle_num++;
7629
6
                    stream_metrics_context.total_need_recycle_data_size +=
7630
6
                            key.size() + value.size();
7631
6
                    return 0;
7632
6
                };
Unexecuted instantiation: recycler.cpp:_ZZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_ENKUlS6_S6_E_clES6_S6_
recycler_test.cpp:_ZZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_ENKUlS6_S6_E_clES6_S6_
Line
Count
Source
7627
6
                                                              std::string_view value) {
7628
6
                    stream_metrics_context.total_need_recycle_num++;
7629
6
                    stream_metrics_context.total_need_recycle_data_size +=
7630
6
                            key.size() + value.size();
7631
6
                    return 0;
7632
6
                };
7633
2
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7634
2
            };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_
Line
Count
Source
7623
2
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7624
2
                std::string end = prefix;
7625
2
                end.push_back('\xff');
7626
2
                auto count_offset = [&stream_metrics_context](std::string_view key,
7627
2
                                                              std::string_view value) {
7628
2
                    stream_metrics_context.total_need_recycle_num++;
7629
2
                    stream_metrics_context.total_need_recycle_data_size +=
7630
2
                            key.size() + value.size();
7631
2
                    return 0;
7632
2
                };
7633
2
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7634
2
            };
7635
1
            const std::string latest_prefix = table_stream_offset_key_prefix(
7636
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7637
1
                    index_id);
7638
1
            const std::string versioned_prefix = versioned::table_stream_offset_key_prefix(
7639
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7640
1
                    index_id);
7641
1
            if (scan_offset_prefix(latest_prefix) != 0 ||
7642
1
                scan_offset_prefix(versioned_prefix) != 0) {
7643
0
                LOG_WARNING("failed to scan table stream offsets for recycle statistics")
7644
0
                        .tag("instance_id", instance_id_)
7645
0
                        .tag("stream_id", index_id);
7646
0
            }
7647
1
            return 0;
7648
1
        }
7649
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7650
0
            return 0;
7651
0
        }
7652
0
        metrics_context.total_need_recycle_num++;
7653
0
        return 0;
7654
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7582
1
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7583
1
        RecycleIndexPB index_pb;
7584
1
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7585
0
            return 0;
7586
0
        }
7587
1
        int64_t current_time = ::time(nullptr);
7588
1
        if (current_time <
7589
1
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7590
0
            return 0;
7591
0
        }
7592
        // decode index_id
7593
1
        auto k1 = k;
7594
1
        k1.remove_prefix(1);
7595
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7596
1
        decode_key(&k1, &out);
7597
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7598
1
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7599
1
        std::unique_ptr<Transaction> txn;
7600
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7601
1
        if (err != TxnErrorCode::TXN_OK) {
7602
0
            return 0;
7603
0
        }
7604
1
        std::string val;
7605
1
        err = txn->get(k, &val);
7606
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7607
0
            return 0;
7608
0
        }
7609
1
        if (err != TxnErrorCode::TXN_OK) {
7610
0
            return 0;
7611
0
        }
7612
1
        index_pb.Clear();
7613
1
        if (!index_pb.ParseFromString(val)) {
7614
0
            return 0;
7615
0
        }
7616
1
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
7617
1
            if (!index_pb.has_db_id() || !index_pb.has_stream_db_id()) {
7618
0
                LOG_WARNING("table stream recycle index is missing binding")
7619
0
                        .tag("instance_id", instance_id_)
7620
0
                        .tag("stream_id", index_id);
7621
0
                return 0;
7622
0
            }
7623
1
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7624
1
                std::string end = prefix;
7625
1
                end.push_back('\xff');
7626
1
                auto count_offset = [&stream_metrics_context](std::string_view key,
7627
1
                                                              std::string_view value) {
7628
1
                    stream_metrics_context.total_need_recycle_num++;
7629
1
                    stream_metrics_context.total_need_recycle_data_size +=
7630
1
                            key.size() + value.size();
7631
1
                    return 0;
7632
1
                };
7633
1
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7634
1
            };
7635
1
            const std::string latest_prefix = table_stream_offset_key_prefix(
7636
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7637
1
                    index_id);
7638
1
            const std::string versioned_prefix = versioned::table_stream_offset_key_prefix(
7639
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7640
1
                    index_id);
7641
1
            if (scan_offset_prefix(latest_prefix) != 0 ||
7642
1
                scan_offset_prefix(versioned_prefix) != 0) {
7643
0
                LOG_WARNING("failed to scan table stream offsets for recycle statistics")
7644
0
                        .tag("instance_id", instance_id_)
7645
0
                        .tag("stream_id", index_id);
7646
0
            }
7647
1
            return 0;
7648
1
        }
7649
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7650
0
            return 0;
7651
0
        }
7652
0
        metrics_context.total_need_recycle_num++;
7653
0
        return 0;
7654
0
    };
7655
7656
1
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
7657
1
    metrics_context.report(true);
7658
1
    stream_metrics_context.report(true);
7659
1
    segment_metrics_context_.report(true);
7660
1
    tablet_metrics_context_.report(true);
7661
1
    return ret;
7662
1
}
7663
7664
// Scan and statistics partitions that need to be recycled
7665
0
int InstanceRecycler::scan_and_statistics_partitions() {
7666
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
7667
7668
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
7669
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
7670
0
    std::string part_key0;
7671
0
    std::string part_key1;
7672
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7673
7674
0
    recycle_partition_key(part_key_info0, &part_key0);
7675
0
    recycle_partition_key(part_key_info1, &part_key1);
7676
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
7677
0
        RecyclePartitionPB part_pb;
7678
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
7679
0
            return 0;
7680
0
        }
7681
0
        int64_t current_time = ::time(nullptr);
7682
0
        if (current_time <
7683
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
7684
0
            return 0;
7685
0
        }
7686
        // decode partition_id
7687
0
        auto k1 = k;
7688
0
        k1.remove_prefix(1);
7689
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7690
0
        decode_key(&k1, &out);
7691
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
7692
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
7693
        // Change state to RECYCLING
7694
0
        std::unique_ptr<Transaction> txn;
7695
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7696
0
        if (err != TxnErrorCode::TXN_OK) {
7697
0
            return 0;
7698
0
        }
7699
0
        std::string val;
7700
0
        err = txn->get(k, &val);
7701
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7702
0
            return 0;
7703
0
        }
7704
0
        if (err != TxnErrorCode::TXN_OK) {
7705
0
            return 0;
7706
0
        }
7707
0
        part_pb.Clear();
7708
0
        if (!part_pb.ParseFromString(val)) {
7709
0
            return 0;
7710
0
        }
7711
        // Partitions with PREPARED state MUST have no data
7712
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
7713
0
        int ret = 0;
7714
0
        for (int64_t index_id : part_pb.index_id()) {
7715
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
7716
0
                                            partition_id, is_empty_tablet) != 0) {
7717
0
                ret = 0;
7718
0
            }
7719
0
        }
7720
0
        metrics_context.total_need_recycle_num++;
7721
0
        return ret;
7722
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_
7723
7724
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
7725
0
    metrics_context.report(true);
7726
0
    segment_metrics_context_.report(true);
7727
0
    tablet_metrics_context_.report(true);
7728
0
    return ret;
7729
0
}
7730
7731
// Scan and statistics rowsets that need to be recycled
7732
0
int InstanceRecycler::scan_and_statistics_rowsets() {
7733
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
7734
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
7735
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
7736
0
    std::string recyc_rs_key0;
7737
0
    std::string recyc_rs_key1;
7738
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
7739
0
                recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
7740
0
       int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7741
7742
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
7743
0
        RecycleRowsetPB rowset;
7744
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7745
0
            return 0;
7746
0
        }
7747
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
7748
0
        int64_t current_time = ::time(nullptr);
7749
0
        if (current_time <
7750
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
7751
0
            return 0;
7752
0
        }
7753
7754
0
        if (!rowset.has_type()) {
7755
0
            if (!rowset.has_resource_id()) [[unlikely]] {
7756
0
                return 0;
7757
0
            }
7758
0
            if (rowset.resource_id().empty()) [[unlikely]] {
7759
0
                return 0;
7760
0
            }
7761
0
            metrics_context.total_need_recycle_num++;
7762
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7763
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
7764
0
            segment_metrics_context_.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7765
0
            return 0;
7766
0
        }
7767
7768
0
        if(!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled()) {
7769
0
            return 0;
7770
0
        }
7771
7772
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
7773
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
7774
0
                return 0;
7775
0
            }
7776
0
        }
7777
0
        metrics_context.total_need_recycle_num++;
7778
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
7779
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
7780
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
7781
0
        return 0;
7782
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_
7783
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
7784
0
    metrics_context.report(true);
7785
0
    segment_metrics_context_.report(true);
7786
0
    return ret;
7787
0
}
7788
7789
// Scan and statistics tmp_rowsets that need to be recycled
7790
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
7791
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
7792
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
7793
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
7794
0
    std::string tmp_rs_key0;
7795
0
    std::string tmp_rs_key1;
7796
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
7797
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
7798
7799
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7800
7801
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
7802
0
        doris::RowsetMetaCloudPB rowset;
7803
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7804
0
            return 0;
7805
0
        }
7806
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
7807
0
        int64_t current_time = ::time(nullptr);
7808
0
        if (current_time < expiration) {
7809
0
            return 0;
7810
0
        }
7811
7812
0
        DCHECK_GT(rowset.txn_id(), 0)
7813
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
7814
7815
0
        if(!rowset.has_is_recycled() || !rowset.is_recycled()) {
7816
0
            return 0;
7817
0
        }
7818
7819
0
        if (!rowset.has_resource_id()) {
7820
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
7821
0
                return 0;
7822
0
            }
7823
0
            return 0;
7824
0
        }
7825
7826
0
        metrics_context.total_need_recycle_num++;
7827
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
7828
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
7829
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
7830
0
        return 0;
7831
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_
7832
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
7833
0
    metrics_context.report(true);
7834
0
    segment_metrics_context_.report(true);
7835
0
    return ret;
7836
0
}
7837
7838
// Scan and statistics abort_timeout_txn that need to be recycled
7839
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
7840
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
7841
7842
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
7843
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7844
0
    std::string begin_txn_running_key;
7845
0
    std::string end_txn_running_key;
7846
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
7847
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
7848
7849
0
    int64_t current_time =
7850
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7851
7852
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
7853
0
                                               std::string_view k, std::string_view v) -> int {
7854
0
        std::unique_ptr<Transaction> txn;
7855
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7856
0
        if (err != TxnErrorCode::TXN_OK) {
7857
0
            return 0;
7858
0
        }
7859
0
        std::string_view k1 = k;
7860
0
        k1.remove_prefix(1);
7861
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7862
0
        if (decode_key(&k1, &out) != 0) {
7863
0
            return 0;
7864
0
        }
7865
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7866
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7867
        // Update txn_info
7868
0
        std::string txn_inf_key, txn_inf_val;
7869
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
7870
0
        err = txn->get(txn_inf_key, &txn_inf_val);
7871
0
        if (err != TxnErrorCode::TXN_OK) {
7872
0
            return 0;
7873
0
        }
7874
0
        TxnInfoPB txn_info;
7875
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
7876
0
            return 0;
7877
0
        }
7878
7879
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
7880
0
            TxnRunningPB txn_running_pb;
7881
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7882
0
                return 0;
7883
0
            }
7884
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7885
0
                return 0;
7886
0
            }
7887
0
            metrics_context.total_need_recycle_num++;
7888
0
        }
7889
0
        return 0;
7890
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_
7891
7892
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key, std::move(handle_abort_timeout_txn_kv));
7893
0
    metrics_context.report(true);
7894
0
    return ret;
7895
0
}
7896
7897
// Scan and statistics expired_txn_label that need to be recycled
7898
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
7899
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
7900
7901
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7902
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7903
0
    std::string begin_recycle_txn_key;
7904
0
    std::string end_recycle_txn_key;
7905
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7906
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7907
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7908
0
    int64_t current_time_ms =
7909
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7910
7911
    // for calculate the total num or bytes of recyled objects
7912
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
7913
0
        RecycleTxnPB recycle_txn_pb;
7914
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7915
0
            return 0;
7916
0
        }
7917
0
        if ((config::force_immediate_recycle) ||
7918
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7919
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7920
0
             current_time_ms)) {
7921
0
            metrics_context.total_need_recycle_num++;
7922
0
        }
7923
0
        return 0;
7924
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_
7925
7926
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key, std::move(handle_expired_txn_label_kv));
7927
0
    metrics_context.report(true);
7928
0
    return ret;
7929
0
}
7930
7931
// Scan and statistics copy_jobs that need to be recycled
7932
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
7933
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
7934
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7935
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7936
0
    std::string key0;
7937
0
    std::string key1;
7938
0
    copy_job_key(key_info0, &key0);
7939
0
    copy_job_key(key_info1, &key1);
7940
7941
    // for calculate the total num or bytes of recyled objects
7942
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
7943
0
        CopyJobPB copy_job;
7944
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7945
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7946
0
            return 0;
7947
0
        }
7948
7949
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7950
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
7951
0
                int64_t current_time =
7952
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7953
0
                if (copy_job.finish_time_ms() > 0) {
7954
0
                    if (!config::force_immediate_recycle &&
7955
0
                        current_time < copy_job.finish_time_ms() +
7956
0
                                               config::copy_job_max_retention_second * 1000) {
7957
0
                        return 0;
7958
0
                    }
7959
0
                } else {
7960
0
                    if (!config::force_immediate_recycle &&
7961
0
                        current_time < copy_job.start_time_ms() +
7962
0
                                               config::copy_job_max_retention_second * 1000) {
7963
0
                        return 0;
7964
0
                    }
7965
0
                }
7966
0
            }
7967
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7968
0
            int64_t current_time =
7969
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7970
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7971
0
                return 0;
7972
0
            }
7973
0
        }
7974
0
        metrics_context.total_need_recycle_num++;
7975
0
        return 0;
7976
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_
7977
7978
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7979
0
    metrics_context.report(true);
7980
0
    return ret;
7981
0
}
7982
7983
// Scan and statistics stage that need to be recycled
7984
0
int InstanceRecycler::scan_and_statistics_stage() {
7985
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
7986
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7987
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7988
0
    std::string key0 = recycle_stage_key(key_info0);
7989
0
    std::string key1 = recycle_stage_key(key_info1);
7990
7991
    // for calculate the total num or bytes of recyled objects
7992
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
7993
0
                                                        std::string_view v) -> int {
7994
0
        RecycleStagePB recycle_stage;
7995
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7996
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7997
0
            return 0;
7998
0
        }
7999
8000
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
8001
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
8002
0
            LOG(WARNING) << "invalid idx: " << idx;
8003
0
            return 0;
8004
0
        }
8005
8006
0
        std::shared_ptr<StorageVaultAccessor> accessor;
8007
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
8008
0
                [&] {
8009
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
8010
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8011
0
                    if (!s3_conf) {
8012
0
                        return 0;
8013
0
                    }
8014
8015
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
8016
0
                    std::shared_ptr<S3Accessor> s3_accessor;
8017
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
8018
0
                    if (ret != 0) {
8019
0
                        return 0;
8020
0
                    }
8021
8022
0
                    accessor = std::move(s3_accessor);
8023
0
                    return 0;
8024
0
                }(),
8025
0
                "recycle_stage:get_accessor", &accessor);
8026
8027
0
        if (ret != 0) {
8028
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
8029
0
            return 0;
8030
0
        }
8031
8032
0
        metrics_context.total_need_recycle_num++;
8033
0
        return 0;
8034
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_
8035
8036
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
8037
0
    metrics_context.report(true);
8038
0
    return ret;
8039
0
}
8040
8041
// Scan and statistics expired_stage_objects that need to be recycled
8042
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
8043
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
8044
8045
    // for calculate the total num or bytes of recyled objects
8046
0
    auto scan_and_statistics = [&metrics_context, this]() {
8047
0
        for (const auto& stage : instance_info_.stages()) {
8048
0
            if (stopped()) {
8049
0
                break;
8050
0
            }
8051
0
            if (stage.type() == StagePB::EXTERNAL) {
8052
0
                continue;
8053
0
            }
8054
0
            int idx = stoi(stage.obj_info().id());
8055
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
8056
0
                continue;
8057
0
            }
8058
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
8059
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8060
0
            if (!s3_conf) {
8061
0
                continue;
8062
0
            }
8063
0
            s3_conf->prefix = stage.obj_info().prefix();
8064
0
            std::shared_ptr<S3Accessor> accessor;
8065
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
8066
0
            if (ret1 != 0) {
8067
0
                continue;
8068
0
            }
8069
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
8070
0
                continue;
8071
0
            }
8072
0
            metrics_context.total_need_recycle_num++;
8073
0
        }
8074
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
8075
8076
0
    scan_and_statistics();
8077
0
    metrics_context.report(true);
8078
0
    return 0;
8079
0
}
8080
8081
// Scan and statistics versions that need to be recycled
8082
0
int InstanceRecycler::scan_and_statistics_versions() {
8083
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
8084
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
8085
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
8086
8087
0
    int64_t last_scanned_table_id = 0;
8088
0
    bool is_recycled = false; // Is last scanned kv recycled
8089
    // for calculate the total num or bytes of recyled objects
8090
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
8091
0
                                       std::string_view k, std::string_view) {
8092
0
        auto k1 = k;
8093
0
        k1.remove_prefix(1);
8094
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
8095
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8096
0
        decode_key(&k1, &out);
8097
0
        DCHECK_EQ(out.size(), 6) << k;
8098
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
8099
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
8100
0
            metrics_context.total_need_recycle_num +=
8101
0
                    is_recycled; // Version kv of this table has been recycled
8102
0
            return 0;
8103
0
        }
8104
0
        last_scanned_table_id = table_id;
8105
0
        is_recycled = false;
8106
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
8107
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
8108
0
        std::unique_ptr<Transaction> txn;
8109
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8110
0
        if (err != TxnErrorCode::TXN_OK) {
8111
0
            return 0;
8112
0
        }
8113
0
        std::unique_ptr<RangeGetIterator> iter;
8114
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
8115
0
        if (err != TxnErrorCode::TXN_OK) {
8116
0
            return 0;
8117
0
        }
8118
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
8119
0
            return 0;
8120
0
        }
8121
0
        metrics_context.total_need_recycle_num++;
8122
0
        is_recycled = true;
8123
0
        return 0;
8124
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_
8125
8126
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
8127
0
    metrics_context.report(true);
8128
0
    return ret;
8129
0
}
8130
8131
// Scan and statistics restore jobs that need to be recycled
8132
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
8133
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
8134
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
8135
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
8136
0
    std::string restore_job_key0;
8137
0
    std::string restore_job_key1;
8138
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
8139
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
8140
8141
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8142
8143
    // for calculate the total num or bytes of recyled objects
8144
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
8145
0
        RestoreJobCloudPB restore_job_pb;
8146
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
8147
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
8148
0
            return 0;
8149
0
        }
8150
0
        int64_t expiration =
8151
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
8152
0
        int64_t current_time = ::time(nullptr);
8153
0
        if (current_time < expiration) { // not expired
8154
0
            return 0;
8155
0
        }
8156
0
        metrics_context.total_need_recycle_num++;
8157
0
        if(restore_job_pb.need_recycle_data()) {
8158
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
8159
0
        }
8160
0
        return 0;
8161
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_
8162
8163
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
8164
0
    metrics_context.report(true);
8165
0
    return ret;
8166
0
}
8167
8168
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
8169
3
    if (!should_recycle_versioned_keys()) {
8170
0
        return;
8171
0
    }
8172
8173
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
8174
8175
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
8176
3
    if (recycle_checker.init() != 0) {
8177
0
        return;
8178
0
    }
8179
8180
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
8181
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
8182
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
8183
8184
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
8185
8
    for (; iter->valid(); iter->next()) {
8186
5
        OperationLogPB operation_log;
8187
5
        if (!iter->parse_value(&operation_log)) {
8188
0
            continue;
8189
0
        }
8190
8191
5
        std::string_view key = iter->key();
8192
5
        Versionstamp log_versionstamp;
8193
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
8194
0
            continue;
8195
0
        }
8196
8197
5
        OperationLogReferenceInfo ref_info;
8198
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
8199
5
                                         &ref_info)) {
8200
4
            metrics_context.total_need_recycle_num++;
8201
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
8202
4
        }
8203
5
    }
8204
8205
3
    metrics_context.report(true);
8206
3
}
8207
8208
int InstanceRecycler::classify_rowset_task_by_ref_count(
8209
60
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
8210
60
    constexpr int MAX_RETRY = 10;
8211
60
    const auto& rowset_meta = task.rowset_meta;
8212
60
    int64_t tablet_id = rowset_meta.tablet_id();
8213
60
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
8214
60
    std::string_view reference_instance_id = instance_id_;
8215
60
    if (rowset_meta.has_reference_instance_id()) {
8216
5
        reference_instance_id = rowset_meta.reference_instance_id();
8217
5
    }
8218
8219
61
    for (int i = 0; i < MAX_RETRY; ++i) {
8220
61
        std::unique_ptr<Transaction> txn;
8221
61
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8222
61
        if (err != TxnErrorCode::TXN_OK) {
8223
0
            LOG_WARNING("failed to create txn when classifying rowset task")
8224
0
                    .tag("instance_id", instance_id_)
8225
0
                    .tag("tablet_id", tablet_id)
8226
0
                    .tag("rowset_id", rowset_id)
8227
0
                    .tag("err", err);
8228
0
            return -1;
8229
0
        }
8230
8231
61
        std::string rowset_ref_count_key =
8232
61
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
8233
61
        task.rowset_ref_count_key = rowset_ref_count_key;
8234
8235
61
        int64_t ref_count = 0;
8236
61
        {
8237
61
            std::string value;
8238
61
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
8239
61
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
8240
0
                ref_count = 1;
8241
61
            } else if (err != TxnErrorCode::TXN_OK) {
8242
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
8243
0
                        .tag("instance_id", instance_id_)
8244
0
                        .tag("tablet_id", tablet_id)
8245
0
                        .tag("rowset_id", rowset_id)
8246
0
                        .tag("err", err);
8247
0
                return -1;
8248
61
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
8249
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
8250
0
                        .tag("instance_id", instance_id_)
8251
0
                        .tag("tablet_id", tablet_id)
8252
0
                        .tag("rowset_id", rowset_id)
8253
0
                        .tag("value", hex(value));
8254
0
                return -1;
8255
0
            }
8256
61
        }
8257
8258
61
        if (ref_count > 1) {
8259
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
8260
12
            txn->atomic_add(rowset_ref_count_key, -1);
8261
12
            LOG_INFO("decrease rowset data ref count in classification phase")
8262
12
                    .tag("instance_id", instance_id_)
8263
12
                    .tag("tablet_id", tablet_id)
8264
12
                    .tag("rowset_id", rowset_id)
8265
12
                    .tag("ref_count", ref_count - 1)
8266
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
8267
8268
12
            if (!task.recycle_rowset_key.empty()) {
8269
0
                txn->remove(task.recycle_rowset_key);
8270
0
                LOG_INFO("remove recycle rowset key in classification phase")
8271
0
                        .tag("key", hex(task.recycle_rowset_key));
8272
0
            }
8273
12
            if (!task.non_versioned_rowset_key.empty()) {
8274
12
                txn->remove(task.non_versioned_rowset_key);
8275
12
                LOG_INFO("remove non versioned rowset key in classification phase")
8276
12
                        .tag("key", hex(task.non_versioned_rowset_key));
8277
12
            }
8278
8279
12
            err = txn->commit();
8280
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
8281
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
8282
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
8283
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
8284
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
8285
1
                continue;
8286
11
            } else if (err != TxnErrorCode::TXN_OK) {
8287
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
8288
0
                        .tag("instance_id", instance_id_)
8289
0
                        .tag("tablet_id", tablet_id)
8290
0
                        .tag("rowset_id", rowset_id)
8291
0
                        .tag("err", err);
8292
0
                return -1;
8293
0
            }
8294
11
            return 1; // handled, not added to batch delete
8295
49
        } else {
8296
            // ref_count == 1: Add to batch delete plan without modifying any KV.
8297
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
8298
49
            LOG_INFO("add rowset to batch delete plan")
8299
49
                    .tag("instance_id", instance_id_)
8300
49
                    .tag("tablet_id", tablet_id)
8301
49
                    .tag("rowset_id", rowset_id)
8302
49
                    .tag("resource_id", rowset_meta.resource_id())
8303
49
                    .tag("ref_count", ref_count);
8304
8305
49
            batch_delete_tasks.push_back(std::move(task));
8306
49
            return 0; // added to batch delete
8307
49
        }
8308
61
    }
8309
8310
0
    LOG_WARNING("failed to classify rowset task after retry")
8311
0
            .tag("instance_id", instance_id_)
8312
0
            .tag("tablet_id", tablet_id)
8313
0
            .tag("rowset_id", rowset_id)
8314
0
            .tag("retry", MAX_RETRY);
8315
0
    return -1;
8316
60
}
8317
8318
10
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
8319
10
    int ret = 0;
8320
49
    for (const auto& task : tasks) {
8321
49
        int64_t tablet_id = task.rowset_meta.tablet_id();
8322
49
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
8323
8324
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
8325
        // so we don't need to call it again here.
8326
8327
        // Remove all metadata keys in one transaction
8328
49
        std::unique_ptr<Transaction> txn;
8329
49
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8330
49
        if (err != TxnErrorCode::TXN_OK) {
8331
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
8332
0
                    .tag("instance_id", instance_id_)
8333
0
                    .tag("tablet_id", tablet_id)
8334
0
                    .tag("rowset_id", rowset_id)
8335
0
                    .tag("err", err);
8336
0
            ret = -1;
8337
0
            continue;
8338
0
        }
8339
8340
49
        std::string_view reference_instance_id = instance_id_;
8341
49
        if (task.rowset_meta.has_reference_instance_id()) {
8342
5
            reference_instance_id = task.rowset_meta.reference_instance_id();
8343
5
        }
8344
8345
49
        txn->remove(task.rowset_ref_count_key);
8346
49
        LOG_INFO("delete rowset data ref count key in cleanup phase")
8347
49
                .tag("instance_id", instance_id_)
8348
49
                .tag("tablet_id", tablet_id)
8349
49
                .tag("rowset_id", rowset_id)
8350
49
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
8351
8352
49
        std::string dbm_start_key =
8353
49
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
8354
49
        std::string dbm_end_key = meta_delete_bitmap_key(
8355
49
                {reference_instance_id, tablet_id, rowset_id,
8356
49
                 std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
8357
49
        txn->remove(dbm_start_key, dbm_end_key);
8358
49
        LOG_INFO("remove delete bitmap kv in cleanup phase")
8359
49
                .tag("instance_id", instance_id_)
8360
49
                .tag("tablet_id", tablet_id)
8361
49
                .tag("rowset_id", rowset_id)
8362
49
                .tag("begin", hex(dbm_start_key))
8363
49
                .tag("end", hex(dbm_end_key));
8364
8365
49
        std::string versioned_dbm_start_key =
8366
49
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
8367
49
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
8368
49
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
8369
49
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
8370
49
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
8371
49
                .tag("instance_id", instance_id_)
8372
49
                .tag("tablet_id", tablet_id)
8373
49
                .tag("rowset_id", rowset_id)
8374
49
                .tag("begin", hex(versioned_dbm_start_key))
8375
49
                .tag("end", hex(versioned_dbm_end_key));
8376
8377
        // Remove versioned meta rowset key
8378
49
        if (!task.versioned_rowset_key.empty()) {
8379
49
            versioned::document_remove<RowsetMetaCloudPB>(
8380
49
                txn.get(), task.versioned_rowset_key, task.versionstamp);
8381
49
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
8382
49
                    .tag("instance_id", instance_id_)
8383
49
                    .tag("tablet_id", tablet_id)
8384
49
                    .tag("rowset_id", rowset_id)
8385
49
                    .tag("key_prefix", hex(task.versioned_rowset_key));
8386
49
        }
8387
8388
49
        if (!task.non_versioned_rowset_key.empty()) {
8389
49
            txn->remove(task.non_versioned_rowset_key);
8390
49
            LOG_INFO("remove non versioned rowset key in cleanup phase")
8391
49
                    .tag("instance_id", instance_id_)
8392
49
                    .tag("tablet_id", tablet_id)
8393
49
                    .tag("rowset_id", rowset_id)
8394
49
                    .tag("key", hex(task.non_versioned_rowset_key));
8395
49
        }
8396
8397
        // Remove recycle_rowset_key last to ensure retry safety:
8398
        // if cleanup fails, this key remains and triggers next round retry.
8399
49
        if (!task.recycle_rowset_key.empty()) {
8400
0
            txn->remove(task.recycle_rowset_key);
8401
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
8402
0
                    .tag("instance_id", instance_id_)
8403
0
                    .tag("tablet_id", tablet_id)
8404
0
                    .tag("rowset_id", rowset_id)
8405
0
                    .tag("key", hex(task.recycle_rowset_key));
8406
0
        }
8407
8408
49
        err = txn->commit();
8409
49
        if (err != TxnErrorCode::TXN_OK) {
8410
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
8411
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
8412
0
                    .tag("instance_id", instance_id_)
8413
0
                    .tag("tablet_id", tablet_id)
8414
0
                    .tag("rowset_id", rowset_id)
8415
0
                    .tag("err", err);
8416
0
            ret = -1;
8417
0
            continue;
8418
0
        }
8419
8420
49
        LOG_INFO("cleanup rowset metadata success")
8421
49
                .tag("instance_id", instance_id_)
8422
49
                .tag("tablet_id", tablet_id)
8423
49
                .tag("rowset_id", rowset_id);
8424
49
    }
8425
10
    return ret;
8426
10
}
8427
8428
} // namespace doris::cloud