Coverage Report

Created: 2026-08-19 01:31

/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
868k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
102
868k
    const auto& locations = rowset.packed_slice_locations();
103
868k
    auto it = locations.find(path);
104
868k
    return it != locations.end() && it->second.has_packed_file_path() &&
105
868k
           !it->second.packed_file_path().empty();
106
868k
}
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
868k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
102
868k
    const auto& locations = rowset.packed_slice_locations();
103
868k
    auto it = locations.find(path);
104
868k
    return it != locations.end() && it->second.has_packed_file_path() &&
105
868k
           !it->second.packed_file_path().empty();
106
868k
}
107
108
void add_file_to_delete_if_not_packed(const doris::RowsetMetaCloudPB& rowset,
109
                                      const std::string& path,
110
866k
                                      std::vector<std::string>* file_paths) {
111
867k
    if (!is_packed_slice_path(rowset, path)) {
112
867k
        file_paths->push_back(path);
113
867k
    }
114
866k
}
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
866k
                                      std::vector<std::string>* file_paths) {
111
867k
    if (!is_packed_slice_path(rowset, path)) {
112
867k
        file_paths->push_back(path);
113
867k
    }
114
866k
}
115
116
37
bool filter_out_instance(const std::string& instance_id) {
117
37
    if (config::recycle_whitelist.empty()) {
118
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
119
35
               config::recycle_blacklist.end();
120
35
    }
121
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
122
2
           config::recycle_whitelist.end();
123
37
}
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
37
bool filter_out_instance(const std::string& instance_id) {
117
37
    if (config::recycle_whitelist.empty()) {
118
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
119
35
               config::recycle_blacklist.end();
120
35
    }
121
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
122
2
           config::recycle_whitelist.end();
123
37
}
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
6
Recycler::Recycler(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
244
6
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
245
246
6
    auto s3_producer_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
247
6
                                                               "s3_producer_pool");
248
6
    s3_producer_pool->start();
249
6
    auto recycle_tablet_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
250
6
                                                                  "recycle_tablet_pool");
251
6
    recycle_tablet_pool->start();
252
6
    auto group_recycle_function_pool = std::make_shared<SimpleThreadPool>(
253
6
            config::recycle_pool_parallelism, "group_recycle_function_pool");
254
6
    group_recycle_function_pool->start();
255
6
    _thread_pool_group =
256
6
            RecyclerThreadPoolGroup(std::move(s3_producer_pool), std::move(recycle_tablet_pool),
257
6
                                    std::move(group_recycle_function_pool));
258
259
6
    auto resource_mgr = std::make_shared<ResourceManager>(txn_kv_);
260
6
    txn_lazy_committer_ = std::make_shared<TxnLazyCommitter>(txn_kv_, std::move(resource_mgr));
261
6
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
262
6
}
263
264
6
Recycler::~Recycler() {
265
6
    if (!stopped()) {
266
0
        stop();
267
0
    }
268
6
}
269
270
5
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
5
    std::this_thread::sleep_for(
275
5
            std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
276
1.32k
    while (!stopped()) {
277
1.31k
        if (config::enable_recycler) {
278
4
            std::vector<InstanceInfoPB> instances;
279
4
            get_all_instances(txn_kv_.get(), instances);
280
            // TODO(plat1ko): delete job recycle kv of non-existent instances
281
4
            LOG(INFO) << "Recycler get instances: " << [&instances] {
282
4
                std::stringstream ss;
283
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
284
4
                return ss.str();
285
4
            }();
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
Line
Count
Source
281
4
            LOG(INFO) << "Recycler get instances: " << [&instances] {
282
4
                std::stringstream ss;
283
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
284
4
                return ss.str();
285
4
            }();
286
4
            if (!instances.empty()) {
287
                // enqueue instances
288
3
                std::lock_guard lock(mtx_);
289
30
                for (auto& instance : instances) {
290
30
                    if (filter_out_instance(instance.instance_id())) continue;
291
30
                    auto [_, success] = pending_instance_set_.insert(instance.instance_id());
292
                    // skip instance already in pending queue
293
30
                    if (success) {
294
30
                        pending_instance_queue_.push_back(std::move(instance));
295
30
                    }
296
30
                }
297
3
                pending_instance_cond_.notify_all();
298
3
            }
299
1.31k
        } else {
300
1.31k
            LOG(WARNING) << "Skip recycler since enable_recycler is false";
301
1.31k
        }
302
1.31k
        {
303
1.31k
            std::unique_lock lock(mtx_);
304
1.31k
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
305
2.63k
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
305
2.63k
                               [&]() { return stopped(); });
306
1.31k
        }
307
1.31k
    }
308
5
}
309
310
9
void Recycler::recycle_callback() {
311
40
    while (!stopped()) {
312
38
        InstanceInfoPB instance;
313
38
        {
314
38
            std::unique_lock lock(mtx_);
315
38
            pending_instance_cond_.wait(
316
51
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
316
51
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
317
38
            if (stopped()) {
318
7
                return;
319
7
            }
320
31
            instance = std::move(pending_instance_queue_.front());
321
31
            pending_instance_queue_.pop_front();
322
31
            pending_instance_set_.erase(instance.instance_id());
323
31
        }
324
0
        auto& instance_id = instance.instance_id();
325
31
        {
326
31
            std::lock_guard lock(mtx_);
327
            // skip instance in recycling
328
31
            if (recycling_instance_map_.count(instance_id)) continue;
329
31
        }
330
31
        if (!config::enable_recycler) {
331
1
            LOG(WARNING) << "Skip recycle instance_id=" << instance_id
332
1
                         << " since enable_recycler is false";
333
1
            continue;
334
1
        }
335
30
        auto instance_recycler = std::make_shared<InstanceRecycler>(
336
30
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
337
338
30
        if (int r = instance_recycler->init(); r != 0) {
339
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
340
0
                         << " ret=" << r;
341
0
            continue;
342
0
        }
343
30
        std::string recycle_job_key;
344
30
        job_recycle_key({instance_id}, &recycle_job_key);
345
30
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
346
30
                                               ip_port_, config::recycle_interval_seconds * 1000);
347
30
        if (ret != 0) { // Prepare failed
348
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
349
20
                         << " ret=" << ret;
350
20
            continue;
351
20
        } else {
352
10
            std::lock_guard lock(mtx_);
353
10
            recycling_instance_map_.emplace(instance_id, instance_recycler);
354
10
        }
355
10
        if (stopped()) return;
356
10
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
357
10
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
358
10
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
359
10
        g_bvar_recycler_instance_recycle_task_status.put({"submitted"}, 1);
360
10
        ret = instance_recycler->do_recycle();
361
        // If instance recycler has been aborted, don't finish this job
362
363
10
        if (!instance_recycler->stopped()) {
364
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
365
10
                                        ret == 0, ctime_ms);
366
10
        }
367
10
        if (instance_recycler->stopped() || ret != 0) {
368
0
            g_bvar_recycler_instance_recycle_task_status.put({"error"}, 1);
369
0
        }
370
10
        {
371
10
            std::lock_guard lock(mtx_);
372
10
            recycling_instance_map_.erase(instance_id);
373
10
        }
374
375
10
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
376
10
        auto elpased_ms = now - ctime_ms;
377
10
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
378
10
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
379
10
        g_bvar_recycler_instance_next_ts.put({instance_id},
380
10
                                             now + config::recycle_interval_seconds * 1000);
381
10
        g_bvar_recycler_instance_recycle_task_status.put({"completed"}, 1);
382
10
        LOG(INFO) << "recycle instance done, "
383
10
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
384
10
                  << " now: " << now;
385
386
10
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
387
388
10
        LOG_WARNING("finish recycle instance")
389
10
                .tag("instance_id", instance_id)
390
10
                .tag("cost_ms", elpased_ms);
391
10
    }
392
9
}
393
394
4
void Recycler::lease_recycle_jobs() {
395
54
    while (!stopped()) {
396
50
        std::vector<std::string> instances;
397
50
        instances.reserve(recycling_instance_map_.size());
398
50
        {
399
50
            std::lock_guard lock(mtx_);
400
50
            for (auto& [id, _] : recycling_instance_map_) {
401
30
                instances.push_back(id);
402
30
            }
403
50
        }
404
50
        for (auto& i : instances) {
405
30
            std::string recycle_job_key;
406
30
            job_recycle_key({i}, &recycle_job_key);
407
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
408
30
            if (ret == 1) {
409
0
                std::lock_guard lock(mtx_);
410
0
                if (auto it = recycling_instance_map_.find(i);
411
0
                    it != recycling_instance_map_.end()) {
412
0
                    it->second->stop();
413
0
                }
414
0
            }
415
30
        }
416
50
        {
417
50
            std::unique_lock lock(mtx_);
418
50
            notifier_.wait_for(lock,
419
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
420
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
420
100
                               [&]() { return stopped(); });
421
50
        }
422
50
    }
423
4
}
424
425
4
void Recycler::check_recycle_tasks() {
426
7
    while (!stopped()) {
427
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
428
3
        {
429
3
            std::lock_guard lock(mtx_);
430
3
            recycling_instance_map = recycling_instance_map_;
431
3
        }
432
3
        for (auto& entry : recycling_instance_map) {
433
0
            entry.second->check_recycle_tasks();
434
0
        }
435
436
3
        std::unique_lock lock(mtx_);
437
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
438
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
438
6
                           [&]() { return stopped(); });
439
3
    }
440
4
}
441
442
4
int Recycler::start(brpc::Server* server) {
443
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
444
4
    S3Environment::getInstance();
445
446
4
    if (config::enable_checker) {
447
0
        checker_ = std::make_unique<Checker>(txn_kv_);
448
0
        int ret = checker_->start();
449
0
        std::string msg;
450
0
        if (ret != 0) {
451
0
            msg = "failed to start checker";
452
0
            LOG(ERROR) << msg;
453
0
            std::cerr << msg << std::endl;
454
0
            return ret;
455
0
        }
456
0
        msg = "checker started";
457
0
        LOG(INFO) << msg;
458
0
        std::cout << msg << std::endl;
459
0
    }
460
461
4
    if (server) {
462
        // Add service
463
1
        auto recycler_service =
464
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
465
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
466
1
    }
467
468
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
468
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
469
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
470
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
470
8
        workers_.emplace_back([this] { recycle_callback(); });
471
8
    }
472
473
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
474
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
475
476
4
    if (config::enable_snapshot_data_migrator) {
477
0
        snapshot_data_migrator_ = std::make_shared<SnapshotDataMigrator>(txn_kv_);
478
0
        int ret = snapshot_data_migrator_->start();
479
0
        if (ret != 0) {
480
0
            LOG(ERROR) << "failed to start snapshot data migrator";
481
0
            return ret;
482
0
        }
483
0
        LOG(INFO) << "snapshot data migrator started";
484
0
    }
485
486
4
    if (config::enable_snapshot_chain_compactor) {
487
0
        snapshot_chain_compactor_ = std::make_shared<SnapshotChainCompactor>(txn_kv_);
488
0
        int ret = snapshot_chain_compactor_->start();
489
0
        if (ret != 0) {
490
0
            LOG(ERROR) << "failed to start snapshot chain compactor";
491
0
            return ret;
492
0
        }
493
0
        LOG(INFO) << "snapshot chain compactor started";
494
0
    }
495
496
4
    return 0;
497
4
}
498
499
4
void Recycler::stop() {
500
4
    stopped_ = true;
501
4
    notifier_.notify_all();
502
4
    pending_instance_cond_.notify_all();
503
4
    {
504
4
        std::lock_guard lock(mtx_);
505
4
        for (auto& [_, recycler] : recycling_instance_map_) {
506
0
            recycler->stop();
507
0
        }
508
4
    }
509
20
    for (auto& w : workers_) {
510
20
        if (w.joinable()) w.join();
511
20
    }
512
4
    if (checker_) {
513
0
        checker_->stop();
514
0
    }
515
4
    if (snapshot_data_migrator_) {
516
0
        snapshot_data_migrator_->stop();
517
0
    }
518
4
    if (snapshot_chain_compactor_) {
519
0
        snapshot_chain_compactor_->stop();
520
0
    }
521
4
}
522
523
class InstanceRecycler::InvertedIndexIdCache {
524
public:
525
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
526
151
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
527
528
    // Return 0 if success, 1 if schema kv not found, negative for error
529
    // For the same index_id, schema_version, res, since `get` is not completely atomic
530
    // one thread has not finished inserting, and another thread has not get the index_id and schema_version,
531
    // resulting in repeated addition and inaccuracy.
532
    // however, this approach can reduce the lock range and sacrifice a bit of meta repeated get to improve concurrency performance.
533
    // repeated addition does not affect correctness.
534
28.4k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
535
28.4k
        {
536
28.4k
            std::lock_guard lock(mtx_);
537
28.4k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
538
4.70k
                return 0;
539
4.70k
            }
540
23.7k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
541
23.7k
                it != inverted_index_id_map_.end()) {
542
18.1k
                res = it->second;
543
18.1k
                return 0;
544
18.1k
            }
545
23.7k
        }
546
        // Get schema from kv
547
        // TODO(plat1ko): Single flight
548
5.54k
        std::unique_ptr<Transaction> txn;
549
5.54k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
550
5.54k
        if (err != TxnErrorCode::TXN_OK) {
551
0
            LOG(WARNING) << "failed to create txn, err=" << err;
552
0
            return -1;
553
0
        }
554
5.54k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
555
5.54k
        ValueBuf val_buf;
556
5.54k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
557
5.54k
        if (err != TxnErrorCode::TXN_OK) {
558
500
            LOG(WARNING) << "failed to get schema, err=" << err;
559
500
            return static_cast<int>(err);
560
500
        }
561
5.04k
        doris::TabletSchemaCloudPB schema;
562
5.04k
        if (!parse_schema_value(val_buf, &schema)) {
563
0
            LOG(WARNING) << "malformed schema value, key=" << hex(schema_key);
564
0
            return -1;
565
0
        }
566
5.04k
        if (schema.index_size() > 0) {
567
4.01k
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
568
4.01k
            if (schema.has_inverted_index_storage_format()) {
569
4.00k
                index_format = schema.inverted_index_storage_format();
570
4.00k
            }
571
4.01k
            res.first = index_format;
572
4.01k
            res.second.reserve(schema.index_size());
573
10.0k
            for (auto& i : schema.index()) {
574
10.0k
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
575
10.0k
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
576
10.0k
                }
577
10.0k
            }
578
4.01k
        }
579
5.04k
        insert(index_id, schema_version, res);
580
5.04k
        return 0;
581
5.04k
    }
582
583
    // Empty `ids` means this schema has no inverted index
584
5.04k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
585
5.04k
        if (index_info.second.empty()) {
586
1.03k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
587
1.03k
            std::lock_guard lock(mtx_);
588
1.03k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
589
4.01k
        } else {
590
4.01k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
591
4.01k
            std::lock_guard lock(mtx_);
592
4.01k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
593
4.01k
        }
594
5.04k
    }
595
596
private:
597
    std::string instance_id_;
598
    std::shared_ptr<TxnKv> txn_kv_;
599
600
    std::mutex mtx_;
601
    using Key = std::pair<int64_t, int32_t>; // <index_id, schema_version>
602
    struct HashOfKey {
603
57.2k
        size_t operator()(const Key& key) const {
604
57.2k
            size_t seed = 0;
605
57.2k
            seed = std::hash<int64_t> {}(key.first);
606
57.2k
            seed = std::hash<int32_t> {}(key.second);
607
57.2k
            return seed;
608
57.2k
        }
609
    };
610
    // <index_id, schema_version> -> inverted_index_ids
611
    std::unordered_map<Key, InvertedIndexInfo, HashOfKey> inverted_index_id_map_;
612
    // Store <index_id, schema_version> of schema which doesn't have inverted index
613
    std::unordered_set<Key, HashOfKey> schemas_without_inverted_index_;
614
};
615
616
InstanceRecycler::InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
617
                                   RecyclerThreadPoolGroup thread_pool_group,
618
                                   std::shared_ptr<TxnLazyCommitter> txn_lazy_committer)
619
        : txn_kv_(std::move(txn_kv)),
620
          instance_id_(instance.instance_id()),
621
          instance_info_(instance),
622
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
623
          _thread_pool_group(std::move(thread_pool_group)),
624
          txn_lazy_committer_(std::move(txn_lazy_committer)),
625
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
626
151
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
627
151
    delete_bitmap_lock_white_list_->init();
628
151
    resource_mgr_->init();
629
630
151
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
631
632
    // Since the recycler's resource manager could not be notified when instance info changes,
633
    // we need to refresh the instance info here to ensure the resource manager has the latest info.
634
151
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
635
151
};
636
637
151
InstanceRecycler::~InstanceRecycler() = default;
638
639
129
int InstanceRecycler::init_obj_store_accessors() {
640
129
    for (const auto& obj_info : instance_info_.obj_info()) {
641
86
#ifdef UNIT_TEST
642
86
        auto accessor = std::make_shared<MockAccessor>();
643
#else
644
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
645
        if (!s3_conf) {
646
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
647
            return -1;
648
        }
649
650
        std::shared_ptr<S3Accessor> accessor;
651
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
652
        if (ret != 0) {
653
            LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
654
                         << " resource_id=" << obj_info.id();
655
            return ret;
656
        }
657
#endif
658
86
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
659
86
    }
660
661
129
    return 0;
662
129
}
663
664
129
int InstanceRecycler::init_storage_vault_accessors() {
665
129
    if (instance_info_.resource_ids().empty()) {
666
122
        return 0;
667
122
    }
668
669
7
    FullRangeGetOptions opts(txn_kv_);
670
7
    opts.prefetch = true;
671
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
672
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
673
674
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
675
18
        auto [k, v] = *kv;
676
18
        StorageVaultPB vault;
677
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
678
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
679
0
            return -1;
680
0
        }
681
18
        std::string recycler_storage_vault_white_list = accumulate(
682
18
                config::recycler_storage_vault_white_list.begin(),
683
18
                config::recycler_storage_vault_white_list.end(), std::string(),
684
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
684
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
685
18
        LOG_INFO("config::recycler_storage_vault_white_list")
686
18
                .tag("", recycler_storage_vault_white_list);
687
18
        if (!config::recycler_storage_vault_white_list.empty()) {
688
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
689
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
690
8
                it == config::recycler_storage_vault_white_list.end()) {
691
2
                LOG_WARNING(
692
2
                        "failed to init accessor for vault because this vault is not in "
693
2
                        "config::recycler_storage_vault_white_list. ")
694
2
                        .tag(" vault name:", vault.name())
695
2
                        .tag(" config::recycler_storage_vault_white_list:",
696
2
                             recycler_storage_vault_white_list);
697
2
                continue;
698
2
            }
699
8
        }
700
16
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
701
16
                                 &accessor_map_, &vault);
702
16
        if (vault.has_hdfs_info()) {
703
9
#ifdef ENABLE_HDFS_STORAGE_VAULT
704
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
705
9
            int ret = accessor->init();
706
9
            if (ret != 0) {
707
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
708
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
709
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
710
4
                continue;
711
4
            }
712
5
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
713
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
714
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
715
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
716
#else
717
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
718
                       << "but HDFS storage vaults were detected";
719
#endif
720
7
        } else if (vault.has_obj_info()) {
721
            // TODO: Propagate object storage session tokens to Recycler in a follow-up PR.
722
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
723
7
            if (!s3_conf) {
724
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
725
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
726
1
                continue;
727
1
            }
728
729
6
            std::shared_ptr<S3Accessor> accessor;
730
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
731
6
            if (ret != 0) {
732
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
733
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
734
0
                             << " ret=" << ret
735
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
736
0
                continue;
737
0
            }
738
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
739
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
740
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
741
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
742
6
        }
743
16
    }
744
745
7
    if (!it->is_valid()) {
746
0
        LOG_WARNING("failed to get storage vault kv");
747
0
        return -1;
748
0
    }
749
750
7
    if (accessor_map_.empty()) {
751
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
752
1
        return -2;
753
1
    }
754
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
755
6
             instance_id_);
756
757
6
    return 0;
758
7
}
759
760
130
int InstanceRecycler::init() {
761
130
    if (instance_info_.status() == InstanceInfoPB::DELETED &&
762
130
        (instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING ||
763
4
         instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED)) {
764
1
        return 0;
765
1
    }
766
767
129
    int ret = init_obj_store_accessors();
768
129
    if (ret != 0) {
769
0
        return ret;
770
0
    }
771
772
129
    return init_storage_vault_accessors();
773
129
}
774
775
template <typename... Func>
776
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
120
    return [funcs...]() {
778
120
        return [](std::initializer_list<int> ret_vals) {
779
120
            int i = 0;
780
140
            for (int ret : ret_vals) {
781
140
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
140
            }
785
120
            return i;
786
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
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
20
            for (int ret : ret_vals) {
781
20
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
20
            }
785
10
            return i;
786
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
20
            for (int ret : ret_vals) {
781
20
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
20
            }
785
10
            return i;
786
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
0
                    i = ret;
783
0
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
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
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
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
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
776
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
777
10
    return [funcs...]() {
778
10
        return [](std::initializer_list<int> ret_vals) {
779
10
            int i = 0;
780
10
            for (int ret : ret_vals) {
781
10
                if (ret != 0) {
782
10
                    i = ret;
783
10
                }
784
10
            }
785
10
            return i;
786
10
        }({funcs()...});
787
10
    };
788
10
}
789
790
11
int InstanceRecycler::do_recycle() {
791
11
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
792
11
    tablet_metrics_context_.reset();
793
11
    segment_metrics_context_.reset();
794
11
    DORIS_CLOUD_DEFER {
795
11
        tablet_metrics_context_.finish_report();
796
11
        segment_metrics_context_.finish_report();
797
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
794
11
    DORIS_CLOUD_DEFER {
795
11
        tablet_metrics_context_.finish_report();
796
11
        segment_metrics_context_.finish_report();
797
11
    };
798
11
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
799
1
        int res = recycle_cluster_snapshots();
800
1
        if (res != 0) {
801
0
            return -1;
802
0
        }
803
1
        return recycle_deleted_instance();
804
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
805
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
806
10
                                        fmt::format("instance id {}", instance_id_),
807
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
807
120
                                        [](int r) { return r != 0; });
808
10
        sync_executor
809
10
                .add(task_wrapper(
810
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
810
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
811
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
811
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
812
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
813
                                   // becase they may both recycle the same set of tablets
814
                        // recycle dropped table or idexes(mv, rollup)
815
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
815
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
816
                        // recycle dropped partitions
817
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
817
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
818
10
                .add(task_wrapper(
819
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
819
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
820
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
820
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
821
10
                .add(task_wrapper(
822
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
822
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
823
10
                .add(task_wrapper(
824
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
824
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
825
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
825
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
826
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
826
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
827
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
827
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
828
10
                .add(task_wrapper(
829
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
829
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
830
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
830
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
831
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
831
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
832
10
        bool finished = true;
833
10
        std::vector<int> rets = sync_executor.when_all(&finished);
834
120
        for (int ret : rets) {
835
120
            if (ret != 0) {
836
0
                return ret;
837
0
            }
838
120
        }
839
10
        return finished ? 0 : -1;
840
10
    } else {
841
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
842
0
                     << " instance_id=" << instance_id_;
843
0
        return -1;
844
0
    }
845
11
}
846
847
/**
848
* 1. delete all remote data
849
* 2. delete all kv
850
* 3. remove instance kv
851
*/
852
13
int InstanceRecycler::recycle_deleted_instance() {
853
13
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
854
855
13
    int ret = 0;
856
13
    auto start_time = steady_clock::now();
857
13
    const auto recycle_state = instance_info_.recycle_state();
858
859
13
    DORIS_CLOUD_DEFER {
860
13
        auto cost = duration<float>(steady_clock::now() - start_time).count();
861
13
        if (ret != 0) {
862
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
863
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
864
0
                         << "s, instance_id=" << instance_id_;
865
13
        } else if (recycle_state ==
866
13
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
867
4
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
868
4
                      << "s, instance_id=" << instance_id_;
869
9
        } else {
870
9
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
871
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
872
9
                      << "s, instance_id=" << instance_id_;
873
9
        }
874
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
859
13
    DORIS_CLOUD_DEFER {
860
13
        auto cost = duration<float>(steady_clock::now() - start_time).count();
861
13
        if (ret != 0) {
862
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
863
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
864
0
                         << "s, instance_id=" << instance_id_;
865
13
        } else if (recycle_state ==
866
13
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
867
4
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
868
4
                      << "s, instance_id=" << instance_id_;
869
9
        } else {
870
9
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
871
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
872
9
                      << "s, instance_id=" << instance_id_;
873
9
        }
874
13
    };
875
876
13
    switch (recycle_state) {
877
6
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING:
878
6
        ret = recycle_deleted_instance_data();
879
6
        break;
880
3
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING:
881
3
        ret = recycle_deleted_instance_metadata();
882
3
        break;
883
4
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED:
884
4
        ret = remove_instance_key();
885
4
        break;
886
0
    default:
887
0
        LOG_WARNING("invalid instance recycle state")
888
0
                .tag("instance_id", instance_id_)
889
0
                .tag("recycle_state", instance_info_.recycle_state());
890
0
        ret = -1;
891
0
        break;
892
13
    }
893
894
13
    return ret;
895
13
}
896
897
6
int InstanceRecycler::recycle_deleted_instance_data() {
898
6
    int ret = 0;
899
900
    // Step 1: Recycle tmp rowsets (contains ref count but txn is not committed)
901
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
902
6
        int res = recycle_tmp_rowsets();
903
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
904
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
905
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
906
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
907
            // and cannot be recycled.
908
0
            res = recycle_tmp_rowsets();
909
0
        }
910
6
        return res;
911
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
Line
Count
Source
901
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
902
6
        int res = recycle_tmp_rowsets();
903
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
904
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
905
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
906
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
907
            // and cannot be recycled.
908
0
            res = recycle_tmp_rowsets();
909
0
        }
910
6
        return res;
911
6
    };
912
913
6
    if (recycle_tmp_rowsets_with_mark_delete_enabled() != 0) {
914
0
        LOG_WARNING("failed to recycle tmp rowsets").tag("instance_id", instance_id_);
915
0
        return -1;
916
0
    }
917
918
    // Step 2: Recycle versioned rowsets in recycle space (already marked for deletion)
919
6
    if (recycle_versioned_rowsets() != 0) {
920
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
921
0
        return -1;
922
0
    }
923
924
    // Step 3: Recycle operation logs (can recycle logs not referenced by snapshots)
925
6
    if (recycle_operation_logs() != 0) {
926
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
927
0
        return -1;
928
0
    }
929
930
    // Step 4: Check if there are still cluster snapshots
931
6
    bool has_snapshots = false;
932
6
    if (has_cluster_snapshots(&has_snapshots) != 0) {
933
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
934
0
        return -1;
935
6
    } else if (has_snapshots) {
936
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
937
1
        return 0;
938
1
    }
939
940
5
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
941
5
                            instance_info().snapshot_switch_status() !=
942
1
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
943
5
    if (snapshot_enabled) {
944
1
        bool has_unrecycled_rowsets = false;
945
1
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
946
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
947
0
            return -1;
948
1
        } else if (has_unrecycled_rowsets) {
949
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
950
0
                    .tag("instance_id", instance_id_);
951
0
            return ret;
952
0
        }
953
4
    } else { // delete all remote data if snapshot is disabled
954
4
        for (auto& [_, accessor] : accessor_map_) {
955
4
            if (stopped()) {
956
0
                return ret;
957
0
            }
958
959
4
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
960
4
            int del_ret = accessor->delete_all();
961
4
            if (del_ret == 0) {
962
4
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
963
4
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
964
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
965
                // so the recycling has been successful.
966
0
                ret = -1;
967
0
            }
968
4
        }
969
970
4
        if (ret != 0) {
971
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
972
0
            return ret;
973
0
        }
974
4
    }
975
976
5
    if (update_instance_recycle_state(
977
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING,
978
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) != 0) {
979
0
        return -1;
980
0
    }
981
982
5
    return 0;
983
5
}
984
985
3
int InstanceRecycler::recycle_deleted_instance_metadata() {
986
    // Check successor instance, if exists, skip deleting kv because successor instance may still need the data in kv
987
3
    if (instance_info_.has_successor_instance_id() &&
988
3
        !instance_info_.successor_instance_id().empty()) {
989
0
        std::string key = instance_key(instance_info_.successor_instance_id());
990
0
        std::unique_ptr<Transaction> txn;
991
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
992
0
        if (err != TxnErrorCode::TXN_OK) {
993
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_
994
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
995
0
                         << " err=" << err;
996
0
            return -1;
997
0
        }
998
999
0
        std::string value;
1000
0
        err = txn->get(key, &value);
1001
0
        if (err == TxnErrorCode::TXN_OK) {
1002
0
            LOG(INFO) << "instance successor instance is still exist, skip deleting kv,"
1003
0
                      << " instance_id=" << instance_id_
1004
0
                      << " successor_instance_id=" << instance_info_.successor_instance_id();
1005
0
            return 0;
1006
0
        } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1007
0
            LOG(WARNING) << "failed to get successor instance, instance_id=" << instance_id_
1008
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1009
0
                         << " err=" << err;
1010
0
            return -1;
1011
0
        }
1012
0
    }
1013
1014
    // delete all kv
1015
3
    std::unique_ptr<Transaction> txn;
1016
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1017
3
    if (err != TxnErrorCode::TXN_OK) {
1018
0
        LOG(WARNING) << "failed to create txn";
1019
0
        return -1;
1020
0
    }
1021
3
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
1022
    // delete kv before deleting objects to prevent the checker from misjudging data loss
1023
3
    std::string start_txn_key = txn_key_prefix(instance_id_);
1024
3
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
1025
3
    txn->remove(start_txn_key, end_txn_key);
1026
3
    std::string start_version_key = version_key_prefix(instance_id_);
1027
3
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
1028
3
    txn->remove(start_version_key, end_version_key);
1029
3
    std::string start_meta_key = meta_key_prefix(instance_id_);
1030
3
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
1031
3
    txn->remove(start_meta_key, end_meta_key);
1032
3
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
1033
3
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
1034
3
    txn->remove(start_recycle_key, end_recycle_key);
1035
3
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
1036
3
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1037
3
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
1038
3
    std::string start_copy_key = copy_key_prefix(instance_id_);
1039
3
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
1040
3
    txn->remove(start_copy_key, end_copy_key);
1041
    // should not remove job key range, because we need to reserve job recycle kv
1042
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
1043
3
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
1044
3
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1045
3
    txn->remove(start_job_tablet_key, end_job_tablet_key);
1046
3
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
1047
3
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
1048
3
    std::string start_vault_key = storage_vault_key(key_info0);
1049
3
    std::string end_vault_key = storage_vault_key(key_info1);
1050
3
    txn->remove(start_vault_key, end_vault_key);
1051
3
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
1052
3
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
1053
3
    txn->remove(versioned_version_key_start, versioned_version_key_end);
1054
3
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
1055
3
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
1056
3
    txn->remove(versioned_index_key_start, versioned_index_key_end);
1057
3
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
1058
3
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
1059
3
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
1060
3
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
1061
3
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
1062
3
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
1063
3
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
1064
3
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
1065
3
    txn->remove(versioned_data_key_start, versioned_data_key_end);
1066
3
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
1067
3
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
1068
3
    txn->remove(versioned_log_key_start, versioned_log_key_end);
1069
1070
    // Updating the recycle state also commits this transaction, making the metadata deletions
1071
    // and state transition atomic.
1072
3
    if (update_instance_recycle_state(
1073
3
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING,
1074
3
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED, txn.get()) != 0) {
1075
0
        return -1;
1076
0
    }
1077
1078
3
    return 0;
1079
3
}
1080
1081
4
int InstanceRecycler::remove_instance_key() {
1082
4
    std::unique_ptr<Transaction> txn;
1083
4
    std::string key = instance_key(instance_info_.instance_id());
1084
4
    std::string value;
1085
4
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1086
4
    if (err != TxnErrorCode::TXN_OK) {
1087
0
        LOG(WARNING) << "failed to create txn";
1088
0
        return -1;
1089
0
    }
1090
1091
4
    err = txn->get(key, &value);
1092
4
    if (err != TxnErrorCode::TXN_OK) {
1093
0
        LOG(WARNING) << "failed to get instance, instance_id=" << instance_info_.instance_id()
1094
0
                     << ", err=" << err;
1095
0
        return -1;
1096
0
    }
1097
1098
4
    InstanceInfoPB instance;
1099
4
    if (!instance.ParseFromString(value)) {
1100
0
        LOG(WARNING) << "malformed instance info, key=" << key;
1101
0
        return -1;
1102
0
    }
1103
1104
4
    if (instance.status() != InstanceInfoPB::DELETED) {
1105
0
        LOG(WARNING) << "failed to remove instance key, instance is not deleted, instance_id="
1106
0
                     << instance_id_ << ", status=" << instance.status();
1107
0
        return -1;
1108
0
    }
1109
1110
4
    if (instance.recycle_state() != INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1111
0
        LOG(WARNING) << "failed to remove instance key, invalid recycle state, instance_id="
1112
0
                     << instance_id_
1113
0
                     << ", current_state=" << InstanceRecycleState_Name(instance.recycle_state())
1114
0
                     << ", expected_state="
1115
0
                     << InstanceRecycleState_Name(INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1116
0
        return -1;
1117
0
    }
1118
1119
4
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1120
4
    txn->remove(key);
1121
4
    err = txn->commit();
1122
4
    if (err != TxnErrorCode::TXN_OK) {
1123
0
        LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
1124
0
                     << " err=" << err;
1125
0
        return -1;
1126
0
    }
1127
4
    return 0;
1128
4
}
1129
1130
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState expected_state,
1131
7
                                                    InstanceRecycleState target_state) {
1132
7
    std::unique_ptr<Transaction> txn;
1133
7
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1134
7
    if (err != TxnErrorCode::TXN_OK) {
1135
0
        LOG(WARNING) << "failed to create txn";
1136
0
        return -1;
1137
0
    }
1138
7
    return update_instance_recycle_state(expected_state, target_state, txn.get());
1139
7
}
1140
1141
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState current_state,
1142
                                                    InstanceRecycleState target_state,
1143
10
                                                    Transaction* txn) {
1144
10
    const bool valid_transition =
1145
10
            (current_state == INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING &&
1146
10
             target_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) ||
1147
10
            (current_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING &&
1148
4
             target_state == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1149
1150
10
    if (!valid_transition) {
1151
1
        LOG_WARNING("invalid instance recycled state transition")
1152
1
                .tag("instance_id", instance_id_)
1153
1
                .tag("current_state", InstanceRecycleState_Name(current_state))
1154
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1155
1
        return -1;
1156
1
    }
1157
1158
9
    std::string key = instance_key({instance_id_});
1159
9
    std::string value;
1160
9
    TxnErrorCode err = txn->get(key, &value);
1161
9
    if (err != TxnErrorCode::TXN_OK) {
1162
0
        LOG_WARNING("failed to get instance when updating instance recycled state")
1163
0
                .tag("instance_id", instance_id_)
1164
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1165
0
                .tag("target_state", InstanceRecycleState_Name(target_state))
1166
0
                .tag("err", err);
1167
0
        return -1;
1168
0
    }
1169
1170
9
    InstanceInfoPB instance;
1171
9
    if (!instance.ParseFromString(value)) {
1172
0
        LOG_WARNING("failed to parse InstanceInfoPB when updating instance recycled state")
1173
0
                .tag("instance_id", instance_id_)
1174
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1175
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1176
0
        return -1;
1177
0
    }
1178
9
    if (instance.status() != InstanceInfoPB::DELETED) {
1179
0
        LOG_WARNING("instance is not deleted when updating instance recycled state")
1180
0
                .tag("instance_id", instance_id_)
1181
0
                .tag("status", instance.status())
1182
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1183
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1184
0
        return -1;
1185
0
    }
1186
9
    if (instance.recycle_state() != current_state) {
1187
1
        LOG_WARNING("instance recycled state changed before update")
1188
1
                .tag("instance_id", instance_id_)
1189
1
                .tag("current_state", InstanceRecycleState_Name(instance.recycle_state()))
1190
1
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1191
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1192
1
        return -1;
1193
1
    }
1194
1195
8
    instance.set_recycle_state(target_state);
1196
8
    instance.set_recycle_state_update_time_ms(
1197
8
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count());
1198
8
    if (!instance.SerializeToString(&value)) {
1199
0
        LOG_WARNING("failed to serialize InstanceInfoPB when updating instance recycled state")
1200
0
                .tag("instance_id", instance_id_)
1201
0
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1202
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1203
0
        return -1;
1204
0
    }
1205
1206
8
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1207
8
    txn->put(key, value);
1208
8
    err = txn->commit();
1209
8
    if (err != TxnErrorCode::TXN_OK) {
1210
0
        LOG(WARNING) << "failed to commit fdb txn when updating instance recycled state, "
1211
0
                     << "instance_id=" << instance_id_ << ", err=" << err;
1212
0
        return -1;
1213
0
    }
1214
1215
8
    instance_info_.Swap(&instance);
1216
8
    LOG_INFO("updated instance recycled state")
1217
8
            .tag("instance_id", instance_id_)
1218
8
            .tag("recycle_state", InstanceRecycleState_Name(target_state));
1219
8
    return 0;
1220
8
}
1221
1222
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
1223
9
                                          bool* exists, PackedFileRecycleStats* stats) {
1224
9
    if (exists == nullptr) {
1225
0
        return -1;
1226
0
    }
1227
9
    *exists = false;
1228
1229
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
1230
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1231
9
    std::string scan_begin = begin;
1232
1233
9
    while (true) {
1234
9
        std::unique_ptr<RangeGetIterator> it_range;
1235
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
1236
9
        if (get_ret < 0) {
1237
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1238
0
                    .tag("instance_id", instance_id_)
1239
0
                    .tag("tablet_id", tablet_id)
1240
0
                    .tag("ret", get_ret);
1241
0
            return -1;
1242
0
        }
1243
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1244
6
            return 0;
1245
6
        }
1246
1247
3
        std::string last_key;
1248
3
        while (it_range->has_next()) {
1249
3
            auto [k, v] = it_range->next();
1250
3
            last_key.assign(k.data(), k.size());
1251
3
            doris::RowsetMetaCloudPB rowset_meta;
1252
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1253
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1254
0
                        .tag("instance_id", instance_id_)
1255
0
                        .tag("tablet_id", tablet_id)
1256
0
                        .tag("key", hex(k));
1257
0
                continue;
1258
0
            }
1259
3
            if (stats) {
1260
3
                ++stats->rowset_scan_count;
1261
3
            }
1262
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1263
3
                *exists = true;
1264
3
                return 0;
1265
3
            }
1266
3
        }
1267
1268
0
        if (!it_range->more()) {
1269
0
            return 0;
1270
0
        }
1271
1272
        // Continue scanning from the next key to keep each transaction short.
1273
0
        scan_begin = std::move(last_key);
1274
0
        scan_begin.push_back('\x00');
1275
0
    }
1276
9
}
1277
1278
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1279
                                                          const std::string& rowset_id,
1280
                                                          int64_t txn_id, bool* recycle_exists,
1281
11
                                                          bool* tmp_exists) {
1282
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1283
0
        return -1;
1284
0
    }
1285
11
    *recycle_exists = false;
1286
11
    *tmp_exists = false;
1287
1288
11
    if (txn_id <= 0) {
1289
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1290
0
                .tag("instance_id", instance_id_)
1291
0
                .tag("tablet_id", tablet_id)
1292
0
                .tag("rowset_id", rowset_id)
1293
0
                .tag("txn_id", txn_id);
1294
0
        return -1;
1295
0
    }
1296
1297
11
    std::unique_ptr<Transaction> txn;
1298
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1299
11
    if (err != TxnErrorCode::TXN_OK) {
1300
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1301
0
                .tag("instance_id", instance_id_)
1302
0
                .tag("tablet_id", tablet_id)
1303
0
                .tag("rowset_id", rowset_id)
1304
0
                .tag("txn_id", txn_id)
1305
0
                .tag("err", err);
1306
0
        return -1;
1307
0
    }
1308
1309
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1310
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1311
11
    if (ret == TxnErrorCode::TXN_OK) {
1312
1
        *recycle_exists = true;
1313
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1314
0
        LOG_WARNING("failed to check recycle rowset existence")
1315
0
                .tag("instance_id", instance_id_)
1316
0
                .tag("tablet_id", tablet_id)
1317
0
                .tag("rowset_id", rowset_id)
1318
0
                .tag("key", hex(recycle_key))
1319
0
                .tag("err", ret);
1320
0
        return -1;
1321
0
    }
1322
1323
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1324
11
    ret = key_exists(txn.get(), tmp_key, true);
1325
11
    if (ret == TxnErrorCode::TXN_OK) {
1326
1
        *tmp_exists = true;
1327
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1328
0
        LOG_WARNING("failed to check tmp rowset existence")
1329
0
                .tag("instance_id", instance_id_)
1330
0
                .tag("tablet_id", tablet_id)
1331
0
                .tag("txn_id", txn_id)
1332
0
                .tag("key", hex(tmp_key))
1333
0
                .tag("err", ret);
1334
0
        return -1;
1335
0
    }
1336
1337
11
    return 0;
1338
11
}
1339
1340
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1341
8
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1342
8
    if (!hint.empty()) {
1343
8
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1344
8
            return {hint, it->second};
1345
8
        }
1346
8
    }
1347
1348
0
    return {"", nullptr};
1349
8
}
1350
1351
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1352
                                               const std::string& packed_file_path,
1353
3
                                               PackedFileRecycleStats* stats) {
1354
3
    bool local_changed = false;
1355
3
    int64_t left_num = 0;
1356
3
    int64_t left_bytes = 0;
1357
3
    bool all_small_files_confirmed = true;
1358
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1359
1360
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1361
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1362
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1363
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1364
14
        LOG_INFO("packed slice correction status")
1365
14
                .tag("instance_id", instance_id_)
1366
14
                .tag("packed_file_path", packed_file_path)
1367
14
                .tag("small_file_path", file.path())
1368
14
                .tag("tablet_id", tablet_id)
1369
14
                .tag("rowset_id", rowset_id)
1370
14
                .tag("txn_id", txn_id)
1371
14
                .tag("size", file.size())
1372
14
                .tag("deleted", file.deleted())
1373
14
                .tag("corrected", file.corrected())
1374
14
                .tag("confirmed_this_round", confirmed_this_round);
1375
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
1360
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1361
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1362
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1363
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1364
14
        LOG_INFO("packed slice correction status")
1365
14
                .tag("instance_id", instance_id_)
1366
14
                .tag("packed_file_path", packed_file_path)
1367
14
                .tag("small_file_path", file.path())
1368
14
                .tag("tablet_id", tablet_id)
1369
14
                .tag("rowset_id", rowset_id)
1370
14
                .tag("txn_id", txn_id)
1371
14
                .tag("size", file.size())
1372
14
                .tag("deleted", file.deleted())
1373
14
                .tag("corrected", file.corrected())
1374
14
                .tag("confirmed_this_round", confirmed_this_round);
1375
14
    };
1376
1377
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1378
14
        auto* small_file = packed_info->mutable_slices(i);
1379
14
        if (small_file->deleted()) {
1380
3
            log_small_file_status(*small_file, small_file->corrected());
1381
3
            continue;
1382
3
        }
1383
1384
11
        if (small_file->corrected()) {
1385
0
            left_num++;
1386
0
            left_bytes += small_file->size();
1387
0
            log_small_file_status(*small_file, true);
1388
0
            continue;
1389
0
        }
1390
1391
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1392
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1393
0
                    .tag("instance_id", instance_id_)
1394
0
                    .tag("small_file_path", small_file->path())
1395
0
                    .tag("index", i);
1396
0
            return -1;
1397
0
        }
1398
1399
11
        int64_t tablet_id = small_file->tablet_id();
1400
11
        const std::string& rowset_id = small_file->rowset_id();
1401
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1402
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1403
0
                    .tag("instance_id", instance_id_)
1404
0
                    .tag("small_file_path", small_file->path())
1405
0
                    .tag("index", i)
1406
0
                    .tag("tablet_id", tablet_id)
1407
0
                    .tag("rowset_id", rowset_id)
1408
0
                    .tag("has_txn_id", small_file->has_txn_id())
1409
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1410
0
            return -1;
1411
0
        }
1412
11
        int64_t txn_id = small_file->txn_id();
1413
11
        bool recycle_exists = false;
1414
11
        bool tmp_exists = false;
1415
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1416
11
                                                &tmp_exists) != 0) {
1417
0
            return -1;
1418
0
        }
1419
1420
11
        bool small_file_confirmed = false;
1421
11
        if (tmp_exists) {
1422
1
            left_num++;
1423
1
            left_bytes += small_file->size();
1424
1
            small_file_confirmed = true;
1425
10
        } else if (recycle_exists) {
1426
1
            left_num++;
1427
1
            left_bytes += small_file->size();
1428
            // keep small_file_confirmed=false so the packed file remains uncorrected
1429
9
        } else {
1430
9
            bool rowset_exists = false;
1431
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1432
0
                return -1;
1433
0
            }
1434
1435
9
            if (!rowset_exists) {
1436
6
                if (!small_file->deleted()) {
1437
6
                    small_file->set_deleted(true);
1438
6
                    local_changed = true;
1439
6
                }
1440
6
                if (!small_file->corrected()) {
1441
6
                    small_file->set_corrected(true);
1442
6
                    local_changed = true;
1443
6
                }
1444
6
                small_file_confirmed = true;
1445
6
            } else {
1446
3
                left_num++;
1447
3
                left_bytes += small_file->size();
1448
3
                small_file_confirmed = true;
1449
3
            }
1450
9
        }
1451
1452
11
        if (!small_file_confirmed) {
1453
1
            all_small_files_confirmed = false;
1454
1
        }
1455
1456
11
        if (small_file->corrected() != small_file_confirmed) {
1457
4
            small_file->set_corrected(small_file_confirmed);
1458
4
            local_changed = true;
1459
4
        }
1460
1461
11
        log_small_file_status(*small_file, small_file_confirmed);
1462
11
    }
1463
1464
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1465
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1466
3
        local_changed = true;
1467
3
    }
1468
3
    if (packed_info->ref_cnt() != left_num) {
1469
3
        auto old_ref_cnt = packed_info->ref_cnt();
1470
3
        packed_info->set_ref_cnt(left_num);
1471
3
        LOG_INFO("corrected packed file ref count")
1472
3
                .tag("instance_id", instance_id_)
1473
3
                .tag("resource_id", packed_info->resource_id())
1474
3
                .tag("packed_file_path", packed_file_path)
1475
3
                .tag("old_ref_cnt", old_ref_cnt)
1476
3
                .tag("new_ref_cnt", left_num);
1477
3
        local_changed = true;
1478
3
    }
1479
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1480
2
        packed_info->set_corrected(all_small_files_confirmed);
1481
2
        local_changed = true;
1482
2
    }
1483
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1484
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1485
1
        local_changed = true;
1486
1
    }
1487
1488
3
    if (changed != nullptr) {
1489
3
        *changed = local_changed;
1490
3
    }
1491
3
    return 0;
1492
3
}
1493
1494
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1495
                                                 const std::string& packed_file_path,
1496
3
                                                 PackedFileRecycleStats* stats) {
1497
3
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1498
3
    bool correction_ok = false;
1499
3
    cloud::PackedFileInfoPB packed_info;
1500
1501
3
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1502
3
        if (stopped()) {
1503
0
            LOG_WARNING("recycler stopped before processing packed file")
1504
0
                    .tag("instance_id", instance_id_)
1505
0
                    .tag("packed_file_path", packed_file_path)
1506
0
                    .tag("attempt", attempt);
1507
0
            return -1;
1508
0
        }
1509
1510
3
        std::unique_ptr<Transaction> txn;
1511
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1512
3
        if (err != TxnErrorCode::TXN_OK) {
1513
0
            LOG_WARNING("failed to create txn when processing packed file")
1514
0
                    .tag("instance_id", instance_id_)
1515
0
                    .tag("packed_file_path", packed_file_path)
1516
0
                    .tag("attempt", attempt)
1517
0
                    .tag("err", err);
1518
0
            return -1;
1519
0
        }
1520
1521
3
        std::string packed_val;
1522
3
        err = txn->get(packed_key, &packed_val);
1523
3
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1524
0
            return 0;
1525
0
        }
1526
3
        if (err != TxnErrorCode::TXN_OK) {
1527
0
            LOG_WARNING("failed to get packed file kv")
1528
0
                    .tag("instance_id", instance_id_)
1529
0
                    .tag("packed_file_path", packed_file_path)
1530
0
                    .tag("attempt", attempt)
1531
0
                    .tag("err", err);
1532
0
            return -1;
1533
0
        }
1534
1535
3
        if (!packed_info.ParseFromString(packed_val)) {
1536
0
            LOG_WARNING("failed to parse packed file info")
1537
0
                    .tag("instance_id", instance_id_)
1538
0
                    .tag("packed_file_path", packed_file_path)
1539
0
                    .tag("attempt", attempt);
1540
0
            return -1;
1541
0
        }
1542
1543
3
        int64_t now_sec = ::time(nullptr);
1544
3
        bool corrected = packed_info.corrected();
1545
3
        bool due = config::force_immediate_recycle ||
1546
3
                   now_sec - packed_info.created_at_sec() >=
1547
3
                           config::packed_file_correction_delay_seconds;
1548
1549
3
        if (!corrected && due) {
1550
3
            bool changed = false;
1551
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1552
0
                LOG_WARNING("correct_packed_file_info failed")
1553
0
                        .tag("instance_id", instance_id_)
1554
0
                        .tag("packed_file_path", packed_file_path)
1555
0
                        .tag("attempt", attempt);
1556
0
                return -1;
1557
0
            }
1558
3
            if (changed) {
1559
3
                std::string updated;
1560
3
                if (!packed_info.SerializeToString(&updated)) {
1561
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1562
0
                            .tag("instance_id", instance_id_)
1563
0
                            .tag("packed_file_path", packed_file_path)
1564
0
                            .tag("attempt", attempt);
1565
0
                    return -1;
1566
0
                }
1567
3
                txn->put(packed_key, updated);
1568
3
                err = txn->commit();
1569
3
                if (err == TxnErrorCode::TXN_OK) {
1570
3
                    if (stats) {
1571
3
                        ++stats->num_corrected;
1572
3
                    }
1573
3
                } else {
1574
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1575
0
                        LOG_WARNING(
1576
0
                                "failed to commit correction for packed file due to conflict, "
1577
0
                                "retrying")
1578
0
                                .tag("instance_id", instance_id_)
1579
0
                                .tag("packed_file_path", packed_file_path)
1580
0
                                .tag("attempt", attempt);
1581
0
                        sleep_for_packed_file_retry();
1582
0
                        packed_info.Clear();
1583
0
                        continue;
1584
0
                    }
1585
0
                    LOG_WARNING("failed to commit correction for packed file")
1586
0
                            .tag("instance_id", instance_id_)
1587
0
                            .tag("packed_file_path", packed_file_path)
1588
0
                            .tag("attempt", attempt)
1589
0
                            .tag("err", err);
1590
0
                    return -1;
1591
0
                }
1592
3
            }
1593
3
        }
1594
1595
3
        correction_ok = true;
1596
3
        break;
1597
3
    }
1598
1599
3
    if (!correction_ok) {
1600
0
        return -1;
1601
0
    }
1602
1603
3
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1604
3
          packed_info.ref_cnt() == 0)) {
1605
2
        return 0;
1606
2
    }
1607
1608
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1609
0
        LOG_WARNING("packed file missing resource id when recycling")
1610
0
                .tag("instance_id", instance_id_)
1611
0
                .tag("packed_file_path", packed_file_path);
1612
0
        return -1;
1613
0
    }
1614
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1615
1
    if (!accessor) {
1616
0
        LOG_WARNING("no accessor available to delete packed file")
1617
0
                .tag("instance_id", instance_id_)
1618
0
                .tag("packed_file_path", packed_file_path)
1619
0
                .tag("resource_id", packed_info.resource_id());
1620
0
        return -1;
1621
0
    }
1622
1
    int del_ret = accessor->delete_file(packed_file_path);
1623
1
    if (del_ret != 0 && del_ret != 1) {
1624
0
        LOG_WARNING("failed to delete packed file")
1625
0
                .tag("instance_id", instance_id_)
1626
0
                .tag("packed_file_path", packed_file_path)
1627
0
                .tag("resource_id", resource_id)
1628
0
                .tag("ret", del_ret);
1629
0
        return -1;
1630
0
    }
1631
1
    if (del_ret == 1) {
1632
0
        LOG_INFO("packed file already removed")
1633
0
                .tag("instance_id", instance_id_)
1634
0
                .tag("packed_file_path", packed_file_path)
1635
0
                .tag("resource_id", resource_id);
1636
1
    } else {
1637
1
        LOG_INFO("deleted packed file")
1638
1
                .tag("instance_id", instance_id_)
1639
1
                .tag("packed_file_path", packed_file_path)
1640
1
                .tag("resource_id", resource_id);
1641
1
    }
1642
1643
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1644
1
        std::unique_ptr<Transaction> del_txn;
1645
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1646
1
        if (err != TxnErrorCode::TXN_OK) {
1647
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1648
0
                    .tag("instance_id", instance_id_)
1649
0
                    .tag("packed_file_path", packed_file_path)
1650
0
                    .tag("del_attempt", del_attempt)
1651
0
                    .tag("err", err);
1652
0
            return -1;
1653
0
        }
1654
1655
1
        std::string latest_val;
1656
1
        err = del_txn->get(packed_key, &latest_val);
1657
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1658
0
            return 0;
1659
0
        }
1660
1
        if (err != TxnErrorCode::TXN_OK) {
1661
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1662
0
                    .tag("instance_id", instance_id_)
1663
0
                    .tag("packed_file_path", packed_file_path)
1664
0
                    .tag("del_attempt", del_attempt)
1665
0
                    .tag("err", err);
1666
0
            return -1;
1667
0
        }
1668
1669
1
        cloud::PackedFileInfoPB latest_info;
1670
1
        if (!latest_info.ParseFromString(latest_val)) {
1671
0
            LOG_WARNING("failed to parse packed file info before removal")
1672
0
                    .tag("instance_id", instance_id_)
1673
0
                    .tag("packed_file_path", packed_file_path)
1674
0
                    .tag("del_attempt", del_attempt);
1675
0
            return -1;
1676
0
        }
1677
1678
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1679
1
              latest_info.ref_cnt() == 0)) {
1680
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
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
            return 0;
1685
0
        }
1686
1687
1
        del_txn->remove(packed_key);
1688
1
        err = del_txn->commit();
1689
1
        if (err == TxnErrorCode::TXN_OK) {
1690
1
            if (stats) {
1691
1
                ++stats->num_deleted;
1692
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1693
1
                                        static_cast<int64_t>(latest_val.size());
1694
1
                if (del_ret == 0 || del_ret == 1) {
1695
1
                    ++stats->num_object_deleted;
1696
1
                    int64_t object_size = latest_info.total_slice_bytes();
1697
1
                    if (object_size <= 0) {
1698
0
                        object_size = packed_info.total_slice_bytes();
1699
0
                    }
1700
1
                    stats->bytes_object_deleted += object_size;
1701
1
                }
1702
1
            }
1703
1
            LOG_INFO("removed packed file metadata")
1704
1
                    .tag("instance_id", instance_id_)
1705
1
                    .tag("packed_file_path", packed_file_path);
1706
1
            return 0;
1707
1
        }
1708
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1709
0
            if (del_attempt >= max_retry_times) {
1710
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1711
0
                        .tag("instance_id", instance_id_)
1712
0
                        .tag("packed_file_path", packed_file_path)
1713
0
                        .tag("del_attempt", del_attempt);
1714
0
                return -1;
1715
0
            }
1716
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1717
0
                    .tag("instance_id", instance_id_)
1718
0
                    .tag("packed_file_path", packed_file_path)
1719
0
                    .tag("del_attempt", del_attempt);
1720
0
            sleep_for_packed_file_retry();
1721
0
            continue;
1722
0
        }
1723
0
        LOG_WARNING("failed to remove packed file kv")
1724
0
                .tag("instance_id", instance_id_)
1725
0
                .tag("packed_file_path", packed_file_path)
1726
0
                .tag("del_attempt", del_attempt)
1727
0
                .tag("err", err);
1728
0
        return -1;
1729
0
    }
1730
1731
0
    return -1;
1732
1
}
1733
1734
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view value,
1735
4
                                            PackedFileRecycleStats* stats, int* ret) {
1736
4
    if (stats) {
1737
4
        ++stats->num_scanned;
1738
4
    }
1739
4
    std::string packed_file_path;
1740
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1741
0
        LOG_WARNING("failed to decode packed file key")
1742
0
                .tag("instance_id", instance_id_)
1743
0
                .tag("key", hex(key));
1744
0
        if (stats) {
1745
0
            ++stats->num_failed;
1746
0
        }
1747
0
        if (ret) {
1748
0
            *ret = -1;
1749
0
        }
1750
0
        return 0;
1751
0
    }
1752
1753
4
    cloud::PackedFileInfoPB packed_info;
1754
4
    if (!packed_info.ParseFromArray(value.data(), value.size())) {
1755
0
        LOG_WARNING("failed to parse packed file info from scan")
1756
0
                .tag("instance_id", instance_id_)
1757
0
                .tag("packed_file_path", packed_file_path);
1758
0
        if (stats) {
1759
0
            ++stats->num_failed;
1760
0
        }
1761
0
        if (ret) {
1762
0
            *ret = -1;
1763
0
        }
1764
0
        return 0;
1765
0
    }
1766
1767
4
    const int64_t now_sec = ::time(nullptr);
1768
4
    const bool due =
1769
4
            config::force_immediate_recycle ||
1770
4
            now_sec - packed_info.created_at_sec() >= config::packed_file_correction_delay_seconds;
1771
4
    const bool need_correction = !packed_info.corrected() && due;
1772
4
    const bool need_recycle =
1773
4
            packed_info.state() == cloud::PackedFileInfoPB::RECYCLING && packed_info.ref_cnt() == 0;
1774
4
    if (!need_correction && !need_recycle) {
1775
1
        return 0;
1776
1
    }
1777
1778
3
    std::string packed_key(key);
1779
3
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1780
3
    if (process_ret != 0) {
1781
0
        if (stats) {
1782
0
            ++stats->num_failed;
1783
0
        }
1784
0
        if (ret) {
1785
0
            *ret = -1;
1786
0
        }
1787
0
    }
1788
3
    return 0;
1789
4
}
1790
1791
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1792
6.06k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1793
6.06k
    if (config::force_immediate_recycle) {
1794
15
        return 0L;
1795
15
    }
1796
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1797
6.05k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1798
6.05k
    int64_t retention_seconds = config::retention_seconds;
1799
6.05k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1800
4.74k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1801
4.74k
    }
1802
6.05k
    int64_t final_expiration = expiration + retention_seconds;
1803
6.05k
    if (*earlest_ts > final_expiration) {
1804
16
        *earlest_ts = final_expiration;
1805
16
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1806
16
    }
1807
6.05k
    return final_expiration;
1808
6.06k
}
1809
1810
int64_t calculate_partition_expired_time(
1811
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1812
11
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1813
11
    if (config::force_immediate_recycle) {
1814
5
        return 0L;
1815
5
    }
1816
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1817
6
                                                            : partition_meta_pb.creation_time();
1818
6
    int64_t retention_seconds = config::retention_seconds;
1819
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1820
6
        retention_seconds =
1821
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1822
6
    }
1823
6
    int64_t final_expiration = expiration + retention_seconds;
1824
6
    if (*earlest_ts > final_expiration) {
1825
2
        *earlest_ts = final_expiration;
1826
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1827
2
    }
1828
6
    return final_expiration;
1829
11
}
1830
1831
int64_t calculate_index_expired_time(const std::string& instance_id_,
1832
                                     const RecycleIndexPB& index_meta_pb,
1833
14
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1834
14
    if (config::force_immediate_recycle) {
1835
8
        return 0L;
1836
8
    }
1837
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1838
6
                                                        : index_meta_pb.creation_time();
1839
6
    int64_t retention_seconds = config::retention_seconds;
1840
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1841
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1842
6
    }
1843
6
    int64_t final_expiration = expiration + retention_seconds;
1844
6
    if (*earlest_ts > final_expiration) {
1845
2
        *earlest_ts = final_expiration;
1846
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1847
2
    }
1848
6
    return final_expiration;
1849
14
}
1850
1851
int64_t calculate_tmp_rowset_expired_time(
1852
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1853
53.0k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1854
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1855
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1856
    //  duration or timeout always < `retention_time` in practice.
1857
53.0k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1858
53.0k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1859
53.0k
                                 : tmp_rowset_meta_pb.creation_time();
1860
53.0k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1861
53.0k
    int64_t final_expiration = expiration + config::retention_seconds;
1862
53.0k
    if (*earlest_ts > final_expiration) {
1863
18
        *earlest_ts = final_expiration;
1864
18
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1865
18
    }
1866
53.0k
    return final_expiration;
1867
53.0k
}
1868
1869
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1870
30.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1871
30.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1872
30.0k
    if (*earlest_ts > final_expiration / 1000) {
1873
8
        *earlest_ts = final_expiration / 1000;
1874
8
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1875
8
    }
1876
30.0k
    return final_expiration;
1877
30.0k
}
1878
1879
int64_t calculate_restore_job_expired_time(
1880
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1881
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1882
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1883
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1884
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1885
        // final state, recycle immediately
1886
41
        return 0L;
1887
41
    }
1888
    // not final state, wait much longer than the FE's timeout(1 day)
1889
0
    int64_t last_modified_s =
1890
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1891
0
    int64_t expiration = restore_job.expired_at_s() > 0
1892
0
                                 ? last_modified_s + restore_job.expired_at_s()
1893
0
                                 : last_modified_s;
1894
0
    int64_t final_expiration = expiration + config::retention_seconds;
1895
0
    if (*earlest_ts > final_expiration) {
1896
0
        *earlest_ts = final_expiration;
1897
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1898
0
    }
1899
0
    return final_expiration;
1900
41
}
1901
1902
2
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1903
2
    AbortTxnRequest req;
1904
2
    TxnInfoPB txn_info;
1905
2
    MetaServiceCode code = MetaServiceCode::OK;
1906
2
    std::string msg;
1907
2
    std::stringstream ss;
1908
2
    std::unique_ptr<Transaction> txn;
1909
2
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1910
2
    if (err != TxnErrorCode::TXN_OK) {
1911
0
        LOG_WARNING("failed to create txn").tag("err", err);
1912
0
        return -1;
1913
0
    }
1914
1915
    // get txn index
1916
2
    TxnIndexPB txn_idx_pb;
1917
2
    auto index_key = txn_index_key({instance_id_, txn_id});
1918
2
    std::string index_val;
1919
2
    err = txn->get(index_key, &index_val);
1920
2
    if (err != TxnErrorCode::TXN_OK) {
1921
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1922
            // maybe recycled
1923
0
            LOG_INFO("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1924
0
                    .tag("key", hex(index_key))
1925
0
                    .tag("txn_id", txn_id);
1926
0
            return 0;
1927
0
        }
1928
0
        LOG_WARNING("failed to get txn index")
1929
0
                .tag("err", err)
1930
0
                .tag("key", hex(index_key))
1931
0
                .tag("txn_id", txn_id);
1932
0
        return -1;
1933
0
    }
1934
2
    if (!txn_idx_pb.ParseFromString(index_val)) {
1935
0
        LOG_WARNING("failed to parse txn index")
1936
0
                .tag("err", err)
1937
0
                .tag("key", hex(index_key))
1938
0
                .tag("txn_id", txn_id);
1939
0
        return -1;
1940
0
    }
1941
1942
2
    auto info_key = txn_info_key({instance_id_, txn_idx_pb.tablet_index().db_id(), txn_id});
1943
2
    std::string info_val;
1944
2
    err = txn->get(info_key, &info_val);
1945
2
    if (err != TxnErrorCode::TXN_OK) {
1946
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1947
            // maybe recycled
1948
0
            LOG_INFO("txn info not found, txn_id={} instance_id={}", txn_id, instance_id_)
1949
0
                    .tag("key", hex(info_key))
1950
0
                    .tag("txn_id", txn_id);
1951
0
            return 0;
1952
0
        }
1953
0
        LOG_WARNING("failed to get txn info")
1954
0
                .tag("err", err)
1955
0
                .tag("key", hex(info_key))
1956
0
                .tag("txn_id", txn_id);
1957
0
        return -1;
1958
0
    }
1959
2
    if (!txn_info.ParseFromString(info_val)) {
1960
0
        LOG_WARNING("failed to parse txn info")
1961
0
                .tag("err", err)
1962
0
                .tag("key", hex(info_key))
1963
0
                .tag("txn_id", txn_id);
1964
0
        return -1;
1965
0
    }
1966
1967
2
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
1968
0
        LOG_INFO("txn is not prepared status, txn_id={} status={}", txn_id, txn_info.status())
1969
0
                .tag("key", hex(info_key))
1970
0
                .tag("txn_id", txn_id);
1971
0
        return 0;
1972
0
    }
1973
1974
2
    req.set_txn_id(txn_id);
1975
1976
2
    LOG(INFO) << "begin abort txn for related rowset, txn_id=" << txn_id
1977
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString();
1978
1979
2
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
1980
2
    err = txn->commit();
1981
2
    if (err != TxnErrorCode::TXN_OK) {
1982
0
        code = cast_as<ErrCategory::COMMIT>(err);
1983
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
1984
0
        msg = ss.str();
1985
0
        return -1;
1986
0
    }
1987
1988
2
    LOG(INFO) << "finish abort txn for related rowset, txn_id=" << txn_id
1989
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString()
1990
2
              << " code=" << code << " msg=" << msg;
1991
1992
2
    return 0;
1993
2
}
1994
1995
4
int InstanceRecycler::abort_job_for_related_rowset(const RowsetMetaCloudPB& rowset_meta) {
1996
4
    FinishTabletJobRequest req;
1997
4
    FinishTabletJobResponse res;
1998
4
    req.set_action(FinishTabletJobRequest::ABORT);
1999
4
    MetaServiceCode code = MetaServiceCode::OK;
2000
4
    std::string msg;
2001
4
    std::stringstream ss;
2002
2003
4
    TabletIndexPB tablet_idx;
2004
4
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, rowset_meta.tablet_id(), tablet_idx);
2005
4
    if (ret == 1) {
2006
        // tablet maybe recycled, directly return 0
2007
1
        return 0;
2008
3
    } else if (ret != 0) {
2009
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << rowset_meta.tablet_id()
2010
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
2011
0
        return ret;
2012
0
    }
2013
2014
3
    std::unique_ptr<Transaction> txn;
2015
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2016
3
    if (err != TxnErrorCode::TXN_OK) {
2017
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
2018
0
        return -1;
2019
0
    }
2020
2021
3
    std::string job_key =
2022
3
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
2023
3
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
2024
3
    std::string job_val;
2025
3
    err = txn->get(job_key, &job_val);
2026
3
    if (err != TxnErrorCode::TXN_OK) {
2027
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2028
0
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
2029
0
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2030
0
            return 0;
2031
0
        }
2032
0
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
2033
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
2034
0
                     << " key=" << hex(job_key);
2035
0
        return -1;
2036
0
    }
2037
2038
3
    TabletJobInfoPB job_pb;
2039
3
    if (!job_pb.ParseFromString(job_val)) {
2040
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
2041
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2042
0
        return -1;
2043
0
    }
2044
2045
3
    std::string job_id {};
2046
3
    if (!job_pb.compaction().empty()) {
2047
2
        for (const auto& c : job_pb.compaction()) {
2048
2
            if (c.id() == rowset_meta.job_id()) {
2049
2
                job_id = c.id();
2050
2
                break;
2051
2
            }
2052
2
        }
2053
2
    } else if (job_pb.has_schema_change()) {
2054
1
        job_id = job_pb.schema_change().id();
2055
1
    }
2056
2057
3
    if (!job_id.empty() && rowset_meta.job_id() == job_id) {
2058
3
        LOG(INFO) << "begin to abort job for related rowset, job_id=" << rowset_meta.job_id()
2059
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
2060
3
        req.mutable_job()->CopyFrom(job_pb);
2061
3
        req.set_action(FinishTabletJobRequest::ABORT);
2062
3
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
2063
3
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
2064
3
                           ss);
2065
3
        if (code != MetaServiceCode::OK) {
2066
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
2067
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
2068
0
                         << " msg=" << msg;
2069
0
            return -1;
2070
0
        }
2071
3
        LOG(INFO) << "finish abort job for related rowset, job_id=" << rowset_meta.job_id()
2072
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
2073
3
                  << " code=" << code << " msg=" << msg;
2074
3
    } else {
2075
        // clang-format off
2076
0
        LOG(INFO) << "there is no job for related rowset, directly recycle rowset data"
2077
0
                  << ", instance_id=" << instance_id_ 
2078
0
                  << ", tablet_id=" << tablet_idx.tablet_id() 
2079
0
                  << ", job_id=" << job_id
2080
0
                  << ", rowset_id=" << rowset_meta.rowset_id_v2();
2081
        // clang-format on
2082
0
    }
2083
2084
3
    return 0;
2085
3
}
2086
2087
template <typename T>
2088
13
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2089
13
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2090
9
        return rowset_meta_pb.mutable_rowset_meta();
2091
9
    } else {
2092
9
        return &rowset_meta_pb;
2093
9
    }
2094
13
}
_ZN5doris5cloud19mutable_rowset_metaINS0_15RecycleRowsetPBEEEPNS_17RowsetMetaCloudPBERT_
Line
Count
Source
2088
4
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2089
4
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2090
4
        return rowset_meta_pb.mutable_rowset_meta();
2091
4
    } else {
2092
4
        return &rowset_meta_pb;
2093
4
    }
2094
4
}
_ZN5doris5cloud19mutable_rowset_metaINS_17RowsetMetaCloudPBEEEPS2_RT_
Line
Count
Source
2088
9
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2089
9
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2090
9
        return rowset_meta_pb.mutable_rowset_meta();
2091
9
    } else {
2092
9
        return &rowset_meta_pb;
2093
9
    }
2094
9
}
2095
2096
template <typename T>
2097
51
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2098
51
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2099
35
        return rowset_meta_pb.rowset_meta();
2100
35
    } else {
2101
35
        return rowset_meta_pb;
2102
35
    }
2103
51
}
_ZN5doris5cloud11rowset_metaINS0_15RecycleRowsetPBEEERKNS_17RowsetMetaCloudPBERKT_
Line
Count
Source
2097
16
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2098
16
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2099
16
        return rowset_meta_pb.rowset_meta();
2100
16
    } else {
2101
16
        return rowset_meta_pb;
2102
16
    }
2103
16
}
_ZN5doris5cloud11rowset_metaINS_17RowsetMetaCloudPBEEERKS2_RKT_
Line
Count
Source
2097
35
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2098
35
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2099
35
        return rowset_meta_pb.rowset_meta();
2100
35
    } else {
2101
35
        return rowset_meta_pb;
2102
35
    }
2103
35
}
2104
2105
struct DeferredRecycleAbortTask {
2106
    enum class Type : uint8_t {
2107
        TXN,
2108
        JOB,
2109
    };
2110
2111
    Type type = Type::TXN;
2112
    int64_t txn_id = 0;
2113
    int64_t tablet_id = 0;
2114
    int64_t start_version = 0;
2115
    int64_t end_version = 0;
2116
    std::string rowset_id;
2117
    std::string job_id;
2118
};
2119
2120
struct DeferredRecyclePrepareDeleteTask {
2121
    std::string key;
2122
    std::string resource_id;
2123
    std::string rowset_id;
2124
    int64_t tablet_id = 0;
2125
};
2126
2127
template <typename T>
2128
14
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
2129
14
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2130
4
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2131
0
            return std::nullopt;
2132
0
        }
2133
4
    }
2134
2135
4
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2136
4
    DeferredRecycleAbortTask task;
2137
4
    task.tablet_id = rs_meta.tablet_id();
2138
4
    task.start_version = rs_meta.start_version();
2139
4
    task.end_version = rs_meta.end_version();
2140
14
    if (rs_meta.has_load_id()) {
2141
4
        task.type = DeferredRecycleAbortTask::Type::TXN;
2142
4
        task.txn_id = rs_meta.txn_id();
2143
4
        return task;
2144
4
    }
2145
10
    if (rs_meta.has_job_id()) {
2146
6
        task.type = DeferredRecycleAbortTask::Type::JOB;
2147
6
        task.rowset_id = rs_meta.rowset_id_v2();
2148
6
        task.job_id = rs_meta.job_id();
2149
6
        return task;
2150
6
    }
2151
4
    return std::nullopt;
2152
10
}
_ZN5doris5cloud24make_deferred_abort_taskINS0_15RecycleRowsetPBEEESt8optionalINS0_24DeferredRecycleAbortTaskEERKT_
Line
Count
Source
2128
4
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
2129
4
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2130
4
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2131
0
            return std::nullopt;
2132
0
        }
2133
4
    }
2134
2135
4
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2136
4
    DeferredRecycleAbortTask task;
2137
4
    task.tablet_id = rs_meta.tablet_id();
2138
4
    task.start_version = rs_meta.start_version();
2139
4
    task.end_version = rs_meta.end_version();
2140
4
    if (rs_meta.has_load_id()) {
2141
2
        task.type = DeferredRecycleAbortTask::Type::TXN;
2142
2
        task.txn_id = rs_meta.txn_id();
2143
2
        return task;
2144
2
    }
2145
2
    if (rs_meta.has_job_id()) {
2146
2
        task.type = DeferredRecycleAbortTask::Type::JOB;
2147
2
        task.rowset_id = rs_meta.rowset_id_v2();
2148
2
        task.job_id = rs_meta.job_id();
2149
2
        return task;
2150
2
    }
2151
0
    return std::nullopt;
2152
2
}
_ZN5doris5cloud24make_deferred_abort_taskINS_17RowsetMetaCloudPBEEESt8optionalINS0_24DeferredRecycleAbortTaskEERKT_
Line
Count
Source
2128
10
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
2129
10
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2130
10
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2131
10
            return std::nullopt;
2132
10
        }
2133
10
    }
2134
2135
10
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2136
10
    DeferredRecycleAbortTask task;
2137
10
    task.tablet_id = rs_meta.tablet_id();
2138
10
    task.start_version = rs_meta.start_version();
2139
10
    task.end_version = rs_meta.end_version();
2140
10
    if (rs_meta.has_load_id()) {
2141
2
        task.type = DeferredRecycleAbortTask::Type::TXN;
2142
2
        task.txn_id = rs_meta.txn_id();
2143
2
        return task;
2144
2
    }
2145
8
    if (rs_meta.has_job_id()) {
2146
4
        task.type = DeferredRecycleAbortTask::Type::JOB;
2147
4
        task.rowset_id = rs_meta.rowset_id_v2();
2148
4
        task.job_id = rs_meta.job_id();
2149
4
        return task;
2150
4
    }
2151
4
    return std::nullopt;
2152
8
}
2153
2154
template <typename T>
2155
35
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
2156
35
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2157
35
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
2158
35
}
_ZN5doris5cloud28need_mark_rowset_as_recycledINS0_15RecycleRowsetPBEEEbRKT_
Line
Count
Source
2155
10
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
2156
10
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2157
10
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
2158
10
}
_ZN5doris5cloud28need_mark_rowset_as_recycledINS_17RowsetMetaCloudPBEEEbRKT_
Line
Count
Source
2155
25
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
2156
25
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2157
25
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
2158
25
}
2159
2160
template <typename T>
2161
int batch_mark_rowsets_as_recycled(TxnKv* txn_kv, const std::string& instance_id,
2162
11
                                   const std::vector<std::string>& keys) {
2163
11
    std::unique_ptr<Transaction> txn;
2164
11
    TxnErrorCode err = txn_kv->create_txn(&txn);
2165
11
    if (err != TxnErrorCode::TXN_OK) {
2166
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2167
0
        return -1;
2168
0
    }
2169
11
    std::vector<std::optional<std::string>> values;
2170
11
    err = txn->batch_get(&values, keys);
2171
11
    if (err != TxnErrorCode::TXN_OK) {
2172
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2173
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
2174
0
        return -1;
2175
0
    }
2176
11
    size_t total_keys = keys.size();
2177
24
    for (size_t i = 0; i < total_keys; i++) {
2178
13
        if (!values[i].has_value()) {
2179
            // has already been removed by commit_rowset
2180
0
            continue;
2181
0
        }
2182
13
        auto key = keys[i];
2183
13
        auto val = values[i].value();
2184
13
        T rowset_meta_pb;
2185
13
        if (!rowset_meta_pb.ParseFromString(val)) {
2186
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2187
0
                         << " key=" << hex(key);
2188
0
            return -1;
2189
0
        }
2190
13
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
2191
0
            continue;
2192
0
        }
2193
13
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2194
13
        val.clear();
2195
13
        rowset_meta_pb.SerializeToString(&val);
2196
13
        txn->put(key, val);
2197
13
    }
2198
11
    err = txn->commit();
2199
11
    if (err != TxnErrorCode::TXN_OK) {
2200
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2201
0
        return -1;
2202
0
    }
2203
2204
11
    return 0;
2205
11
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2162
4
                                   const std::vector<std::string>& keys) {
2163
4
    std::unique_ptr<Transaction> txn;
2164
4
    TxnErrorCode err = txn_kv->create_txn(&txn);
2165
4
    if (err != TxnErrorCode::TXN_OK) {
2166
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2167
0
        return -1;
2168
0
    }
2169
4
    std::vector<std::optional<std::string>> values;
2170
4
    err = txn->batch_get(&values, keys);
2171
4
    if (err != TxnErrorCode::TXN_OK) {
2172
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2173
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
2174
0
        return -1;
2175
0
    }
2176
4
    size_t total_keys = keys.size();
2177
8
    for (size_t i = 0; i < total_keys; i++) {
2178
4
        if (!values[i].has_value()) {
2179
            // has already been removed by commit_rowset
2180
0
            continue;
2181
0
        }
2182
4
        auto key = keys[i];
2183
4
        auto val = values[i].value();
2184
4
        T rowset_meta_pb;
2185
4
        if (!rowset_meta_pb.ParseFromString(val)) {
2186
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2187
0
                         << " key=" << hex(key);
2188
0
            return -1;
2189
0
        }
2190
4
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
2191
0
            continue;
2192
0
        }
2193
4
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2194
4
        val.clear();
2195
4
        rowset_meta_pb.SerializeToString(&val);
2196
4
        txn->put(key, val);
2197
4
    }
2198
4
    err = txn->commit();
2199
4
    if (err != TxnErrorCode::TXN_OK) {
2200
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2201
0
        return -1;
2202
0
    }
2203
2204
4
    return 0;
2205
4
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2162
7
                                   const std::vector<std::string>& keys) {
2163
7
    std::unique_ptr<Transaction> txn;
2164
7
    TxnErrorCode err = txn_kv->create_txn(&txn);
2165
7
    if (err != TxnErrorCode::TXN_OK) {
2166
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2167
0
        return -1;
2168
0
    }
2169
7
    std::vector<std::optional<std::string>> values;
2170
7
    err = txn->batch_get(&values, keys);
2171
7
    if (err != TxnErrorCode::TXN_OK) {
2172
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2173
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
2174
0
        return -1;
2175
0
    }
2176
7
    size_t total_keys = keys.size();
2177
16
    for (size_t i = 0; i < total_keys; i++) {
2178
9
        if (!values[i].has_value()) {
2179
            // has already been removed by commit_rowset
2180
0
            continue;
2181
0
        }
2182
9
        auto key = keys[i];
2183
9
        auto val = values[i].value();
2184
9
        T rowset_meta_pb;
2185
9
        if (!rowset_meta_pb.ParseFromString(val)) {
2186
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2187
0
                         << " key=" << hex(key);
2188
0
            return -1;
2189
0
        }
2190
9
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
2191
0
            continue;
2192
0
        }
2193
9
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2194
9
        val.clear();
2195
9
        rowset_meta_pb.SerializeToString(&val);
2196
9
        txn->put(key, val);
2197
9
    }
2198
7
    err = txn->commit();
2199
7
    if (err != TxnErrorCode::TXN_OK) {
2200
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2201
0
        return -1;
2202
0
    }
2203
2204
7
    return 0;
2205
7
}
2206
2207
template <typename T>
2208
int collect_deferred_abort_tasks(TxnKv* txn_kv, const std::string& instance_id,
2209
                                 const std::vector<std::string>& keys,
2210
                                 std::vector<DeferredRecycleAbortTask>* abort_tasks,
2211
5
                                 bool skip_base_version) {
2212
5
    constexpr size_t kAbortCheckBatchSize = 256;
2213
10
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2214
5
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2215
5
        std::unique_ptr<Transaction> txn;
2216
5
        TxnErrorCode err = txn_kv->create_txn(&txn);
2217
5
        if (err != TxnErrorCode::TXN_OK) {
2218
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2219
0
            return -1;
2220
0
        }
2221
10
        for (size_t idx = offset; idx < limit; ++idx) {
2222
5
            const std::string& key = keys[idx];
2223
5
            std::string val;
2224
5
            err = txn->get(key, &val);
2225
5
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2226
                // has already been removed
2227
0
                continue;
2228
0
            }
2229
5
            if (err != TxnErrorCode::TXN_OK) {
2230
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2231
0
                             << " key=" << hex(key);
2232
0
                return -1;
2233
0
            }
2234
5
            T rowset_meta_pb;
2235
5
            if (!rowset_meta_pb.ParseFromString(val)) {
2236
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2237
0
                             << " key=" << hex(key);
2238
0
                return -1;
2239
0
            }
2240
5
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2241
0
                continue;
2242
0
            }
2243
5
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2244
5
                abort_task.has_value()) {
2245
5
                abort_tasks->emplace_back(std::move(*abort_task));
2246
5
            }
2247
5
        }
2248
5
    }
2249
5
    return 0;
2250
5
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24DeferredRecycleAbortTaskESaISI_EEb
Line
Count
Source
2211
2
                                 bool skip_base_version) {
2212
2
    constexpr size_t kAbortCheckBatchSize = 256;
2213
4
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2214
2
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2215
2
        std::unique_ptr<Transaction> txn;
2216
2
        TxnErrorCode err = txn_kv->create_txn(&txn);
2217
2
        if (err != TxnErrorCode::TXN_OK) {
2218
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2219
0
            return -1;
2220
0
        }
2221
4
        for (size_t idx = offset; idx < limit; ++idx) {
2222
2
            const std::string& key = keys[idx];
2223
2
            std::string val;
2224
2
            err = txn->get(key, &val);
2225
2
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2226
                // has already been removed
2227
0
                continue;
2228
0
            }
2229
2
            if (err != TxnErrorCode::TXN_OK) {
2230
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2231
0
                             << " key=" << hex(key);
2232
0
                return -1;
2233
0
            }
2234
2
            T rowset_meta_pb;
2235
2
            if (!rowset_meta_pb.ParseFromString(val)) {
2236
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2237
0
                             << " key=" << hex(key);
2238
0
                return -1;
2239
0
            }
2240
2
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2241
0
                continue;
2242
0
            }
2243
2
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2244
2
                abort_task.has_value()) {
2245
2
                abort_tasks->emplace_back(std::move(*abort_task));
2246
2
            }
2247
2
        }
2248
2
    }
2249
2
    return 0;
2250
2
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24DeferredRecycleAbortTaskESaISI_EEb
Line
Count
Source
2211
3
                                 bool skip_base_version) {
2212
3
    constexpr size_t kAbortCheckBatchSize = 256;
2213
6
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2214
3
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2215
3
        std::unique_ptr<Transaction> txn;
2216
3
        TxnErrorCode err = txn_kv->create_txn(&txn);
2217
3
        if (err != TxnErrorCode::TXN_OK) {
2218
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2219
0
            return -1;
2220
0
        }
2221
6
        for (size_t idx = offset; idx < limit; ++idx) {
2222
3
            const std::string& key = keys[idx];
2223
3
            std::string val;
2224
3
            err = txn->get(key, &val);
2225
3
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2226
                // has already been removed
2227
0
                continue;
2228
0
            }
2229
3
            if (err != TxnErrorCode::TXN_OK) {
2230
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2231
0
                             << " key=" << hex(key);
2232
0
                return -1;
2233
0
            }
2234
3
            T rowset_meta_pb;
2235
3
            if (!rowset_meta_pb.ParseFromString(val)) {
2236
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2237
0
                             << " key=" << hex(key);
2238
0
                return -1;
2239
0
            }
2240
3
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2241
0
                continue;
2242
0
            }
2243
3
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2244
3
                abort_task.has_value()) {
2245
3
                abort_tasks->emplace_back(std::move(*abort_task));
2246
3
            }
2247
3
        }
2248
3
    }
2249
3
    return 0;
2250
3
}
2251
2252
template <typename T>
2253
int InstanceRecycler::batch_abort_txn_or_job_for_recycle(const std::vector<std::string>& keys,
2254
5
                                                         bool skip_base_version) {
2255
5
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2256
5
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2257
5
                                        skip_base_version) != 0) {
2258
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2259
0
        return -1;
2260
0
    }
2261
5
    for (const auto& abort_task : abort_tasks) {
2262
5
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2263
5
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2264
5
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2265
5
        int abort_ret = 0;
2266
5
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2267
2
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2268
3
        } else {
2269
3
            RowsetMetaCloudPB rowset_meta;
2270
3
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2271
3
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2272
3
            rowset_meta.set_job_id(abort_task.job_id);
2273
3
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2274
3
        }
2275
5
        if (abort_ret != 0) {
2276
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2277
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2278
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2279
0
            return abort_ret;
2280
0
        }
2281
5
    }
2282
5
    return 0;
2283
5
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEb
Line
Count
Source
2254
2
                                                         bool skip_base_version) {
2255
2
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2256
2
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2257
2
                                        skip_base_version) != 0) {
2258
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2259
0
        return -1;
2260
0
    }
2261
2
    for (const auto& abort_task : abort_tasks) {
2262
2
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2263
2
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2264
2
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2265
2
        int abort_ret = 0;
2266
2
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2267
1
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2268
1
        } else {
2269
1
            RowsetMetaCloudPB rowset_meta;
2270
1
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2271
1
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2272
1
            rowset_meta.set_job_id(abort_task.job_id);
2273
1
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2274
1
        }
2275
2
        if (abort_ret != 0) {
2276
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2277
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2278
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2279
0
            return abort_ret;
2280
0
        }
2281
2
    }
2282
2
    return 0;
2283
2
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEb
Line
Count
Source
2254
3
                                                         bool skip_base_version) {
2255
3
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2256
3
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2257
3
                                        skip_base_version) != 0) {
2258
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2259
0
        return -1;
2260
0
    }
2261
3
    for (const auto& abort_task : abort_tasks) {
2262
3
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2263
3
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2264
3
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2265
3
        int abort_ret = 0;
2266
3
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2267
1
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2268
2
        } else {
2269
2
            RowsetMetaCloudPB rowset_meta;
2270
2
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2271
2
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2272
2
            rowset_meta.set_job_id(abort_task.job_id);
2273
2
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2274
2
        }
2275
3
        if (abort_ret != 0) {
2276
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2277
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2278
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2279
0
            return abort_ret;
2280
0
        }
2281
3
    }
2282
3
    return 0;
2283
3
}
2284
2285
int collect_prepare_delete_tasks(TxnKv* txn_kv, const std::string& instance_id,
2286
                                 const std::vector<std::string>& keys,
2287
0
                                 std::vector<DeferredRecyclePrepareDeleteTask>* delete_tasks) {
2288
0
    constexpr size_t kPrepareCheckBatchSize = 256;
2289
0
    for (size_t offset = 0; offset < keys.size(); offset += kPrepareCheckBatchSize) {
2290
0
        size_t limit = std::min(keys.size(), offset + kPrepareCheckBatchSize);
2291
0
        std::unique_ptr<Transaction> txn;
2292
0
        TxnErrorCode err = txn_kv->create_txn(&txn);
2293
0
        if (err != TxnErrorCode::TXN_OK) {
2294
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2295
0
            return -1;
2296
0
        }
2297
0
        for (size_t idx = offset; idx < limit; ++idx) {
2298
0
            const std::string& key = keys[idx];
2299
0
            std::string val;
2300
0
            err = txn->get(key, &val);
2301
0
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2302
                // has already been removed
2303
0
                continue;
2304
0
            }
2305
0
            if (err != TxnErrorCode::TXN_OK) {
2306
0
                LOG(WARNING) << "failed to get recycle rowset, instance_id=" << instance_id
2307
0
                             << " key=" << hex(key);
2308
0
                return -1;
2309
0
            }
2310
0
            RecycleRowsetPB rowset;
2311
0
            if (!rowset.ParseFromString(val)) {
2312
0
                LOG(WARNING) << "failed to parse recycle rowset, instance_id=" << instance_id
2313
0
                             << " key=" << hex(key);
2314
0
                return -1;
2315
0
            }
2316
0
            if (rowset.type() != RecycleRowsetPB::PREPARE) {
2317
0
                continue;
2318
0
            }
2319
0
            const auto& rs_meta = rowset.rowset_meta();
2320
0
            delete_tasks->push_back(
2321
0
                    {key, rs_meta.resource_id(), rs_meta.rowset_id_v2(), rs_meta.tablet_id()});
2322
0
        }
2323
0
    }
2324
0
    return 0;
2325
0
}
2326
2327
1
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
2328
1
    const std::string task_name = "recycle_ref_rowsets";
2329
1
    *has_unrecycled_rowsets = false;
2330
2331
1
    std::string data_rowset_ref_count_key_start =
2332
1
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
2333
1
    std::string data_rowset_ref_count_key_end =
2334
1
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
2335
2336
1
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
2337
2338
1
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2339
1
    register_recycle_task(task_name, start_time);
2340
2341
1
    DORIS_CLOUD_DEFER {
2342
1
        unregister_recycle_task(task_name);
2343
1
        int64_t cost =
2344
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2345
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2346
1
                .tag("instance_id", instance_id_);
2347
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Line
Count
Source
2341
1
    DORIS_CLOUD_DEFER {
2342
1
        unregister_recycle_task(task_name);
2343
1
        int64_t cost =
2344
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2345
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2346
1
                .tag("instance_id", instance_id_);
2347
1
    };
2348
2349
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
2350
1
    std::set<int64_t> tablets_with_refs;
2351
1
    int64_t num_scanned = 0;
2352
2353
1
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
2354
0
        ++num_scanned;
2355
0
        int64_t tablet_id;
2356
0
        std::string rowset_id;
2357
0
        std::string_view key(k);
2358
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
2359
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
2360
0
            return 0; // Continue scanning
2361
0
        }
2362
2363
0
        tablets_with_refs.insert(tablet_id);
2364
0
        return 0;
2365
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
2366
2367
1
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
2368
1
                         std::move(scan_func)) != 0) {
2369
0
        LOG_WARNING("failed to scan data rowset ref count keys");
2370
0
        return -1;
2371
0
    }
2372
2373
1
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
2374
1
             tablets_with_refs.size(), num_scanned)
2375
1
            .tag("instance_id", instance_id_);
2376
2377
    // Phase 2: Recycle each tablet
2378
1
    int64_t num_recycled_tablets = 0;
2379
1
    for (int64_t tablet_id : tablets_with_refs) {
2380
0
        if (stopped()) {
2381
0
            LOG_INFO("recycler stopped, skip remaining tablets")
2382
0
                    .tag("instance_id", instance_id_)
2383
0
                    .tag("tablets_processed", num_recycled_tablets)
2384
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
2385
0
            break;
2386
0
        }
2387
2388
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
2389
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
2390
0
            LOG_WARNING("failed to recycle tablet")
2391
0
                    .tag("instance_id", instance_id_)
2392
0
                    .tag("tablet_id", tablet_id);
2393
0
            return -1;
2394
0
        }
2395
0
        ++num_recycled_tablets;
2396
0
    }
2397
2398
1
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
2399
1
            .tag("instance_id", instance_id_)
2400
1
            .tag("total_tablets", tablets_with_refs.size());
2401
2402
    // Phase 3: Scan again to check if any ref count keys still exist
2403
1
    std::unique_ptr<Transaction> txn;
2404
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2405
1
    if (err != TxnErrorCode::TXN_OK) {
2406
0
        LOG_WARNING("failed to create txn for final check")
2407
0
                .tag("instance_id", instance_id_)
2408
0
                .tag("err", err);
2409
0
        return -1;
2410
0
    }
2411
2412
1
    std::unique_ptr<RangeGetIterator> iter;
2413
1
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2414
1
    if (err != TxnErrorCode::TXN_OK) {
2415
0
        LOG_WARNING("failed to create range iterator for final check")
2416
0
                .tag("instance_id", instance_id_)
2417
0
                .tag("err", err);
2418
0
        return -1;
2419
0
    }
2420
2421
1
    *has_unrecycled_rowsets = iter->has_next();
2422
1
    if (*has_unrecycled_rowsets) {
2423
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2424
0
                .tag("instance_id", instance_id_);
2425
0
    }
2426
2427
1
    return 0;
2428
1
}
2429
2430
int InstanceRecycler::recycle_table_stream_offset_prefix(std::string prefix,
2431
6
                                                         RecyclerMetricsContext* metrics_context) {
2432
6
    std::string end = prefix;
2433
6
    end.push_back('\xff');
2434
6
    std::vector<std::string_view> keys;
2435
8
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2436
8
        keys.push_back(key);
2437
8
        return 0;
2438
8
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_1clESt17basic_string_viewIcS5_ESC_
Line
Count
Source
2435
2
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2436
2
        keys.push_back(key);
2437
2
        return 0;
2438
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_1clESt17basic_string_viewIcS5_ESC_
Line
Count
Source
2435
6
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2436
6
        keys.push_back(key);
2437
6
        return 0;
2438
6
    };
2439
6
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2440
4
        if (keys.empty()) {
2441
0
            return 0;
2442
0
        }
2443
4
        DORIS_CLOUD_DEFER {
2444
4
            keys.clear();
2445
4
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlvE_clEv
Line
Count
Source
2443
2
        DORIS_CLOUD_DEFER {
2444
2
            keys.clear();
2445
2
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlvE_clEv
Line
Count
Source
2443
2
        DORIS_CLOUD_DEFER {
2444
2
            keys.clear();
2445
2
        };
2446
4
        const size_t num_keys = keys.size();
2447
4
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2448
0
            LOG_WARNING("failed to delete table stream offsets")
2449
0
                    .tag("instance_id", instance_id_)
2450
0
                    .tag("num_keys", num_keys);
2451
0
            return -1;
2452
0
        }
2453
4
        metrics_context->total_recycled_num += num_keys;
2454
4
        metrics_context->report();
2455
4
        return 0;
2456
4
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2439
2
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2440
2
        if (keys.empty()) {
2441
0
            return 0;
2442
0
        }
2443
2
        DORIS_CLOUD_DEFER {
2444
2
            keys.clear();
2445
2
        };
2446
2
        const size_t num_keys = keys.size();
2447
2
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2448
0
            LOG_WARNING("failed to delete table stream offsets")
2449
0
                    .tag("instance_id", instance_id_)
2450
0
                    .tag("num_keys", num_keys);
2451
0
            return -1;
2452
0
        }
2453
2
        metrics_context->total_recycled_num += num_keys;
2454
2
        metrics_context->report();
2455
2
        return 0;
2456
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2439
2
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2440
2
        if (keys.empty()) {
2441
0
            return 0;
2442
0
        }
2443
2
        DORIS_CLOUD_DEFER {
2444
2
            keys.clear();
2445
2
        };
2446
2
        const size_t num_keys = keys.size();
2447
2
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2448
0
            LOG_WARNING("failed to delete table stream offsets")
2449
0
                    .tag("instance_id", instance_id_)
2450
0
                    .tag("num_keys", num_keys);
2451
0
            return -1;
2452
0
        }
2453
2
        metrics_context->total_recycled_num += num_keys;
2454
2
        metrics_context->report();
2455
2
        return 0;
2456
2
    };
2457
6
    return scan_and_recycle(std::move(prefix), end, std::move(collect_key), std::move(remove_keys));
2458
6
}
2459
2460
int InstanceRecycler::finalize_recycle_stream(int64_t stream_id,
2461
                                              const RecycleIndexPB& recycle_index,
2462
3
                                              std::string_view recycle_key) {
2463
3
    std::unique_ptr<Transaction> txn;
2464
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2465
3
    if (err != TxnErrorCode::TXN_OK) {
2466
0
        LOG_WARNING("failed to create transaction for final table stream cleanup")
2467
0
                .tag("instance_id", instance_id_)
2468
0
                .tag("stream_id", stream_id)
2469
0
                .tag("err", err);
2470
0
        return -1;
2471
0
    }
2472
2473
3
    std::string current_recycle_value;
2474
3
    err = txn->get(recycle_key, &current_recycle_value);
2475
3
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2476
0
        return 0;
2477
0
    }
2478
3
    if (err != TxnErrorCode::TXN_OK) {
2479
0
        LOG_WARNING("failed to read table stream recycle index")
2480
0
                .tag("instance_id", instance_id_)
2481
0
                .tag("stream_id", stream_id)
2482
0
                .tag("err", err);
2483
0
        return -1;
2484
0
    }
2485
3
    RecycleIndexPB current_recycle_index;
2486
3
    if (!current_recycle_index.ParseFromString(current_recycle_value) ||
2487
3
        current_recycle_index.state() != RecycleIndexPB::RECYCLING ||
2488
3
        current_recycle_index.object_type() != IndexObjectTypePB::TABLE_STREAM ||
2489
3
        current_recycle_index.db_id() != recycle_index.db_id() ||
2490
3
        current_recycle_index.table_id() != recycle_index.table_id() ||
2491
3
        current_recycle_index.stream_db_id() != recycle_index.stream_db_id()) {
2492
0
        LOG_WARNING("table stream recycle index changed during recycling")
2493
0
                .tag("instance_id", instance_id_)
2494
0
                .tag("stream_id", stream_id);
2495
0
        return -1;
2496
0
    }
2497
2498
3
    txn->remove(recycle_key);
2499
3
    err = txn->commit();
2500
3
    if (err != TxnErrorCode::TXN_OK) {
2501
0
        LOG_WARNING("failed to commit final table stream cleanup")
2502
0
                .tag("instance_id", instance_id_)
2503
0
                .tag("stream_id", stream_id)
2504
0
                .tag("err", err);
2505
0
        return -1;
2506
0
    }
2507
3
    return 0;
2508
3
}
2509
2510
int InstanceRecycler::recycle_stream(int64_t stream_id, const RecycleIndexPB& recycle_index,
2511
3
                                     std::string_view recycle_key) {
2512
3
    if (!recycle_index.has_db_id() || !recycle_index.has_stream_db_id()) {
2513
0
        LOG_WARNING("table stream recycle index is missing binding")
2514
0
                .tag("instance_id", instance_id_)
2515
0
                .tag("stream_id", stream_id);
2516
0
        return -1;
2517
0
    }
2518
2519
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stream");
2520
3
    DORIS_CLOUD_DEFER {
2521
3
        metrics_context.finish_report();
2522
3
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_streamElRKNS0_14RecycleIndexPBESt17basic_string_viewIcSt11char_traitsIcEEENK3$_0clEv
Line
Count
Source
2520
2
    DORIS_CLOUD_DEFER {
2521
2
        metrics_context.finish_report();
2522
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_streamElRKNS0_14RecycleIndexPBESt17basic_string_viewIcSt11char_traitsIcEEENK3$_0clEv
Line
Count
Source
2520
1
    DORIS_CLOUD_DEFER {
2521
1
        metrics_context.finish_report();
2522
1
    };
2523
3
    const std::string latest_offset_prefix = table_stream_offset_key_prefix(
2524
3
            instance_id_, recycle_index.db_id(), recycle_index.table_id(),
2525
3
            recycle_index.stream_db_id(), stream_id);
2526
3
    if (recycle_table_stream_offset_prefix(latest_offset_prefix, &metrics_context) != 0) {
2527
0
        return -1;
2528
0
    }
2529
3
    const std::string versioned_offset_prefix = versioned::table_stream_offset_key_prefix(
2530
3
            instance_id_, recycle_index.db_id(), recycle_index.table_id(),
2531
3
            recycle_index.stream_db_id(), stream_id);
2532
3
    if (recycle_table_stream_offset_prefix(versioned_offset_prefix, &metrics_context) != 0 ||
2533
3
        stopped()) {
2534
0
        return -1;
2535
0
    }
2536
3
    return finalize_recycle_stream(stream_id, recycle_index, recycle_key);
2537
3
}
2538
2539
int InstanceRecycler::recycle_partition_table_stream_offsets(
2540
        int64_t db_id, int64_t table_id, int64_t partition_id,
2541
10
        const google::protobuf::RepeatedPtrField<TableStreamIdentityPB>& table_streams) {
2542
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stream_partition_offsets");
2543
10
    DORIS_CLOUD_DEFER {
2544
10
        metrics_context.finish_report();
2545
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler38recycle_partition_table_stream_offsetsElllRKN6google8protobuf16RepeatedPtrFieldINS0_21TableStreamIdentityPBEEEENK3$_0clEv
Line
Count
Source
2543
1
    DORIS_CLOUD_DEFER {
2544
1
        metrics_context.finish_report();
2545
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler38recycle_partition_table_stream_offsetsElllRKN6google8protobuf16RepeatedPtrFieldINS0_21TableStreamIdentityPBEEEENK3$_0clEv
Line
Count
Source
2543
9
    DORIS_CLOUD_DEFER {
2544
9
        metrics_context.finish_report();
2545
9
    };
2546
10
    const size_t batch_size = std::max(1, config::recycler_max_tasks_per_batch);
2547
12
    for (size_t begin_index = 0; begin_index < table_streams.size(); begin_index += batch_size) {
2548
2
        const size_t end_index =
2549
2
                std::min(static_cast<size_t>(table_streams.size()), begin_index + batch_size);
2550
2
        std::unique_ptr<Transaction> txn;
2551
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2552
2
        if (err != TxnErrorCode::TXN_OK) {
2553
0
            LOG_WARNING("failed to create transaction for partition stream offset cleanup")
2554
0
                    .tag("instance_id", instance_id_)
2555
0
                    .tag("partition_id", partition_id)
2556
0
                    .tag("err", err);
2557
0
            return -1;
2558
0
        }
2559
4
        for (size_t i = begin_index; i < end_index; ++i) {
2560
2
            const TableStreamIdentityPB& stream = table_streams.Get(i);
2561
2
            if (stream.base_db_id() != db_id || stream.base_table_id() != table_id ||
2562
2
                stream.stream_db_id() <= 0 || stream.stream_id() <= 0) {
2563
0
                LOG_WARNING("invalid table stream binding in recycle partition")
2564
0
                        .tag("instance_id", instance_id_)
2565
0
                        .tag("partition_id", partition_id)
2566
0
                        .tag("stream_id", stream.stream_id());
2567
0
                return -1;
2568
0
            }
2569
2
            txn->remove(table_stream_offset_key({instance_id_, stream.base_db_id(),
2570
2
                                                 stream.base_table_id(), stream.stream_db_id(),
2571
2
                                                 stream.stream_id(), partition_id}));
2572
2
            versioned_remove_all(
2573
2
                    txn.get(), versioned::table_stream_offset_key(
2574
2
                                       {instance_id_, stream.base_db_id(), stream.base_table_id(),
2575
2
                                        stream.stream_db_id(), stream.stream_id(), partition_id}));
2576
2
        }
2577
2
        err = txn->commit();
2578
2
        if (err != TxnErrorCode::TXN_OK) {
2579
0
            LOG_WARNING("failed to commit partition stream offset cleanup")
2580
0
                    .tag("instance_id", instance_id_)
2581
0
                    .tag("partition_id", partition_id)
2582
0
                    .tag("err", err);
2583
0
            return -1;
2584
0
        }
2585
2
        metrics_context.total_recycled_num += end_index - begin_index;
2586
2
        metrics_context.report();
2587
2
    }
2588
10
    return 0;
2589
10
}
2590
2591
19
int InstanceRecycler::recycle_indexes() {
2592
19
    const std::string task_name = "recycle_indexes";
2593
19
    int64_t num_scanned = 0;
2594
19
    int64_t num_expired = 0;
2595
19
    int64_t num_recycled = 0;
2596
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2597
2598
19
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2599
19
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2600
19
    std::string index_key0;
2601
19
    std::string index_key1;
2602
19
    recycle_index_key(index_key_info0, &index_key0);
2603
19
    recycle_index_key(index_key_info1, &index_key1);
2604
2605
19
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2606
2607
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2608
19
    register_recycle_task(task_name, start_time);
2609
2610
19
    DORIS_CLOUD_DEFER {
2611
19
        unregister_recycle_task(task_name);
2612
19
        int64_t cost =
2613
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2614
19
        metrics_context.finish_report();
2615
19
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2616
19
                .tag("instance_id", instance_id_)
2617
19
                .tag("num_scanned", num_scanned)
2618
19
                .tag("num_expired", num_expired)
2619
19
                .tag("num_recycled", num_recycled);
2620
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2610
3
    DORIS_CLOUD_DEFER {
2611
3
        unregister_recycle_task(task_name);
2612
3
        int64_t cost =
2613
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2614
3
        metrics_context.finish_report();
2615
3
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2616
3
                .tag("instance_id", instance_id_)
2617
3
                .tag("num_scanned", num_scanned)
2618
3
                .tag("num_expired", num_expired)
2619
3
                .tag("num_recycled", num_recycled);
2620
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2610
16
    DORIS_CLOUD_DEFER {
2611
16
        unregister_recycle_task(task_name);
2612
16
        int64_t cost =
2613
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2614
16
        metrics_context.finish_report();
2615
16
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2616
16
                .tag("instance_id", instance_id_)
2617
16
                .tag("num_scanned", num_scanned)
2618
16
                .tag("num_expired", num_expired)
2619
16
                .tag("num_recycled", num_recycled);
2620
16
    };
2621
2622
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2623
2624
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2625
19
    std::vector<std::string_view> index_keys;
2626
19
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2627
13
        ++num_scanned;
2628
13
        RecycleIndexPB index_pb;
2629
13
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2630
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2631
0
            return -1;
2632
0
        }
2633
13
        int64_t current_time = ::time(nullptr);
2634
13
        if (current_time <
2635
13
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2636
0
            return 0;
2637
0
        }
2638
13
        ++num_expired;
2639
        // decode index_id
2640
13
        auto k1 = k;
2641
13
        k1.remove_prefix(1);
2642
13
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2643
13
        decode_key(&k1, &out);
2644
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2645
13
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2646
13
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2647
13
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2648
13
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2649
        // Change state to RECYCLING
2650
13
        std::unique_ptr<Transaction> txn;
2651
13
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2652
13
        if (err != TxnErrorCode::TXN_OK) {
2653
0
            LOG_WARNING("failed to create txn").tag("err", err);
2654
0
            return -1;
2655
0
        }
2656
13
        std::string val;
2657
13
        err = txn->get(k, &val);
2658
13
        if (err ==
2659
13
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2660
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2661
0
            return 0;
2662
0
        }
2663
13
        if (err != TxnErrorCode::TXN_OK) {
2664
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2665
0
            return -1;
2666
0
        }
2667
13
        index_pb.Clear();
2668
13
        if (!index_pb.ParseFromString(val)) {
2669
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2670
0
            return -1;
2671
0
        }
2672
13
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2673
12
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2674
12
            txn->put(k, index_pb.SerializeAsString());
2675
12
            err = txn->commit();
2676
12
            if (err != TxnErrorCode::TXN_OK) {
2677
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2678
0
                return -1;
2679
0
            }
2680
12
        }
2681
13
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
2682
3
            if (recycle_stream(index_id, index_pb, k) != 0) {
2683
0
                LOG_WARNING("failed to recycle table stream")
2684
0
                        .tag("instance_id", instance_id_)
2685
0
                        .tag("stream_id", index_id);
2686
0
                return -1;
2687
0
            }
2688
3
            metrics_context.total_recycled_num = ++num_recycled;
2689
3
            metrics_context.report();
2690
3
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2691
3
            return 0;
2692
3
        }
2693
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2694
1
            LOG_WARNING("failed to recycle tablets under index")
2695
1
                    .tag("table_id", index_pb.table_id())
2696
1
                    .tag("instance_id", instance_id_)
2697
1
                    .tag("index_id", index_id);
2698
1
            return -1;
2699
1
        }
2700
2701
9
        if (index_pb.has_db_id()) {
2702
            // Recycle the versioned keys
2703
3
            std::unique_ptr<Transaction> txn;
2704
3
            err = txn_kv_->create_txn(&txn);
2705
3
            if (err != TxnErrorCode::TXN_OK) {
2706
0
                LOG_WARNING("failed to create txn").tag("err", err);
2707
0
                return -1;
2708
0
            }
2709
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2710
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2711
3
            std::string index_inverted_key = versioned::index_inverted_key(
2712
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2713
3
            versioned_remove_all(txn.get(), meta_key);
2714
3
            txn->remove(index_key);
2715
3
            txn->remove(index_inverted_key);
2716
3
            err = txn->commit();
2717
3
            if (err != TxnErrorCode::TXN_OK) {
2718
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2719
0
                return -1;
2720
0
            }
2721
3
        }
2722
2723
9
        metrics_context.total_recycled_num = ++num_recycled;
2724
9
        metrics_context.report();
2725
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2726
9
        index_keys.push_back(k);
2727
9
        return 0;
2728
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2626
4
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2627
4
        ++num_scanned;
2628
4
        RecycleIndexPB index_pb;
2629
4
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2630
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2631
0
            return -1;
2632
0
        }
2633
4
        int64_t current_time = ::time(nullptr);
2634
4
        if (current_time <
2635
4
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2636
0
            return 0;
2637
0
        }
2638
4
        ++num_expired;
2639
        // decode index_id
2640
4
        auto k1 = k;
2641
4
        k1.remove_prefix(1);
2642
4
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2643
4
        decode_key(&k1, &out);
2644
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2645
4
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2646
4
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2647
4
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2648
4
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2649
        // Change state to RECYCLING
2650
4
        std::unique_ptr<Transaction> txn;
2651
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2652
4
        if (err != TxnErrorCode::TXN_OK) {
2653
0
            LOG_WARNING("failed to create txn").tag("err", err);
2654
0
            return -1;
2655
0
        }
2656
4
        std::string val;
2657
4
        err = txn->get(k, &val);
2658
4
        if (err ==
2659
4
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2660
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2661
0
            return 0;
2662
0
        }
2663
4
        if (err != TxnErrorCode::TXN_OK) {
2664
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2665
0
            return -1;
2666
0
        }
2667
4
        index_pb.Clear();
2668
4
        if (!index_pb.ParseFromString(val)) {
2669
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2670
0
            return -1;
2671
0
        }
2672
4
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2673
3
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2674
3
            txn->put(k, index_pb.SerializeAsString());
2675
3
            err = txn->commit();
2676
3
            if (err != TxnErrorCode::TXN_OK) {
2677
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2678
0
                return -1;
2679
0
            }
2680
3
        }
2681
4
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
2682
2
            if (recycle_stream(index_id, index_pb, k) != 0) {
2683
0
                LOG_WARNING("failed to recycle table stream")
2684
0
                        .tag("instance_id", instance_id_)
2685
0
                        .tag("stream_id", index_id);
2686
0
                return -1;
2687
0
            }
2688
2
            metrics_context.total_recycled_num = ++num_recycled;
2689
2
            metrics_context.report();
2690
2
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2691
2
            return 0;
2692
2
        }
2693
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2694
1
            LOG_WARNING("failed to recycle tablets under index")
2695
1
                    .tag("table_id", index_pb.table_id())
2696
1
                    .tag("instance_id", instance_id_)
2697
1
                    .tag("index_id", index_id);
2698
1
            return -1;
2699
1
        }
2700
2701
1
        if (index_pb.has_db_id()) {
2702
            // Recycle the versioned keys
2703
1
            std::unique_ptr<Transaction> txn;
2704
1
            err = txn_kv_->create_txn(&txn);
2705
1
            if (err != TxnErrorCode::TXN_OK) {
2706
0
                LOG_WARNING("failed to create txn").tag("err", err);
2707
0
                return -1;
2708
0
            }
2709
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2710
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2711
1
            std::string index_inverted_key = versioned::index_inverted_key(
2712
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2713
1
            versioned_remove_all(txn.get(), meta_key);
2714
1
            txn->remove(index_key);
2715
1
            txn->remove(index_inverted_key);
2716
1
            err = txn->commit();
2717
1
            if (err != TxnErrorCode::TXN_OK) {
2718
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2719
0
                return -1;
2720
0
            }
2721
1
        }
2722
2723
1
        metrics_context.total_recycled_num = ++num_recycled;
2724
1
        metrics_context.report();
2725
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2726
1
        index_keys.push_back(k);
2727
1
        return 0;
2728
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2626
9
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2627
9
        ++num_scanned;
2628
9
        RecycleIndexPB index_pb;
2629
9
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2630
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2631
0
            return -1;
2632
0
        }
2633
9
        int64_t current_time = ::time(nullptr);
2634
9
        if (current_time <
2635
9
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2636
0
            return 0;
2637
0
        }
2638
9
        ++num_expired;
2639
        // decode index_id
2640
9
        auto k1 = k;
2641
9
        k1.remove_prefix(1);
2642
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2643
9
        decode_key(&k1, &out);
2644
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2645
9
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2646
9
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2647
9
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2648
9
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2649
        // Change state to RECYCLING
2650
9
        std::unique_ptr<Transaction> txn;
2651
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2652
9
        if (err != TxnErrorCode::TXN_OK) {
2653
0
            LOG_WARNING("failed to create txn").tag("err", err);
2654
0
            return -1;
2655
0
        }
2656
9
        std::string val;
2657
9
        err = txn->get(k, &val);
2658
9
        if (err ==
2659
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2660
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2661
0
            return 0;
2662
0
        }
2663
9
        if (err != TxnErrorCode::TXN_OK) {
2664
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2665
0
            return -1;
2666
0
        }
2667
9
        index_pb.Clear();
2668
9
        if (!index_pb.ParseFromString(val)) {
2669
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2670
0
            return -1;
2671
0
        }
2672
9
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2673
9
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2674
9
            txn->put(k, index_pb.SerializeAsString());
2675
9
            err = txn->commit();
2676
9
            if (err != TxnErrorCode::TXN_OK) {
2677
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2678
0
                return -1;
2679
0
            }
2680
9
        }
2681
9
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
2682
1
            if (recycle_stream(index_id, index_pb, k) != 0) {
2683
0
                LOG_WARNING("failed to recycle table stream")
2684
0
                        .tag("instance_id", instance_id_)
2685
0
                        .tag("stream_id", index_id);
2686
0
                return -1;
2687
0
            }
2688
1
            metrics_context.total_recycled_num = ++num_recycled;
2689
1
            metrics_context.report();
2690
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2691
1
            return 0;
2692
1
        }
2693
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2694
0
            LOG_WARNING("failed to recycle tablets under index")
2695
0
                    .tag("table_id", index_pb.table_id())
2696
0
                    .tag("instance_id", instance_id_)
2697
0
                    .tag("index_id", index_id);
2698
0
            return -1;
2699
0
        }
2700
2701
8
        if (index_pb.has_db_id()) {
2702
            // Recycle the versioned keys
2703
2
            std::unique_ptr<Transaction> txn;
2704
2
            err = txn_kv_->create_txn(&txn);
2705
2
            if (err != TxnErrorCode::TXN_OK) {
2706
0
                LOG_WARNING("failed to create txn").tag("err", err);
2707
0
                return -1;
2708
0
            }
2709
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2710
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2711
2
            std::string index_inverted_key = versioned::index_inverted_key(
2712
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2713
2
            versioned_remove_all(txn.get(), meta_key);
2714
2
            txn->remove(index_key);
2715
2
            txn->remove(index_inverted_key);
2716
2
            err = txn->commit();
2717
2
            if (err != TxnErrorCode::TXN_OK) {
2718
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2719
0
                return -1;
2720
0
            }
2721
2
        }
2722
2723
8
        metrics_context.total_recycled_num = ++num_recycled;
2724
8
        metrics_context.report();
2725
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2726
8
        index_keys.push_back(k);
2727
8
        return 0;
2728
8
    };
2729
2730
19
    auto loop_done = [&index_keys, this]() -> int {
2731
8
        if (index_keys.empty()) return 0;
2732
5
        DORIS_CLOUD_DEFER {
2733
5
            index_keys.clear();
2734
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2732
1
        DORIS_CLOUD_DEFER {
2733
1
            index_keys.clear();
2734
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2732
4
        DORIS_CLOUD_DEFER {
2733
4
            index_keys.clear();
2734
4
        };
2735
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2736
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2737
0
            return -1;
2738
0
        }
2739
5
        return 0;
2740
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2730
3
    auto loop_done = [&index_keys, this]() -> int {
2731
3
        if (index_keys.empty()) return 0;
2732
1
        DORIS_CLOUD_DEFER {
2733
1
            index_keys.clear();
2734
1
        };
2735
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2736
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2737
0
            return -1;
2738
0
        }
2739
1
        return 0;
2740
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2730
5
    auto loop_done = [&index_keys, this]() -> int {
2731
5
        if (index_keys.empty()) return 0;
2732
4
        DORIS_CLOUD_DEFER {
2733
4
            index_keys.clear();
2734
4
        };
2735
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2736
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2737
0
            return -1;
2738
0
        }
2739
4
        return 0;
2740
4
    };
2741
2742
19
    if (config::enable_recycler_stats_metrics) {
2743
0
        scan_and_statistics_indexes();
2744
0
    }
2745
    // recycle_func and loop_done for scan and recycle
2746
19
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
2747
19
}
2748
2749
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
2750
8.25k
                             int64_t tablet_id) {
2751
8.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
2752
2753
8.25k
    std::unique_ptr<Transaction> txn;
2754
8.25k
    TxnErrorCode err = txn_kv->create_txn(&txn);
2755
8.25k
    if (err != TxnErrorCode::TXN_OK) {
2756
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
2757
0
                     << " tablet_id=" << tablet_id << " err=" << err;
2758
0
        return false;
2759
0
    }
2760
2761
8.25k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
2762
8.25k
    std::string tablet_idx_val;
2763
8.25k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
2764
8.25k
    if (TxnErrorCode::TXN_OK != err) {
2765
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
2766
0
                     << " tablet_id=" << tablet_id << " err=" << err
2767
0
                     << " key=" << hex(tablet_idx_key);
2768
0
        return false;
2769
0
    }
2770
2771
8.25k
    TabletIndexPB tablet_idx_pb;
2772
8.25k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
2773
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
2774
0
                     << " tablet_id=" << tablet_id;
2775
0
        return false;
2776
0
    }
2777
2778
8.25k
    if (!tablet_idx_pb.has_db_id()) {
2779
        // In the previous version, the db_id was not set in the index_pb.
2780
        // If updating to the version which enable txn lazy commit, the db_id will be set.
2781
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
2782
0
                  << " instance_id=" << instance_id
2783
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
2784
0
        return true;
2785
0
    }
2786
2787
8.25k
    std::string ver_val;
2788
8.25k
    std::string ver_key =
2789
8.25k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
2790
8.25k
                                   tablet_idx_pb.partition_id()});
2791
8.25k
    err = txn->get(ver_key, &ver_val);
2792
2793
8.25k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
2794
214
        LOG(INFO) << ""
2795
214
                     "partition version not found, instance_id="
2796
214
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
2797
214
                  << " table_id=" << tablet_idx_pb.table_id()
2798
214
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
2799
214
                  << " key=" << hex(ver_key);
2800
214
        return true;
2801
214
    }
2802
2803
8.03k
    if (TxnErrorCode::TXN_OK != err) {
2804
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
2805
0
                     << " db_id=" << tablet_idx_pb.db_id()
2806
0
                     << " table_id=" << tablet_idx_pb.table_id()
2807
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2808
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
2809
0
        return false;
2810
0
    }
2811
2812
8.03k
    VersionPB version_pb;
2813
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
2814
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
2815
0
                     << " db_id=" << tablet_idx_pb.db_id()
2816
0
                     << " table_id=" << tablet_idx_pb.table_id()
2817
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2818
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
2819
0
        return false;
2820
0
    }
2821
2822
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
2823
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
2824
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
2825
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
2826
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
2827
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
2828
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
2829
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
2830
4.00k
                     << " key=" << hex(ver_key);
2831
4.00k
        return false;
2832
4.00k
    }
2833
4.03k
    return true;
2834
8.03k
}
2835
2836
17
int InstanceRecycler::recycle_partitions() {
2837
17
    const std::string task_name = "recycle_partitions";
2838
17
    int64_t num_scanned = 0;
2839
17
    int64_t num_expired = 0;
2840
17
    int64_t num_recycled = 0;
2841
17
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2842
2843
17
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
2844
17
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
2845
17
    std::string part_key0;
2846
17
    std::string part_key1;
2847
17
    recycle_partition_key(part_key_info0, &part_key0);
2848
17
    recycle_partition_key(part_key_info1, &part_key1);
2849
2850
17
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
2851
2852
17
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2853
17
    register_recycle_task(task_name, start_time);
2854
2855
17
    DORIS_CLOUD_DEFER {
2856
17
        unregister_recycle_task(task_name);
2857
17
        int64_t cost =
2858
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2859
17
        metrics_context.finish_report();
2860
17
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2861
17
                .tag("instance_id", instance_id_)
2862
17
                .tag("num_scanned", num_scanned)
2863
17
                .tag("num_expired", num_expired)
2864
17
                .tag("num_recycled", num_recycled);
2865
17
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2855
2
    DORIS_CLOUD_DEFER {
2856
2
        unregister_recycle_task(task_name);
2857
2
        int64_t cost =
2858
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2859
2
        metrics_context.finish_report();
2860
2
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2861
2
                .tag("instance_id", instance_id_)
2862
2
                .tag("num_scanned", num_scanned)
2863
2
                .tag("num_expired", num_expired)
2864
2
                .tag("num_recycled", num_recycled);
2865
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2855
15
    DORIS_CLOUD_DEFER {
2856
15
        unregister_recycle_task(task_name);
2857
15
        int64_t cost =
2858
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2859
15
        metrics_context.finish_report();
2860
15
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2861
15
                .tag("instance_id", instance_id_)
2862
15
                .tag("num_scanned", num_scanned)
2863
15
                .tag("num_expired", num_expired)
2864
15
                .tag("num_recycled", num_recycled);
2865
15
    };
2866
2867
17
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2868
2869
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
2870
17
    std::vector<std::string_view> partition_keys;
2871
17
    std::vector<std::string> partition_version_keys;
2872
17
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2873
11
        ++num_scanned;
2874
11
        RecyclePartitionPB part_pb;
2875
11
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2876
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2877
0
            return -1;
2878
0
        }
2879
11
        int64_t current_time = ::time(nullptr);
2880
11
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2881
11
                                                            &earlest_ts)) { // not expired
2882
0
            return 0;
2883
0
        }
2884
11
        ++num_expired;
2885
        // decode partition_id
2886
11
        auto k1 = k;
2887
11
        k1.remove_prefix(1);
2888
11
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2889
11
        decode_key(&k1, &out);
2890
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2891
11
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2892
11
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2893
11
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2894
11
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2895
        // Change state to RECYCLING
2896
11
        std::unique_ptr<Transaction> txn;
2897
11
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2898
11
        if (err != TxnErrorCode::TXN_OK) {
2899
0
            LOG_WARNING("failed to create txn").tag("err", err);
2900
0
            return -1;
2901
0
        }
2902
11
        std::string val;
2903
11
        err = txn->get(k, &val);
2904
11
        if (err ==
2905
11
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2906
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2907
0
            return 0;
2908
0
        }
2909
11
        if (err != TxnErrorCode::TXN_OK) {
2910
0
            LOG_WARNING("failed to get kv");
2911
0
            return -1;
2912
0
        }
2913
11
        part_pb.Clear();
2914
11
        if (!part_pb.ParseFromString(val)) {
2915
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2916
0
            return -1;
2917
0
        }
2918
        // Partitions with PREPARED state MUST have no data
2919
11
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2920
10
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2921
10
            txn->put(k, part_pb.SerializeAsString());
2922
10
            err = txn->commit();
2923
10
            if (err != TxnErrorCode::TXN_OK) {
2924
0
                LOG_WARNING("failed to commit txn: {}", err);
2925
0
                return -1;
2926
0
            }
2927
10
        }
2928
2929
11
        int ret = 0;
2930
35
        for (int64_t index_id : part_pb.index_id()) {
2931
35
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2932
1
                LOG_WARNING("failed to recycle tablets under partition")
2933
1
                        .tag("table_id", part_pb.table_id())
2934
1
                        .tag("instance_id", instance_id_)
2935
1
                        .tag("index_id", index_id)
2936
1
                        .tag("partition_id", partition_id);
2937
1
                ret = -1;
2938
1
            }
2939
35
        }
2940
11
        if (ret == 0 && part_pb.has_db_id() &&
2941
11
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
2942
10
                                                   partition_id, part_pb.table_streams()) != 0) {
2943
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
2944
0
                    .tag("instance_id", instance_id_)
2945
0
                    .tag("table_id", part_pb.table_id())
2946
0
                    .tag("partition_id", partition_id);
2947
0
            ret = -1;
2948
0
        }
2949
11
        if (ret == 0 && part_pb.has_db_id()) {
2950
            // Recycle the versioned keys
2951
10
            std::unique_ptr<Transaction> txn;
2952
10
            err = txn_kv_->create_txn(&txn);
2953
10
            if (err != TxnErrorCode::TXN_OK) {
2954
0
                LOG_WARNING("failed to create txn").tag("err", err);
2955
0
                return -1;
2956
0
            }
2957
10
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2958
10
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2959
10
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2960
10
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2961
10
            std::string partition_version_key =
2962
10
                    versioned::partition_version_key({instance_id_, partition_id});
2963
10
            versioned_remove_all(txn.get(), meta_key);
2964
10
            txn->remove(index_key);
2965
10
            txn->remove(inverted_index_key);
2966
10
            versioned_remove_all(txn.get(), partition_version_key);
2967
10
            err = txn->commit();
2968
10
            if (err != TxnErrorCode::TXN_OK) {
2969
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2970
0
                return -1;
2971
0
            }
2972
10
        }
2973
2974
11
        if (ret == 0) {
2975
10
            ++num_recycled;
2976
10
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2977
10
            partition_keys.push_back(k);
2978
10
            if (part_pb.db_id() > 0) {
2979
10
                partition_version_keys.push_back(partition_version_key(
2980
10
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2981
10
            }
2982
10
            metrics_context.total_recycled_num = num_recycled;
2983
10
            metrics_context.report();
2984
10
        }
2985
11
        return ret;
2986
11
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2872
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2873
2
        ++num_scanned;
2874
2
        RecyclePartitionPB part_pb;
2875
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2876
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2877
0
            return -1;
2878
0
        }
2879
2
        int64_t current_time = ::time(nullptr);
2880
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2881
2
                                                            &earlest_ts)) { // not expired
2882
0
            return 0;
2883
0
        }
2884
2
        ++num_expired;
2885
        // decode partition_id
2886
2
        auto k1 = k;
2887
2
        k1.remove_prefix(1);
2888
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2889
2
        decode_key(&k1, &out);
2890
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2891
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2892
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2893
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2894
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2895
        // Change state to RECYCLING
2896
2
        std::unique_ptr<Transaction> txn;
2897
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2898
2
        if (err != TxnErrorCode::TXN_OK) {
2899
0
            LOG_WARNING("failed to create txn").tag("err", err);
2900
0
            return -1;
2901
0
        }
2902
2
        std::string val;
2903
2
        err = txn->get(k, &val);
2904
2
        if (err ==
2905
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2906
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2907
0
            return 0;
2908
0
        }
2909
2
        if (err != TxnErrorCode::TXN_OK) {
2910
0
            LOG_WARNING("failed to get kv");
2911
0
            return -1;
2912
0
        }
2913
2
        part_pb.Clear();
2914
2
        if (!part_pb.ParseFromString(val)) {
2915
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2916
0
            return -1;
2917
0
        }
2918
        // Partitions with PREPARED state MUST have no data
2919
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2920
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2921
1
            txn->put(k, part_pb.SerializeAsString());
2922
1
            err = txn->commit();
2923
1
            if (err != TxnErrorCode::TXN_OK) {
2924
0
                LOG_WARNING("failed to commit txn: {}", err);
2925
0
                return -1;
2926
0
            }
2927
1
        }
2928
2929
2
        int ret = 0;
2930
2
        for (int64_t index_id : part_pb.index_id()) {
2931
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2932
1
                LOG_WARNING("failed to recycle tablets under partition")
2933
1
                        .tag("table_id", part_pb.table_id())
2934
1
                        .tag("instance_id", instance_id_)
2935
1
                        .tag("index_id", index_id)
2936
1
                        .tag("partition_id", partition_id);
2937
1
                ret = -1;
2938
1
            }
2939
2
        }
2940
2
        if (ret == 0 && part_pb.has_db_id() &&
2941
2
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
2942
1
                                                   partition_id, part_pb.table_streams()) != 0) {
2943
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
2944
0
                    .tag("instance_id", instance_id_)
2945
0
                    .tag("table_id", part_pb.table_id())
2946
0
                    .tag("partition_id", partition_id);
2947
0
            ret = -1;
2948
0
        }
2949
2
        if (ret == 0 && part_pb.has_db_id()) {
2950
            // Recycle the versioned keys
2951
1
            std::unique_ptr<Transaction> txn;
2952
1
            err = txn_kv_->create_txn(&txn);
2953
1
            if (err != TxnErrorCode::TXN_OK) {
2954
0
                LOG_WARNING("failed to create txn").tag("err", err);
2955
0
                return -1;
2956
0
            }
2957
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2958
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2959
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2960
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2961
1
            std::string partition_version_key =
2962
1
                    versioned::partition_version_key({instance_id_, partition_id});
2963
1
            versioned_remove_all(txn.get(), meta_key);
2964
1
            txn->remove(index_key);
2965
1
            txn->remove(inverted_index_key);
2966
1
            versioned_remove_all(txn.get(), partition_version_key);
2967
1
            err = txn->commit();
2968
1
            if (err != TxnErrorCode::TXN_OK) {
2969
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2970
0
                return -1;
2971
0
            }
2972
1
        }
2973
2974
2
        if (ret == 0) {
2975
1
            ++num_recycled;
2976
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2977
1
            partition_keys.push_back(k);
2978
1
            if (part_pb.db_id() > 0) {
2979
1
                partition_version_keys.push_back(partition_version_key(
2980
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2981
1
            }
2982
1
            metrics_context.total_recycled_num = num_recycled;
2983
1
            metrics_context.report();
2984
1
        }
2985
2
        return ret;
2986
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2872
9
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2873
9
        ++num_scanned;
2874
9
        RecyclePartitionPB part_pb;
2875
9
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2876
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2877
0
            return -1;
2878
0
        }
2879
9
        int64_t current_time = ::time(nullptr);
2880
9
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2881
9
                                                            &earlest_ts)) { // not expired
2882
0
            return 0;
2883
0
        }
2884
9
        ++num_expired;
2885
        // decode partition_id
2886
9
        auto k1 = k;
2887
9
        k1.remove_prefix(1);
2888
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2889
9
        decode_key(&k1, &out);
2890
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2891
9
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2892
9
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2893
9
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2894
9
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2895
        // Change state to RECYCLING
2896
9
        std::unique_ptr<Transaction> txn;
2897
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2898
9
        if (err != TxnErrorCode::TXN_OK) {
2899
0
            LOG_WARNING("failed to create txn").tag("err", err);
2900
0
            return -1;
2901
0
        }
2902
9
        std::string val;
2903
9
        err = txn->get(k, &val);
2904
9
        if (err ==
2905
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2906
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2907
0
            return 0;
2908
0
        }
2909
9
        if (err != TxnErrorCode::TXN_OK) {
2910
0
            LOG_WARNING("failed to get kv");
2911
0
            return -1;
2912
0
        }
2913
9
        part_pb.Clear();
2914
9
        if (!part_pb.ParseFromString(val)) {
2915
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2916
0
            return -1;
2917
0
        }
2918
        // Partitions with PREPARED state MUST have no data
2919
9
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2920
9
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2921
9
            txn->put(k, part_pb.SerializeAsString());
2922
9
            err = txn->commit();
2923
9
            if (err != TxnErrorCode::TXN_OK) {
2924
0
                LOG_WARNING("failed to commit txn: {}", err);
2925
0
                return -1;
2926
0
            }
2927
9
        }
2928
2929
9
        int ret = 0;
2930
33
        for (int64_t index_id : part_pb.index_id()) {
2931
33
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2932
0
                LOG_WARNING("failed to recycle tablets under partition")
2933
0
                        .tag("table_id", part_pb.table_id())
2934
0
                        .tag("instance_id", instance_id_)
2935
0
                        .tag("index_id", index_id)
2936
0
                        .tag("partition_id", partition_id);
2937
0
                ret = -1;
2938
0
            }
2939
33
        }
2940
9
        if (ret == 0 && part_pb.has_db_id() &&
2941
9
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
2942
9
                                                   partition_id, part_pb.table_streams()) != 0) {
2943
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
2944
0
                    .tag("instance_id", instance_id_)
2945
0
                    .tag("table_id", part_pb.table_id())
2946
0
                    .tag("partition_id", partition_id);
2947
0
            ret = -1;
2948
0
        }
2949
9
        if (ret == 0 && part_pb.has_db_id()) {
2950
            // Recycle the versioned keys
2951
9
            std::unique_ptr<Transaction> txn;
2952
9
            err = txn_kv_->create_txn(&txn);
2953
9
            if (err != TxnErrorCode::TXN_OK) {
2954
0
                LOG_WARNING("failed to create txn").tag("err", err);
2955
0
                return -1;
2956
0
            }
2957
9
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2958
9
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2959
9
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2960
9
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2961
9
            std::string partition_version_key =
2962
9
                    versioned::partition_version_key({instance_id_, partition_id});
2963
9
            versioned_remove_all(txn.get(), meta_key);
2964
9
            txn->remove(index_key);
2965
9
            txn->remove(inverted_index_key);
2966
9
            versioned_remove_all(txn.get(), partition_version_key);
2967
9
            err = txn->commit();
2968
9
            if (err != TxnErrorCode::TXN_OK) {
2969
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2970
0
                return -1;
2971
0
            }
2972
9
        }
2973
2974
9
        if (ret == 0) {
2975
9
            ++num_recycled;
2976
9
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2977
9
            partition_keys.push_back(k);
2978
9
            if (part_pb.db_id() > 0) {
2979
9
                partition_version_keys.push_back(partition_version_key(
2980
9
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2981
9
            }
2982
9
            metrics_context.total_recycled_num = num_recycled;
2983
9
            metrics_context.report();
2984
9
        }
2985
9
        return ret;
2986
9
    };
2987
2988
17
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2989
7
        if (partition_keys.empty()) return 0;
2990
6
        DORIS_CLOUD_DEFER {
2991
6
            partition_keys.clear();
2992
6
            partition_version_keys.clear();
2993
6
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2990
1
        DORIS_CLOUD_DEFER {
2991
1
            partition_keys.clear();
2992
1
            partition_version_keys.clear();
2993
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2990
5
        DORIS_CLOUD_DEFER {
2991
5
            partition_keys.clear();
2992
5
            partition_version_keys.clear();
2993
5
        };
2994
6
        std::unique_ptr<Transaction> txn;
2995
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2996
6
        if (err != TxnErrorCode::TXN_OK) {
2997
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2998
0
            return -1;
2999
0
        }
3000
10
        for (auto& k : partition_keys) {
3001
10
            txn->remove(k);
3002
10
        }
3003
10
        for (auto& k : partition_version_keys) {
3004
10
            txn->remove(k);
3005
10
        }
3006
6
        err = txn->commit();
3007
6
        if (err != TxnErrorCode::TXN_OK) {
3008
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3009
0
                         << " err=" << err;
3010
0
            return -1;
3011
0
        }
3012
6
        return 0;
3013
6
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2988
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2989
2
        if (partition_keys.empty()) return 0;
2990
1
        DORIS_CLOUD_DEFER {
2991
1
            partition_keys.clear();
2992
1
            partition_version_keys.clear();
2993
1
        };
2994
1
        std::unique_ptr<Transaction> txn;
2995
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2996
1
        if (err != TxnErrorCode::TXN_OK) {
2997
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2998
0
            return -1;
2999
0
        }
3000
1
        for (auto& k : partition_keys) {
3001
1
            txn->remove(k);
3002
1
        }
3003
1
        for (auto& k : partition_version_keys) {
3004
1
            txn->remove(k);
3005
1
        }
3006
1
        err = txn->commit();
3007
1
        if (err != TxnErrorCode::TXN_OK) {
3008
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3009
0
                         << " err=" << err;
3010
0
            return -1;
3011
0
        }
3012
1
        return 0;
3013
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2988
5
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2989
5
        if (partition_keys.empty()) return 0;
2990
5
        DORIS_CLOUD_DEFER {
2991
5
            partition_keys.clear();
2992
5
            partition_version_keys.clear();
2993
5
        };
2994
5
        std::unique_ptr<Transaction> txn;
2995
5
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2996
5
        if (err != TxnErrorCode::TXN_OK) {
2997
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2998
0
            return -1;
2999
0
        }
3000
9
        for (auto& k : partition_keys) {
3001
9
            txn->remove(k);
3002
9
        }
3003
9
        for (auto& k : partition_version_keys) {
3004
9
            txn->remove(k);
3005
9
        }
3006
5
        err = txn->commit();
3007
5
        if (err != TxnErrorCode::TXN_OK) {
3008
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3009
0
                         << " err=" << err;
3010
0
            return -1;
3011
0
        }
3012
5
        return 0;
3013
5
    };
3014
3015
17
    if (config::enable_recycler_stats_metrics) {
3016
0
        scan_and_statistics_partitions();
3017
0
    }
3018
    // recycle_func and loop_done for scan and recycle
3019
17
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
3020
17
}
3021
3022
14
int InstanceRecycler::recycle_versions() {
3023
14
    if (should_recycle_versioned_keys()) {
3024
2
        return recycle_orphan_partitions();
3025
2
    }
3026
3027
12
    int64_t num_scanned = 0;
3028
12
    int64_t num_recycled = 0;
3029
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
3030
3031
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
3032
3033
12
    auto start_time = steady_clock::now();
3034
3035
12
    DORIS_CLOUD_DEFER {
3036
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3037
12
        metrics_context.finish_report();
3038
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3039
12
                .tag("instance_id", instance_id_)
3040
12
                .tag("num_scanned", num_scanned)
3041
12
                .tag("num_recycled", num_recycled);
3042
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
3035
12
    DORIS_CLOUD_DEFER {
3036
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3037
12
        metrics_context.finish_report();
3038
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3039
12
                .tag("instance_id", instance_id_)
3040
12
                .tag("num_scanned", num_scanned)
3041
12
                .tag("num_recycled", num_recycled);
3042
12
    };
3043
3044
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
3045
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
3046
12
    int64_t last_scanned_table_id = 0;
3047
12
    bool is_recycled = false; // Is last scanned kv recycled
3048
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
3049
12
                         &metrics_context, this](std::string_view k, std::string_view) {
3050
2
        ++num_scanned;
3051
2
        auto k1 = k;
3052
2
        k1.remove_prefix(1);
3053
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3054
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3055
2
        decode_key(&k1, &out);
3056
2
        DCHECK_EQ(out.size(), 6) << k;
3057
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3058
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3059
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3060
0
            return 0;
3061
0
        }
3062
2
        last_scanned_table_id = table_id;
3063
2
        is_recycled = false;
3064
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3065
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3066
2
        std::unique_ptr<Transaction> txn;
3067
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3068
2
        if (err != TxnErrorCode::TXN_OK) {
3069
0
            return -1;
3070
0
        }
3071
2
        std::unique_ptr<RangeGetIterator> iter;
3072
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3073
2
        if (err != TxnErrorCode::TXN_OK) {
3074
0
            return -1;
3075
0
        }
3076
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3077
1
            return 0;
3078
1
        }
3079
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3080
        // 1. Remove all partition version kvs of this table
3081
1
        auto partition_version_key_begin =
3082
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3083
1
        auto partition_version_key_end =
3084
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3085
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3086
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3087
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3088
1
                     << " table_id=" << table_id;
3089
        // 2. Remove the table version kv of this table
3090
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3091
1
        txn->remove(tbl_version_key);
3092
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3093
        // 3. Remove mow delete bitmap update lock and tablet job lock
3094
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3095
1
        txn->remove(lock_key);
3096
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3097
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3098
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3099
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3100
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3101
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3102
1
                     << " table_id=" << table_id;
3103
1
        err = txn->commit();
3104
1
        if (err != TxnErrorCode::TXN_OK) {
3105
0
            return -1;
3106
0
        }
3107
1
        metrics_context.total_recycled_num = ++num_recycled;
3108
1
        metrics_context.report();
3109
1
        is_recycled = true;
3110
1
        return 0;
3111
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3049
2
                         &metrics_context, this](std::string_view k, std::string_view) {
3050
2
        ++num_scanned;
3051
2
        auto k1 = k;
3052
2
        k1.remove_prefix(1);
3053
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3054
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3055
2
        decode_key(&k1, &out);
3056
2
        DCHECK_EQ(out.size(), 6) << k;
3057
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3058
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3059
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3060
0
            return 0;
3061
0
        }
3062
2
        last_scanned_table_id = table_id;
3063
2
        is_recycled = false;
3064
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3065
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3066
2
        std::unique_ptr<Transaction> txn;
3067
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3068
2
        if (err != TxnErrorCode::TXN_OK) {
3069
0
            return -1;
3070
0
        }
3071
2
        std::unique_ptr<RangeGetIterator> iter;
3072
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3073
2
        if (err != TxnErrorCode::TXN_OK) {
3074
0
            return -1;
3075
0
        }
3076
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3077
1
            return 0;
3078
1
        }
3079
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3080
        // 1. Remove all partition version kvs of this table
3081
1
        auto partition_version_key_begin =
3082
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3083
1
        auto partition_version_key_end =
3084
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3085
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3086
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3087
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3088
1
                     << " table_id=" << table_id;
3089
        // 2. Remove the table version kv of this table
3090
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3091
1
        txn->remove(tbl_version_key);
3092
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3093
        // 3. Remove mow delete bitmap update lock and tablet job lock
3094
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3095
1
        txn->remove(lock_key);
3096
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3097
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3098
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3099
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3100
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3101
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3102
1
                     << " table_id=" << table_id;
3103
1
        err = txn->commit();
3104
1
        if (err != TxnErrorCode::TXN_OK) {
3105
0
            return -1;
3106
0
        }
3107
1
        metrics_context.total_recycled_num = ++num_recycled;
3108
1
        metrics_context.report();
3109
1
        is_recycled = true;
3110
1
        return 0;
3111
1
    };
3112
3113
12
    if (config::enable_recycler_stats_metrics) {
3114
0
        scan_and_statistics_versions();
3115
0
    }
3116
    // recycle_func and loop_done for scan and recycle
3117
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
3118
14
}
3119
3120
3
int InstanceRecycler::recycle_orphan_partitions() {
3121
3
    int64_t num_scanned = 0;
3122
3
    int64_t num_recycled = 0;
3123
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
3124
3125
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
3126
3
            .tag("instance_id", instance_id_);
3127
3128
3
    auto start_time = steady_clock::now();
3129
3130
3
    DORIS_CLOUD_DEFER {
3131
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3132
3
        metrics_context.finish_report();
3133
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3134
3
                .tag("instance_id", instance_id_)
3135
3
                .tag("num_scanned", num_scanned)
3136
3
                .tag("num_recycled", num_recycled);
3137
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
3130
3
    DORIS_CLOUD_DEFER {
3131
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3132
3
        metrics_context.finish_report();
3133
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3134
3
                .tag("instance_id", instance_id_)
3135
3
                .tag("num_scanned", num_scanned)
3136
3
                .tag("num_recycled", num_recycled);
3137
3
    };
3138
3139
3
    bool is_empty_table = false;        // whether the table has no indexes
3140
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
3141
3
    int64_t current_table_id = 0;       // current scanning table id
3142
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
3143
3
                         &current_table_id, &is_table_kvs_recycled,
3144
3
                         this](std::string_view k, std::string_view) {
3145
2
        ++num_scanned;
3146
3147
2
        std::string_view k1(k);
3148
2
        int64_t db_id, table_id, partition_id;
3149
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3150
2
                                                            &partition_id)) {
3151
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3152
0
            return -1;
3153
2
        } else if (table_id != current_table_id) {
3154
2
            current_table_id = table_id;
3155
2
            is_table_kvs_recycled = false;
3156
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3157
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3158
2
            if (err != TxnErrorCode::TXN_OK) {
3159
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3160
0
                             << " table_id=" << table_id << " err=" << err;
3161
0
                return -1;
3162
0
            }
3163
2
        }
3164
3165
2
        if (!is_empty_table) {
3166
            // table is not empty, skip recycle
3167
1
            return 0;
3168
1
        }
3169
3170
1
        std::unique_ptr<Transaction> txn;
3171
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3172
1
        if (err != TxnErrorCode::TXN_OK) {
3173
0
            return -1;
3174
0
        }
3175
3176
        // 1. Remove all partition related kvs
3177
1
        std::string partition_meta_key =
3178
1
                versioned::meta_partition_key({instance_id_, partition_id});
3179
1
        std::string partition_index_key =
3180
1
                versioned::partition_index_key({instance_id_, partition_id});
3181
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3182
1
                {instance_id_, db_id, table_id, partition_id});
3183
1
        std::string partition_version_key =
3184
1
                versioned::partition_version_key({instance_id_, partition_id});
3185
1
        txn->remove(partition_index_key);
3186
1
        txn->remove(partition_inverted_key);
3187
1
        versioned_remove_all(txn.get(), partition_meta_key);
3188
1
        versioned_remove_all(txn.get(), partition_version_key);
3189
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3190
1
                     << " table_id=" << table_id << " db_id=" << db_id
3191
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3192
1
                     << " partition_version_key=" << hex(partition_version_key);
3193
3194
1
        if (!is_table_kvs_recycled) {
3195
1
            is_table_kvs_recycled = true;
3196
3197
            // 2. Remove the table version kv of this table
3198
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3199
1
            versioned_remove_all(txn.get(), table_version_key);
3200
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3201
            // 3. Remove mow delete bitmap update lock and tablet job lock
3202
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3203
1
            txn->remove(lock_key);
3204
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3205
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3206
1
            std::string tablet_job_key_end =
3207
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3208
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3209
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3210
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3211
1
                         << " table_id=" << table_id;
3212
1
        }
3213
3214
1
        err = txn->commit();
3215
1
        if (err != TxnErrorCode::TXN_OK) {
3216
0
            return -1;
3217
0
        }
3218
1
        metrics_context.total_recycled_num = ++num_recycled;
3219
1
        metrics_context.report();
3220
1
        return 0;
3221
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
3144
2
                         this](std::string_view k, std::string_view) {
3145
2
        ++num_scanned;
3146
3147
2
        std::string_view k1(k);
3148
2
        int64_t db_id, table_id, partition_id;
3149
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3150
2
                                                            &partition_id)) {
3151
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3152
0
            return -1;
3153
2
        } else if (table_id != current_table_id) {
3154
2
            current_table_id = table_id;
3155
2
            is_table_kvs_recycled = false;
3156
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3157
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3158
2
            if (err != TxnErrorCode::TXN_OK) {
3159
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3160
0
                             << " table_id=" << table_id << " err=" << err;
3161
0
                return -1;
3162
0
            }
3163
2
        }
3164
3165
2
        if (!is_empty_table) {
3166
            // table is not empty, skip recycle
3167
1
            return 0;
3168
1
        }
3169
3170
1
        std::unique_ptr<Transaction> txn;
3171
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3172
1
        if (err != TxnErrorCode::TXN_OK) {
3173
0
            return -1;
3174
0
        }
3175
3176
        // 1. Remove all partition related kvs
3177
1
        std::string partition_meta_key =
3178
1
                versioned::meta_partition_key({instance_id_, partition_id});
3179
1
        std::string partition_index_key =
3180
1
                versioned::partition_index_key({instance_id_, partition_id});
3181
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3182
1
                {instance_id_, db_id, table_id, partition_id});
3183
1
        std::string partition_version_key =
3184
1
                versioned::partition_version_key({instance_id_, partition_id});
3185
1
        txn->remove(partition_index_key);
3186
1
        txn->remove(partition_inverted_key);
3187
1
        versioned_remove_all(txn.get(), partition_meta_key);
3188
1
        versioned_remove_all(txn.get(), partition_version_key);
3189
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3190
1
                     << " table_id=" << table_id << " db_id=" << db_id
3191
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3192
1
                     << " partition_version_key=" << hex(partition_version_key);
3193
3194
1
        if (!is_table_kvs_recycled) {
3195
1
            is_table_kvs_recycled = true;
3196
3197
            // 2. Remove the table version kv of this table
3198
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3199
1
            versioned_remove_all(txn.get(), table_version_key);
3200
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3201
            // 3. Remove mow delete bitmap update lock and tablet job lock
3202
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3203
1
            txn->remove(lock_key);
3204
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3205
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3206
1
            std::string tablet_job_key_end =
3207
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3208
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3209
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3210
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3211
1
                         << " table_id=" << table_id;
3212
1
        }
3213
3214
1
        err = txn->commit();
3215
1
        if (err != TxnErrorCode::TXN_OK) {
3216
0
            return -1;
3217
0
        }
3218
1
        metrics_context.total_recycled_num = ++num_recycled;
3219
1
        metrics_context.report();
3220
1
        return 0;
3221
1
    };
3222
3223
    // recycle_func and loop_done for scan and recycle
3224
3
    return scan_and_recycle(
3225
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
3226
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
3227
3
            std::move(recycle_func));
3228
3
}
3229
3230
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
3231
                                      RecyclerMetricsContext& metrics_context,
3232
54
                                      int64_t partition_id) {
3233
54
    bool is_multi_version =
3234
54
            instance_info_.has_multi_version_status() &&
3235
54
            instance_info_.multi_version_status() != MultiVersionStatus::MULTI_VERSION_DISABLED;
3236
54
    int64_t num_scanned = 0;
3237
54
    std::atomic_long num_recycled = 0;
3238
3239
54
    std::string tablet_key_begin, tablet_key_end;
3240
54
    std::string stats_key_begin, stats_key_end;
3241
54
    std::string job_key_begin, job_key_end;
3242
3243
54
    std::string tablet_belongs;
3244
54
    if (partition_id > 0) {
3245
        // recycle tablets in a partition belonging to the index
3246
35
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
3247
35
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
3248
35
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
3249
35
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
3250
35
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
3251
35
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
3252
35
        tablet_belongs = "partition";
3253
35
    } else {
3254
        // recycle tablets in the index
3255
19
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
3256
19
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
3257
19
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
3258
19
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
3259
19
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
3260
19
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
3261
19
        tablet_belongs = "index";
3262
19
    }
3263
3264
54
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
3265
54
            .tag("table_id", table_id)
3266
54
            .tag("index_id", index_id)
3267
54
            .tag("partition_id", partition_id);
3268
3269
54
    auto start_time = steady_clock::now();
3270
3271
54
    DORIS_CLOUD_DEFER {
3272
54
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3273
54
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3274
54
                .tag("instance_id", instance_id_)
3275
54
                .tag("table_id", table_id)
3276
54
                .tag("index_id", index_id)
3277
54
                .tag("partition_id", partition_id)
3278
54
                .tag("num_scanned", num_scanned)
3279
54
                .tag("num_recycled", num_recycled);
3280
54
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3271
4
    DORIS_CLOUD_DEFER {
3272
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3273
4
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3274
4
                .tag("instance_id", instance_id_)
3275
4
                .tag("table_id", table_id)
3276
4
                .tag("index_id", index_id)
3277
4
                .tag("partition_id", partition_id)
3278
4
                .tag("num_scanned", num_scanned)
3279
4
                .tag("num_recycled", num_recycled);
3280
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3271
50
    DORIS_CLOUD_DEFER {
3272
50
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3273
50
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3274
50
                .tag("instance_id", instance_id_)
3275
50
                .tag("table_id", table_id)
3276
50
                .tag("index_id", index_id)
3277
50
                .tag("partition_id", partition_id)
3278
50
                .tag("num_scanned", num_scanned)
3279
50
                .tag("num_recycled", num_recycled);
3280
50
    };
3281
3282
    // The tablet key and id which have been recycled.
3283
54
    struct TabletInfo {
3284
54
        std::string_view tablet_meta_key;
3285
54
        int64_t tablet_id;
3286
54
    };
3287
54
    SyncExecutor<TabletInfo> sync_executor(
3288
54
            _thread_pool_group.recycle_tablet_pool,
3289
54
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
3290
54
                        index_id, partition_id),
3291
4.24k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3291
4.00k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3291
241
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
3292
3293
    // Elements in `tablets_info` has the same lifetime as `it` in `scan_and_recycle`
3294
54
    std::vector<std::string> init_rs_keys;
3295
54
    bool has_failure = false;
3296
8.25k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3297
8.25k
        ++num_scanned;
3298
8.25k
        doris::TabletMetaCloudPB tablet_meta_pb;
3299
8.25k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3300
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3301
0
            has_failure = true;
3302
0
            return -1;
3303
0
        }
3304
8.25k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3305
3306
8.25k
        if (config::enable_recycler_check_lazy_txn_finished &&
3307
8.25k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3308
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3309
4.00k
            has_failure = true;
3310
4.00k
            return -1;
3311
4.00k
        }
3312
3313
4.25k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3314
4.25k
        sync_executor.add(
3315
4.25k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3316
4.25k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3317
2
                        LOG_WARNING("failed to recycle tablet")
3318
2
                                .tag("instance_id", instance_id_)
3319
2
                                .tag("tablet_id", tid);
3320
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3321
2
                    }
3322
4.25k
                    ++num_recycled;
3323
4.25k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3324
4.25k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3325
4.25k
                });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3315
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3316
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3317
0
                        LOG_WARNING("failed to recycle tablet")
3318
0
                                .tag("instance_id", instance_id_)
3319
0
                                .tag("tablet_id", tid);
3320
0
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3321
0
                    }
3322
4.00k
                    ++num_recycled;
3323
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3324
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3325
4.00k
                });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3315
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3316
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3317
2
                        LOG_WARNING("failed to recycle tablet")
3318
2
                                .tag("instance_id", instance_id_)
3319
2
                                .tag("tablet_id", tid);
3320
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3321
2
                    }
3322
248
                    ++num_recycled;
3323
248
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3324
248
                    return {.tablet_meta_key = k, .tablet_id = tid};
3325
250
                });
3326
4.25k
        return 0;
3327
4.25k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3296
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3297
8.00k
        ++num_scanned;
3298
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
3299
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3300
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3301
0
            has_failure = true;
3302
0
            return -1;
3303
0
        }
3304
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3305
3306
8.00k
        if (config::enable_recycler_check_lazy_txn_finished &&
3307
8.00k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3308
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3309
4.00k
            has_failure = true;
3310
4.00k
            return -1;
3311
4.00k
        }
3312
3313
4.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3314
4.00k
        sync_executor.add(
3315
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3316
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3317
4.00k
                        LOG_WARNING("failed to recycle tablet")
3318
4.00k
                                .tag("instance_id", instance_id_)
3319
4.00k
                                .tag("tablet_id", tid);
3320
4.00k
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3321
4.00k
                    }
3322
4.00k
                    ++num_recycled;
3323
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3324
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3325
4.00k
                });
3326
4.00k
        return 0;
3327
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3296
251
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3297
251
        ++num_scanned;
3298
251
        doris::TabletMetaCloudPB tablet_meta_pb;
3299
251
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3300
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3301
0
            has_failure = true;
3302
0
            return -1;
3303
0
        }
3304
251
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3305
3306
251
        if (config::enable_recycler_check_lazy_txn_finished &&
3307
251
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3308
1
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3309
1
            has_failure = true;
3310
1
            return -1;
3311
1
        }
3312
3313
250
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3314
250
        sync_executor.add(
3315
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3316
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3317
250
                        LOG_WARNING("failed to recycle tablet")
3318
250
                                .tag("instance_id", instance_id_)
3319
250
                                .tag("tablet_id", tid);
3320
250
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3321
250
                    }
3322
250
                    ++num_recycled;
3323
250
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3324
250
                    return {.tablet_meta_key = k, .tablet_id = tid};
3325
250
                });
3326
250
        return 0;
3327
250
    };
3328
3329
54
    auto loop_done = [&, this]() -> int {
3330
52
        int ret = 0;
3331
52
        bool finished = true;
3332
52
        bool has_empty_key = false;
3333
52
        DORIS_CLOUD_DEFER {
3334
52
            init_rs_keys.clear();
3335
52
            has_failure = false;
3336
52
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3333
4
        DORIS_CLOUD_DEFER {
3334
4
            init_rs_keys.clear();
3335
4
            has_failure = false;
3336
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3333
48
        DORIS_CLOUD_DEFER {
3334
48
            init_rs_keys.clear();
3335
48
            has_failure = false;
3336
48
        };
3337
52
        auto tablets_info = sync_executor.when_all(&finished);
3338
52
        if (!finished) {
3339
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3340
1
            return -1;
3341
1
        }
3342
3343
51
        size_t size_before_erase = tablets_info.size();
3344
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
3344
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
3344
249
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3345
51
        if (tablets_info.empty()) {
3346
2
            return size_before_erase == 0 ? 0 : -1;
3347
49
        } else if (size_before_erase != tablets_info.size()) {
3348
1
            has_empty_key = true;
3349
1
        }
3350
3351
49
        ret = has_empty_key ? -1 : 0;
3352
        // sort the vector using key's order
3353
49.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3354
49.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3355
49.4k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3353
48.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3354
48.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3355
48.4k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3353
958
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3354
958
            return prev.tablet_meta_key < last.tablet_meta_key;
3355
958
        });
3356
49
        std::unique_ptr<Transaction> txn;
3357
49
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3358
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3359
0
            return -1;
3360
0
        }
3361
49
        std::string tablet_key_end;
3362
49
        if (!tablets_info.empty()) {
3363
49
            if (!has_empty_key && !has_failure) {
3364
47
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3365
47
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3366
47
            } else {
3367
8
                for (auto& tablet_info : tablets_info) {
3368
8
                    txn->remove(tablet_info.tablet_meta_key);
3369
8
                }
3370
2
            }
3371
49
        }
3372
49
        if (is_multi_version) {
3373
6
            for (auto& tablet_info : tablets_info) {
3374
                // Remove all versions of tablet compact stats for recycled tablet
3375
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3376
6
                LOG_INFO("remove versioned tablet compact stats key")
3377
6
                        .tag("compact_stats_key", hex(k));
3378
6
                versioned_remove_all(txn.get(), k);
3379
6
            }
3380
6
            for (auto& tablet_info : tablets_info) {
3381
                // Remove all versions of tablet load stats for recycled tablet
3382
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3383
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3384
6
                versioned_remove_all(txn.get(), k);
3385
6
            }
3386
6
            for (auto& tablet_info : tablets_info) {
3387
                // Remove all versions of meta tablet for recycled tablet
3388
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3389
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3390
6
                versioned_remove_all(txn.get(), k);
3391
6
            }
3392
5
        }
3393
4.25k
        for (auto& tablet_info : tablets_info) {
3394
4.25k
            std::string k;
3395
4.25k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3396
4.25k
            txn->remove(k);
3397
4.25k
        }
3398
4.25k
        for (auto& tablet_info : tablets_info) {
3399
4.25k
            std::string k;
3400
4.25k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3401
4.25k
            txn->remove(k);
3402
4.25k
        }
3403
49
        for (auto& k : init_rs_keys) {
3404
0
            txn->remove(k);
3405
0
        }
3406
49
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3407
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3408
0
                         << ", err=" << err;
3409
0
            return -1;
3410
0
        }
3411
49
        return ret;
3412
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
3329
4
    auto loop_done = [&, this]() -> int {
3330
4
        int ret = 0;
3331
4
        bool finished = true;
3332
4
        bool has_empty_key = false;
3333
4
        DORIS_CLOUD_DEFER {
3334
4
            init_rs_keys.clear();
3335
4
            has_failure = false;
3336
4
        };
3337
4
        auto tablets_info = sync_executor.when_all(&finished);
3338
4
        if (!finished) {
3339
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3340
0
            return -1;
3341
0
        }
3342
3343
4
        size_t size_before_erase = tablets_info.size();
3344
4
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3345
4
        if (tablets_info.empty()) {
3346
2
            return size_before_erase == 0 ? 0 : -1;
3347
2
        } else if (size_before_erase != tablets_info.size()) {
3348
0
            has_empty_key = true;
3349
0
        }
3350
3351
2
        ret = has_empty_key ? -1 : 0;
3352
        // sort the vector using key's order
3353
2
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3354
2
            return prev.tablet_meta_key < last.tablet_meta_key;
3355
2
        });
3356
2
        std::unique_ptr<Transaction> txn;
3357
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3358
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3359
0
            return -1;
3360
0
        }
3361
2
        std::string tablet_key_end;
3362
2
        if (!tablets_info.empty()) {
3363
2
            if (!has_empty_key && !has_failure) {
3364
2
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3365
2
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3366
2
            } else {
3367
0
                for (auto& tablet_info : tablets_info) {
3368
0
                    txn->remove(tablet_info.tablet_meta_key);
3369
0
                }
3370
0
            }
3371
2
        }
3372
2
        if (is_multi_version) {
3373
0
            for (auto& tablet_info : tablets_info) {
3374
                // Remove all versions of tablet compact stats for recycled tablet
3375
0
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3376
0
                LOG_INFO("remove versioned tablet compact stats key")
3377
0
                        .tag("compact_stats_key", hex(k));
3378
0
                versioned_remove_all(txn.get(), k);
3379
0
            }
3380
0
            for (auto& tablet_info : tablets_info) {
3381
                // Remove all versions of tablet load stats for recycled tablet
3382
0
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3383
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3384
0
                versioned_remove_all(txn.get(), k);
3385
0
            }
3386
0
            for (auto& tablet_info : tablets_info) {
3387
                // Remove all versions of meta tablet for recycled tablet
3388
0
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3389
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3390
0
                versioned_remove_all(txn.get(), k);
3391
0
            }
3392
0
        }
3393
4.00k
        for (auto& tablet_info : tablets_info) {
3394
4.00k
            std::string k;
3395
4.00k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3396
4.00k
            txn->remove(k);
3397
4.00k
        }
3398
4.00k
        for (auto& tablet_info : tablets_info) {
3399
4.00k
            std::string k;
3400
4.00k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3401
4.00k
            txn->remove(k);
3402
4.00k
        }
3403
2
        for (auto& k : init_rs_keys) {
3404
0
            txn->remove(k);
3405
0
        }
3406
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3407
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3408
0
                         << ", err=" << err;
3409
0
            return -1;
3410
0
        }
3411
2
        return ret;
3412
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
3329
48
    auto loop_done = [&, this]() -> int {
3330
48
        int ret = 0;
3331
48
        bool finished = true;
3332
48
        bool has_empty_key = false;
3333
48
        DORIS_CLOUD_DEFER {
3334
48
            init_rs_keys.clear();
3335
48
            has_failure = false;
3336
48
        };
3337
48
        auto tablets_info = sync_executor.when_all(&finished);
3338
48
        if (!finished) {
3339
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3340
1
            return -1;
3341
1
        }
3342
3343
47
        size_t size_before_erase = tablets_info.size();
3344
47
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3345
47
        if (tablets_info.empty()) {
3346
0
            return size_before_erase == 0 ? 0 : -1;
3347
47
        } else if (size_before_erase != tablets_info.size()) {
3348
1
            has_empty_key = true;
3349
1
        }
3350
3351
47
        ret = has_empty_key ? -1 : 0;
3352
        // sort the vector using key's order
3353
47
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3354
47
            return prev.tablet_meta_key < last.tablet_meta_key;
3355
47
        });
3356
47
        std::unique_ptr<Transaction> txn;
3357
47
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3358
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3359
0
            return -1;
3360
0
        }
3361
47
        std::string tablet_key_end;
3362
47
        if (!tablets_info.empty()) {
3363
47
            if (!has_empty_key && !has_failure) {
3364
45
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3365
45
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3366
45
            } else {
3367
8
                for (auto& tablet_info : tablets_info) {
3368
8
                    txn->remove(tablet_info.tablet_meta_key);
3369
8
                }
3370
2
            }
3371
47
        }
3372
47
        if (is_multi_version) {
3373
6
            for (auto& tablet_info : tablets_info) {
3374
                // Remove all versions of tablet compact stats for recycled tablet
3375
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3376
6
                LOG_INFO("remove versioned tablet compact stats key")
3377
6
                        .tag("compact_stats_key", hex(k));
3378
6
                versioned_remove_all(txn.get(), k);
3379
6
            }
3380
6
            for (auto& tablet_info : tablets_info) {
3381
                // Remove all versions of tablet load stats for recycled tablet
3382
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3383
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3384
6
                versioned_remove_all(txn.get(), k);
3385
6
            }
3386
6
            for (auto& tablet_info : tablets_info) {
3387
                // Remove all versions of meta tablet for recycled tablet
3388
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3389
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3390
6
                versioned_remove_all(txn.get(), k);
3391
6
            }
3392
5
        }
3393
248
        for (auto& tablet_info : tablets_info) {
3394
248
            std::string k;
3395
248
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3396
248
            txn->remove(k);
3397
248
        }
3398
248
        for (auto& tablet_info : tablets_info) {
3399
248
            std::string k;
3400
248
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3401
248
            txn->remove(k);
3402
248
        }
3403
47
        for (auto& k : init_rs_keys) {
3404
0
            txn->remove(k);
3405
0
        }
3406
47
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3407
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3408
0
                         << ", err=" << err;
3409
0
            return -1;
3410
0
        }
3411
47
        return ret;
3412
47
    };
3413
3414
54
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
3415
54
                               std::move(loop_done));
3416
54
    if (ret != 0) {
3417
5
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
3418
5
        return ret;
3419
5
    }
3420
3421
    // directly remove tablet stats and tablet jobs of these dropped index or partition
3422
49
    std::unique_ptr<Transaction> txn;
3423
49
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3424
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
3425
0
        return -1;
3426
0
    }
3427
49
    txn->remove(stats_key_begin, stats_key_end);
3428
49
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
3429
49
                 << " end=" << hex(stats_key_end);
3430
49
    txn->remove(job_key_begin, job_key_end);
3431
49
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
3432
49
    std::string schema_key_begin, schema_key_end;
3433
49
    std::string schema_dict_key;
3434
49
    std::string versioned_schema_key_begin, versioned_schema_key_end;
3435
49
    if (partition_id <= 0) {
3436
        // Delete schema kv of this index
3437
15
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
3438
15
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
3439
15
        txn->remove(schema_key_begin, schema_key_end);
3440
15
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
3441
15
                     << " end=" << hex(schema_key_end);
3442
15
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
3443
15
        txn->remove(schema_dict_key);
3444
15
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
3445
15
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
3446
15
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
3447
15
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
3448
15
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
3449
15
                     << " end=" << hex(versioned_schema_key_end);
3450
15
    }
3451
3452
49
    TxnErrorCode err = txn->commit();
3453
49
    if (err != TxnErrorCode::TXN_OK) {
3454
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
3455
0
                     << " err=" << err;
3456
0
        return -1;
3457
0
    }
3458
3459
49
    return ret;
3460
49
}
3461
3462
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
3463
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
3464
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
3465
5.61k
    if (num_segments <= 0) return 0;
3466
3467
5.61k
    std::vector<std::string> file_paths;
3468
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
3469
0
        return -1;
3470
0
    }
3471
3472
    // Process inverted indexes
3473
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
3474
5.61k
    InvertedIndexStorageFormatPB index_format = rs_meta_pb.has_inverted_index_storage_format()
3475
5.61k
                                                        ? rs_meta_pb.inverted_index_storage_format()
3476
5.61k
                                                        : InvertedIndexStorageFormatPB::V1;
3477
5.61k
    bool delete_rowset_data_by_prefix = false;
3478
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3479
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3480
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3481
0
        delete_rowset_data_by_prefix = true;
3482
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
3483
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
3484
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3485
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3486
10.0k
            }
3487
10.0k
        }
3488
4.80k
        if (!rs_meta_pb.has_inverted_index_storage_format() &&
3489
4.80k
            rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
3490
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
3491
2.00k
        }
3492
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
3493
        // schema version and index id are not found, delete rowset data by prefix directly.
3494
0
        delete_rowset_data_by_prefix = true;
3495
809
    } else {
3496
        // otherwise, try to get schema kv
3497
809
        InvertedIndexInfo index_info;
3498
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
3499
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
3500
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3501
809
                                 &inverted_index_get_ret);
3502
809
        if (inverted_index_get_ret == 0) {
3503
809
            if (!rs_meta_pb.has_inverted_index_storage_format()) {
3504
809
                index_format = index_info.first;
3505
809
            }
3506
809
            index_ids = index_info.second;
3507
809
        } else if (inverted_index_get_ret == 1) {
3508
            // 1. Schema kv not found means tablet has been recycled
3509
            // Maybe some tablet recycle failed by some bugs
3510
            // We need to delete again to double check
3511
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3512
            // because we are uncertain about the inverted index information.
3513
            // If there are inverted indexes, some data might not be deleted,
3514
            // but this is acceptable as we have made our best effort to delete the data.
3515
0
            LOG_INFO(
3516
0
                    "delete rowset data schema kv not found, need to delete again to double "
3517
0
                    "check")
3518
0
                    .tag("instance_id", instance_id_)
3519
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3520
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
3521
            // Currently index_ids is guaranteed to be empty,
3522
            // but we clear it again here as a safeguard against future code changes
3523
            // that might cause index_ids to no longer be empty
3524
0
            index_format = InvertedIndexStorageFormatPB::V2;
3525
0
            index_ids.clear();
3526
0
        } else {
3527
            // failed to get schema kv, delete rowset data by prefix directly.
3528
0
            delete_rowset_data_by_prefix = true;
3529
0
        }
3530
809
    }
3531
3532
5.61k
    if (delete_rowset_data_by_prefix) {
3533
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
3534
0
                                  rs_meta_pb.rowset_id_v2());
3535
0
    }
3536
3537
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
3538
5.61k
    if (it == accessor_map_.end()) {
3539
1.60k
        LOG_WARNING("instance has no such resource id")
3540
1.60k
                .tag("instance_id", instance_id_)
3541
1.60k
                .tag("resource_id", rs_meta_pb.resource_id());
3542
1.60k
        return -1;
3543
1.60k
    }
3544
4.01k
    auto& accessor = it->second;
3545
3546
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
3547
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
3548
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
3549
20.0k
        add_file_to_delete_if_not_packed(rs_meta_pb, segment_path(tablet_id, rowset_id, i),
3550
20.0k
                                         &file_paths);
3551
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
3552
40.0k
            for (const auto& index_id : index_ids) {
3553
40.0k
                add_file_to_delete_if_not_packed(
3554
40.0k
                        rs_meta_pb,
3555
40.0k
                        inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
3556
40.0k
                                               index_id.second),
3557
40.0k
                        &file_paths);
3558
40.0k
            }
3559
20.0k
        } else if (!index_ids.empty()) {
3560
0
            add_file_to_delete_if_not_packed(
3561
0
                    rs_meta_pb, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
3562
0
        }
3563
20.0k
    }
3564
3565
    // Process delete bitmap - check where it's stored.
3566
4.01k
    DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3567
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3568
4.01k
                                                       &delete_bitmap_storage_type) != 0) {
3569
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3570
0
                .tag("instance_id", instance_id_)
3571
0
                .tag("tablet_id", tablet_id)
3572
0
                .tag("rowset_id", rowset_id);
3573
0
        return -1;
3574
0
    }
3575
4.01k
    if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3576
2.00k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3577
2.00k
    }
3578
    // TODO(AlexYue): seems could do do batch
3579
4.01k
    return accessor->delete_files(file_paths);
3580
4.01k
}
3581
3582
62.3k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3583
62.3k
    LOG_INFO("begin process_packed_file_location_index")
3584
62.3k
            .tag("instance_id", instance_id_)
3585
62.3k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3586
62.3k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3587
62.3k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3588
62.3k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3589
62.3k
    if (index_map.empty()) {
3590
62.3k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3591
62.3k
                .tag("instance_id", instance_id_)
3592
62.3k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3593
62.3k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3594
62.3k
        return 0;
3595
62.3k
    }
3596
3597
17
    struct PackedSmallFileInfo {
3598
17
        std::string small_file_path;
3599
17
    };
3600
17
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3601
17
    packed_file_updates.reserve(index_map.size());
3602
27
    for (const auto& [small_path, index_pb] : index_map) {
3603
27
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3604
0
            continue;
3605
0
        }
3606
27
        packed_file_updates[index_pb.packed_file_path()].push_back(
3607
27
                PackedSmallFileInfo {small_path});
3608
27
    }
3609
17
    if (packed_file_updates.empty()) {
3610
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3611
0
                .tag("instance_id", instance_id_)
3612
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3613
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3614
0
                .tag("index_map_size", index_map.size());
3615
0
        return 0;
3616
0
    }
3617
3618
17
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3619
17
    int ret = 0;
3620
24
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3621
24
        if (small_files.empty()) {
3622
0
            continue;
3623
0
        }
3624
3625
24
        bool success = false;
3626
24
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3627
24
            std::unique_ptr<Transaction> txn;
3628
24
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3629
24
            if (err != TxnErrorCode::TXN_OK) {
3630
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3631
0
                        .tag("instance_id", instance_id_)
3632
0
                        .tag("packed_file_path", packed_file_path)
3633
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3634
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3635
0
                        .tag("err", err);
3636
0
                ret = -1;
3637
0
                break;
3638
0
            }
3639
3640
24
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3641
24
            std::string packed_val;
3642
24
            err = txn->get(packed_key, &packed_val);
3643
24
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3644
0
                LOG_WARNING("packed file info not found when recycling rowset")
3645
0
                        .tag("instance_id", instance_id_)
3646
0
                        .tag("packed_file_path", packed_file_path)
3647
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3648
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3649
0
                        .tag("key", hex(packed_key))
3650
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3651
                // Skip this packed file entry and continue with others
3652
0
                success = true;
3653
0
                break;
3654
0
            }
3655
24
            if (err != TxnErrorCode::TXN_OK) {
3656
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
3657
0
                        .tag("instance_id", instance_id_)
3658
0
                        .tag("packed_file_path", packed_file_path)
3659
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3660
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3661
0
                        .tag("err", err);
3662
0
                ret = -1;
3663
0
                break;
3664
0
            }
3665
3666
24
            cloud::PackedFileInfoPB packed_info;
3667
24
            if (!packed_info.ParseFromString(packed_val)) {
3668
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
3669
0
                        .tag("instance_id", instance_id_)
3670
0
                        .tag("packed_file_path", packed_file_path)
3671
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3672
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3673
0
                ret = -1;
3674
0
                break;
3675
0
            }
3676
3677
24
            LOG_INFO("packed file update check")
3678
24
                    .tag("instance_id", instance_id_)
3679
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3680
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3681
24
                    .tag("merged_file_path", packed_file_path)
3682
24
                    .tag("requested_small_files", small_files.size())
3683
24
                    .tag("merge_entries", packed_info.slices_size());
3684
3685
24
            auto* small_file_entries = packed_info.mutable_slices();
3686
24
            int64_t changed_files = 0;
3687
24
            int64_t missing_entries = 0;
3688
24
            int64_t already_deleted = 0;
3689
27
            for (const auto& small_file_info : small_files) {
3690
27
                bool found = false;
3691
87
                for (auto& small_file_entry : *small_file_entries) {
3692
87
                    if (small_file_entry.path() == small_file_info.small_file_path) {
3693
27
                        if (!small_file_entry.deleted()) {
3694
27
                            small_file_entry.set_deleted(true);
3695
27
                            if (!small_file_entry.corrected()) {
3696
27
                                small_file_entry.set_corrected(true);
3697
27
                            }
3698
27
                            ++changed_files;
3699
27
                        } else {
3700
0
                            ++already_deleted;
3701
0
                        }
3702
27
                        found = true;
3703
27
                        break;
3704
27
                    }
3705
87
                }
3706
27
                if (!found) {
3707
0
                    ++missing_entries;
3708
0
                    LOG_WARNING("packed file info missing small file entry")
3709
0
                            .tag("instance_id", instance_id_)
3710
0
                            .tag("packed_file_path", packed_file_path)
3711
0
                            .tag("small_file_path", small_file_info.small_file_path)
3712
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3713
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
3714
0
                }
3715
27
            }
3716
3717
24
            if (changed_files == 0) {
3718
0
                LOG_INFO("skip merge file update: no merge entries changed")
3719
0
                        .tag("instance_id", instance_id_)
3720
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3721
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3722
0
                        .tag("merged_file_path", packed_file_path)
3723
0
                        .tag("missing_entries", missing_entries)
3724
0
                        .tag("already_deleted", already_deleted)
3725
0
                        .tag("requested_small_files", small_files.size())
3726
0
                        .tag("merge_entries", packed_info.slices_size());
3727
0
                success = true;
3728
0
                break;
3729
0
            }
3730
3731
            // Calculate remaining files
3732
24
            int64_t left_file_count = 0;
3733
24
            int64_t left_file_bytes = 0;
3734
141
            for (const auto& small_file_entry : packed_info.slices()) {
3735
141
                if (!small_file_entry.deleted()) {
3736
57
                    ++left_file_count;
3737
57
                    left_file_bytes += small_file_entry.size();
3738
57
                }
3739
141
            }
3740
24
            packed_info.set_remaining_slice_bytes(left_file_bytes);
3741
24
            packed_info.set_ref_cnt(left_file_count);
3742
24
            LOG_INFO("updated packed file reference info")
3743
24
                    .tag("instance_id", instance_id_)
3744
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3745
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3746
24
                    .tag("packed_file_path", packed_file_path)
3747
24
                    .tag("ref_cnt", left_file_count)
3748
24
                    .tag("left_file_bytes", left_file_bytes);
3749
3750
24
            if (left_file_count == 0) {
3751
7
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3752
7
            }
3753
3754
24
            std::string updated_val;
3755
24
            if (!packed_info.SerializeToString(&updated_val)) {
3756
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
3757
0
                        .tag("instance_id", instance_id_)
3758
0
                        .tag("packed_file_path", packed_file_path)
3759
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3760
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3761
0
                ret = -1;
3762
0
                break;
3763
0
            }
3764
3765
24
            txn->put(packed_key, updated_val);
3766
24
            err = txn->commit();
3767
24
            if (err == TxnErrorCode::TXN_OK) {
3768
24
                success = true;
3769
24
                if (left_file_count == 0) {
3770
7
                    LOG_INFO("packed file ready to delete, deleting immediately")
3771
7
                            .tag("instance_id", instance_id_)
3772
7
                            .tag("packed_file_path", packed_file_path);
3773
7
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3774
0
                        ret = -1;
3775
0
                    }
3776
7
                }
3777
24
                break;
3778
24
            }
3779
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
3780
0
                if (attempt >= max_retry_times) {
3781
0
                    LOG_WARNING("packed file info update conflict after max retry")
3782
0
                            .tag("instance_id", instance_id_)
3783
0
                            .tag("packed_file_path", packed_file_path)
3784
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3785
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
3786
0
                            .tag("changed_files", changed_files)
3787
0
                            .tag("attempt", attempt);
3788
0
                    ret = -1;
3789
0
                    break;
3790
0
                }
3791
0
                LOG_WARNING("packed file info update conflict, retrying")
3792
0
                        .tag("instance_id", instance_id_)
3793
0
                        .tag("packed_file_path", packed_file_path)
3794
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3795
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3796
0
                        .tag("changed_files", changed_files)
3797
0
                        .tag("attempt", attempt);
3798
0
                sleep_for_packed_file_retry();
3799
0
                continue;
3800
0
            }
3801
3802
0
            LOG_WARNING("failed to commit packed file info update")
3803
0
                    .tag("instance_id", instance_id_)
3804
0
                    .tag("packed_file_path", packed_file_path)
3805
0
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3806
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3807
0
                    .tag("err", err)
3808
0
                    .tag("changed_files", changed_files);
3809
0
            ret = -1;
3810
0
            break;
3811
0
        }
3812
3813
24
        if (!success) {
3814
0
            ret = -1;
3815
0
        }
3816
24
    }
3817
3818
17
    return ret;
3819
17
}
3820
3821
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(
3822
        int64_t tablet_id, const std::string& rowset_id,
3823
58.2k
        DeleteBitmapStorageType* out_storage_type) {
3824
58.2k
    if (out_storage_type) {
3825
58.2k
        *out_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3826
58.2k
    }
3827
3828
    // Get delete bitmap storage info from FDB
3829
58.2k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
3830
58.2k
    std::unique_ptr<Transaction> txn;
3831
58.2k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
3832
58.2k
    if (err != TxnErrorCode::TXN_OK) {
3833
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
3834
0
                .tag("instance_id", instance_id_)
3835
0
                .tag("tablet_id", tablet_id)
3836
0
                .tag("rowset_id", rowset_id)
3837
0
                .tag("err", err);
3838
0
        return -1;
3839
0
    }
3840
3841
58.2k
    ValueBuf dbm_val;
3842
58.2k
    err = cloud::blob_get(txn.get(), dbm_key, &dbm_val);
3843
58.2k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3844
        // No delete bitmap for this rowset, nothing to do
3845
4.66k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
3846
4.66k
                .tag("instance_id", instance_id_)
3847
4.66k
                .tag("tablet_id", tablet_id)
3848
4.66k
                .tag("rowset_id", rowset_id);
3849
4.66k
        return 0;
3850
4.66k
    }
3851
53.5k
    if (err != TxnErrorCode::TXN_OK) {
3852
0
        LOG_WARNING("failed to get 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
53.5k
    DeleteBitmapStoragePB storage;
3861
53.5k
    if (!dbm_val.to_pb(&storage)) {
3862
0
        LOG_WARNING("failed to parse delete bitmap storage")
3863
0
                .tag("instance_id", instance_id_)
3864
0
                .tag("tablet_id", tablet_id)
3865
0
                .tag("rowset_id", rowset_id);
3866
0
        return -1;
3867
0
    }
3868
3869
53.5k
    if (storage.store_in_fdb()) {
3870
0
        if (out_storage_type) {
3871
0
            *out_storage_type = DeleteBitmapStorageType::IN_FDB;
3872
0
        }
3873
0
        return 0;
3874
0
    }
3875
3876
    // Check if delete bitmap is stored in standalone file.
3877
53.5k
    if (!storage.has_packed_slice_location() ||
3878
53.5k
        storage.packed_slice_location().packed_file_path().empty()) {
3879
53.5k
        if (out_storage_type) {
3880
53.5k
            *out_storage_type = DeleteBitmapStorageType::STANDALONE_FILE;
3881
53.5k
        }
3882
53.5k
        return 0;
3883
53.5k
    }
3884
3885
18.4E
    if (out_storage_type) {
3886
0
        *out_storage_type = DeleteBitmapStorageType::PACKED_FILE;
3887
0
    }
3888
3889
18.4E
    const auto& packed_loc = storage.packed_slice_location();
3890
18.4E
    const std::string& packed_file_path = packed_loc.packed_file_path();
3891
3892
18.4E
    LOG_INFO("decrementing delete bitmap packed file ref count")
3893
18.4E
            .tag("instance_id", instance_id_)
3894
18.4E
            .tag("tablet_id", tablet_id)
3895
18.4E
            .tag("rowset_id", rowset_id)
3896
18.4E
            .tag("packed_file_path", packed_file_path);
3897
3898
18.4E
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3899
18.4E
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3900
0
        std::unique_ptr<Transaction> update_txn;
3901
0
        err = txn_kv_->create_txn(&update_txn);
3902
0
        if (err != TxnErrorCode::TXN_OK) {
3903
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
3904
0
                    .tag("instance_id", instance_id_)
3905
0
                    .tag("tablet_id", tablet_id)
3906
0
                    .tag("rowset_id", rowset_id)
3907
0
                    .tag("err", err);
3908
0
            return -1;
3909
0
        }
3910
3911
0
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3912
0
        std::string packed_val;
3913
0
        err = update_txn->get(packed_key, &packed_val);
3914
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3915
0
            LOG_WARNING("packed file info not found for delete bitmap")
3916
0
                    .tag("instance_id", instance_id_)
3917
0
                    .tag("tablet_id", tablet_id)
3918
0
                    .tag("rowset_id", rowset_id)
3919
0
                    .tag("packed_file_path", packed_file_path);
3920
0
            return 0;
3921
0
        }
3922
0
        if (err != TxnErrorCode::TXN_OK) {
3923
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
3924
0
                    .tag("instance_id", instance_id_)
3925
0
                    .tag("tablet_id", tablet_id)
3926
0
                    .tag("rowset_id", rowset_id)
3927
0
                    .tag("packed_file_path", packed_file_path)
3928
0
                    .tag("err", err);
3929
0
            return -1;
3930
0
        }
3931
3932
0
        cloud::PackedFileInfoPB packed_info;
3933
0
        if (!packed_info.ParseFromString(packed_val)) {
3934
0
            LOG_WARNING("failed to parse packed file info 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 -1;
3940
0
        }
3941
3942
        // Find and mark the small file entry as deleted
3943
        // Use tablet_id and rowset_id to match entry instead of path,
3944
        // because path format may vary with path_version (with or without shard prefix)
3945
0
        auto* entries = packed_info.mutable_slices();
3946
0
        bool found = false;
3947
0
        bool already_deleted = false;
3948
0
        for (auto& entry : *entries) {
3949
0
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
3950
0
                if (!entry.deleted()) {
3951
0
                    entry.set_deleted(true);
3952
0
                    if (!entry.corrected()) {
3953
0
                        entry.set_corrected(true);
3954
0
                    }
3955
0
                } else {
3956
0
                    already_deleted = true;
3957
0
                }
3958
0
                found = true;
3959
0
                break;
3960
0
            }
3961
0
        }
3962
3963
0
        if (!found) {
3964
0
            LOG_WARNING("delete bitmap entry not found in packed file")
3965
0
                    .tag("instance_id", instance_id_)
3966
0
                    .tag("tablet_id", tablet_id)
3967
0
                    .tag("rowset_id", rowset_id)
3968
0
                    .tag("packed_file_path", packed_file_path);
3969
0
            return 0;
3970
0
        }
3971
3972
0
        if (already_deleted) {
3973
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
3974
0
                    .tag("instance_id", instance_id_)
3975
0
                    .tag("tablet_id", tablet_id)
3976
0
                    .tag("rowset_id", rowset_id)
3977
0
                    .tag("packed_file_path", packed_file_path);
3978
0
            return 0;
3979
0
        }
3980
3981
        // Calculate remaining files
3982
0
        int64_t left_file_count = 0;
3983
0
        int64_t left_file_bytes = 0;
3984
0
        for (const auto& entry : packed_info.slices()) {
3985
0
            if (!entry.deleted()) {
3986
0
                ++left_file_count;
3987
0
                left_file_bytes += entry.size();
3988
0
            }
3989
0
        }
3990
0
        packed_info.set_remaining_slice_bytes(left_file_bytes);
3991
0
        packed_info.set_ref_cnt(left_file_count);
3992
3993
0
        if (left_file_count == 0) {
3994
0
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3995
0
        }
3996
3997
0
        std::string updated_val;
3998
0
        if (!packed_info.SerializeToString(&updated_val)) {
3999
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
4000
0
                    .tag("instance_id", instance_id_)
4001
0
                    .tag("tablet_id", tablet_id)
4002
0
                    .tag("rowset_id", rowset_id)
4003
0
                    .tag("packed_file_path", packed_file_path);
4004
0
            return -1;
4005
0
        }
4006
4007
0
        update_txn->put(packed_key, updated_val);
4008
0
        err = update_txn->commit();
4009
0
        if (err == TxnErrorCode::TXN_OK) {
4010
0
            LOG_INFO("delete bitmap packed file ref count decremented")
4011
0
                    .tag("instance_id", instance_id_)
4012
0
                    .tag("tablet_id", tablet_id)
4013
0
                    .tag("rowset_id", rowset_id)
4014
0
                    .tag("packed_file_path", packed_file_path)
4015
0
                    .tag("left_file_count", left_file_count);
4016
0
            if (left_file_count == 0) {
4017
0
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4018
0
                    return -1;
4019
0
                }
4020
0
            }
4021
0
            return 0;
4022
0
        }
4023
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4024
0
            if (attempt >= max_retry_times) {
4025
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
4026
0
                        .tag("instance_id", instance_id_)
4027
0
                        .tag("tablet_id", tablet_id)
4028
0
                        .tag("rowset_id", rowset_id)
4029
0
                        .tag("packed_file_path", packed_file_path)
4030
0
                        .tag("attempt", attempt);
4031
0
                return -1;
4032
0
            }
4033
0
            sleep_for_packed_file_retry();
4034
0
            continue;
4035
0
        }
4036
4037
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
4038
0
                .tag("instance_id", instance_id_)
4039
0
                .tag("tablet_id", tablet_id)
4040
0
                .tag("rowset_id", rowset_id)
4041
0
                .tag("packed_file_path", packed_file_path)
4042
0
                .tag("err", err);
4043
0
        return -1;
4044
0
    }
4045
4046
18.4E
    return -1;
4047
18.4E
}
4048
4049
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
4050
                                                const std::string& packed_key,
4051
7
                                                const cloud::PackedFileInfoPB& packed_info) {
4052
7
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
4053
0
        LOG_WARNING("packed file missing resource id when recycling")
4054
0
                .tag("instance_id", instance_id_)
4055
0
                .tag("packed_file_path", packed_file_path);
4056
0
        return -1;
4057
0
    }
4058
4059
7
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
4060
7
    if (!accessor) {
4061
0
        LOG_WARNING("no accessor available to delete packed file")
4062
0
                .tag("instance_id", instance_id_)
4063
0
                .tag("packed_file_path", packed_file_path)
4064
0
                .tag("resource_id", packed_info.resource_id());
4065
0
        return -1;
4066
0
    }
4067
4068
7
    int del_ret = accessor->delete_file(packed_file_path);
4069
7
    if (del_ret != 0 && del_ret != 1) {
4070
0
        LOG_WARNING("failed to delete packed file")
4071
0
                .tag("instance_id", instance_id_)
4072
0
                .tag("packed_file_path", packed_file_path)
4073
0
                .tag("resource_id", resource_id)
4074
0
                .tag("ret", del_ret);
4075
0
        return -1;
4076
0
    }
4077
7
    if (del_ret == 1) {
4078
0
        LOG_INFO("packed file already removed")
4079
0
                .tag("instance_id", instance_id_)
4080
0
                .tag("packed_file_path", packed_file_path)
4081
0
                .tag("resource_id", resource_id);
4082
7
    } else {
4083
7
        LOG_INFO("deleted packed file")
4084
7
                .tag("instance_id", instance_id_)
4085
7
                .tag("packed_file_path", packed_file_path)
4086
7
                .tag("resource_id", resource_id);
4087
7
    }
4088
4089
7
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
4090
7
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4091
7
        std::unique_ptr<Transaction> del_txn;
4092
7
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
4093
7
        if (err != TxnErrorCode::TXN_OK) {
4094
0
            LOG_WARNING("failed to create txn when removing packed file kv")
4095
0
                    .tag("instance_id", instance_id_)
4096
0
                    .tag("packed_file_path", packed_file_path)
4097
0
                    .tag("attempt", attempt)
4098
0
                    .tag("err", err);
4099
0
            return -1;
4100
0
        }
4101
4102
7
        std::string latest_val;
4103
7
        err = del_txn->get(packed_key, &latest_val);
4104
7
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4105
0
            return 0;
4106
0
        }
4107
7
        if (err != TxnErrorCode::TXN_OK) {
4108
0
            LOG_WARNING("failed to re-read packed file kv before removal")
4109
0
                    .tag("instance_id", instance_id_)
4110
0
                    .tag("packed_file_path", packed_file_path)
4111
0
                    .tag("attempt", attempt)
4112
0
                    .tag("err", err);
4113
0
            return -1;
4114
0
        }
4115
4116
7
        cloud::PackedFileInfoPB latest_info;
4117
7
        if (!latest_info.ParseFromString(latest_val)) {
4118
0
            LOG_WARNING("failed to parse packed file info before removal")
4119
0
                    .tag("instance_id", instance_id_)
4120
0
                    .tag("packed_file_path", packed_file_path)
4121
0
                    .tag("attempt", attempt);
4122
0
            return -1;
4123
0
        }
4124
4125
7
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
4126
7
              latest_info.ref_cnt() == 0)) {
4127
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
4128
0
                    .tag("instance_id", instance_id_)
4129
0
                    .tag("packed_file_path", packed_file_path)
4130
0
                    .tag("attempt", attempt);
4131
0
            return 0;
4132
0
        }
4133
4134
7
        del_txn->remove(packed_key);
4135
7
        err = del_txn->commit();
4136
7
        if (err == TxnErrorCode::TXN_OK) {
4137
7
            LOG_INFO("removed packed file metadata")
4138
7
                    .tag("instance_id", instance_id_)
4139
7
                    .tag("packed_file_path", packed_file_path);
4140
7
            return 0;
4141
7
        }
4142
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4143
0
            if (attempt >= max_retry_times) {
4144
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
4145
0
                        .tag("instance_id", instance_id_)
4146
0
                        .tag("packed_file_path", packed_file_path)
4147
0
                        .tag("attempt", attempt);
4148
0
                return -1;
4149
0
            }
4150
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
4151
0
                    .tag("instance_id", instance_id_)
4152
0
                    .tag("packed_file_path", packed_file_path)
4153
0
                    .tag("attempt", attempt);
4154
0
            sleep_for_packed_file_retry();
4155
0
            continue;
4156
0
        }
4157
0
        LOG_WARNING("failed to remove packed file kv")
4158
0
                .tag("instance_id", instance_id_)
4159
0
                .tag("packed_file_path", packed_file_path)
4160
0
                .tag("attempt", attempt)
4161
0
                .tag("err", err);
4162
0
        return -1;
4163
0
    }
4164
0
    return -1;
4165
7
}
4166
4167
int InstanceRecycler::delete_rowset_data(
4168
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
4169
57
        RecyclerMetricsContext& metrics_context) {
4170
57
    int ret = 0;
4171
    // resource_id -> file_paths
4172
57
    std::map<std::string, std::vector<std::string>> resource_file_paths;
4173
    // (resource_id, tablet_id, rowset_id)
4174
57
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
4175
57
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
4176
4177
56.2k
    for (const auto& [_, rs] : rowsets) {
4178
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
4179
        // due to aborted schema change.
4180
56.2k
        if (is_formal_rowset) {
4181
3.19k
            std::lock_guard lock(recycled_tablets_mtx_);
4182
3.19k
            if (recycled_tablets_.count(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
4183
                // Tablet has been recycled and this rowset has no packed slices, so file data
4184
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
4185
                // slice info must still run to decrement packed file ref counts.
4186
0
                continue;
4187
0
            }
4188
3.19k
        }
4189
4190
56.2k
        int64_t num_segments = rs.num_segments();
4191
        // Check num_segments before accessor lookup, because empty rowsets
4192
        // (e.g. base compaction output of empty rowsets) may have no resource_id
4193
        // set. Skipping them early avoids a spurious "no such resource id" error
4194
        // that marks the entire batch as failed and prevents txn_remove from
4195
        // cleaning up recycle KV keys.
4196
56.2k
        if (num_segments <= 0) {
4197
0
            metrics_context.total_recycled_num++;
4198
0
            metrics_context.total_recycled_data_size += rs.total_disk_size();
4199
0
            continue;
4200
0
        }
4201
4202
56.2k
        auto it = accessor_map_.find(rs.resource_id());
4203
        // possible if the accessor is not initilized correctly
4204
56.2k
        if (it == accessor_map_.end()) [[unlikely]] {
4205
2.00k
            LOG_WARNING("instance has no such resource id")
4206
2.00k
                    .tag("instance_id", instance_id_)
4207
2.00k
                    .tag("resource_id", rs.resource_id());
4208
2.00k
            ret = -1;
4209
2.00k
            continue;
4210
2.00k
        }
4211
4212
54.2k
        auto& file_paths = resource_file_paths[rs.resource_id()];
4213
54.2k
        const auto& rowset_id = rs.rowset_id_v2();
4214
54.2k
        int64_t tablet_id = rs.tablet_id();
4215
54.2k
        LOG_INFO("recycle rowset merge index size")
4216
54.2k
                .tag("instance_id", instance_id_)
4217
54.2k
                .tag("tablet_id", tablet_id)
4218
54.2k
                .tag("rowset_id", rowset_id)
4219
54.2k
                .tag("merge_index_size", rs.packed_slice_locations_size());
4220
54.2k
        if (decrement_packed_file_ref_counts(rs) != 0) {
4221
0
            ret = -1;
4222
0
            continue;
4223
0
        }
4224
4225
        // Process delete bitmap - check where it's stored.
4226
54.2k
        DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4227
54.2k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
4228
54.2k
                                                           &delete_bitmap_storage_type) != 0) {
4229
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
4230
0
                    .tag("instance_id", instance_id_)
4231
0
                    .tag("tablet_id", tablet_id)
4232
0
                    .tag("rowset_id", rowset_id);
4233
0
            ret = -1;
4234
0
            continue;
4235
0
        }
4236
54.2k
        if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
4237
51.5k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
4238
51.5k
        }
4239
4240
        // Process inverted indexes
4241
54.2k
        std::vector<std::pair<int64_t, std::string>> index_ids;
4242
        // default format as v1.
4243
54.2k
        InvertedIndexStorageFormatPB index_format = rs.has_inverted_index_storage_format()
4244
54.2k
                                                            ? rs.inverted_index_storage_format()
4245
54.2k
                                                            : InvertedIndexStorageFormatPB::V1;
4246
54.2k
        int inverted_index_get_ret = 0;
4247
54.2k
        if (rs.has_tablet_schema()) {
4248
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
4249
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
4250
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
4251
53.5k
                }
4252
53.5k
            }
4253
26.6k
            if (!rs.has_inverted_index_storage_format() &&
4254
26.6k
                rs.tablet_schema().has_inverted_index_storage_format()) {
4255
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
4256
26.5k
            }
4257
27.6k
        } else {
4258
27.6k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
4259
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
4260
0
                                "instance_id="
4261
0
                             << instance_id_ << " tablet_id=" << tablet_id
4262
0
                             << " rowset_id=" << rowset_id;
4263
0
                ret = -1;
4264
0
                continue;
4265
0
            }
4266
27.6k
            InvertedIndexInfo index_info;
4267
27.6k
            inverted_index_get_ret =
4268
27.6k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
4269
27.6k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
4270
27.6k
                                     &inverted_index_get_ret);
4271
27.6k
            if (inverted_index_get_ret == 0) {
4272
27.1k
                if (!rs.has_inverted_index_storage_format()) {
4273
27.1k
                    index_format = index_info.first;
4274
27.1k
                }
4275
27.1k
                index_ids = index_info.second;
4276
27.1k
            } else if (inverted_index_get_ret == 1) {
4277
                // 1. Schema kv not found means tablet has been recycled
4278
                // Maybe some tablet recycle failed by some bugs
4279
                // We need to delete again to double check
4280
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
4281
                // because we are uncertain about the inverted index information.
4282
                // If there are inverted indexes, some data might not be deleted,
4283
                // but this is acceptable as we have made our best effort to delete the data.
4284
503
                LOG_INFO(
4285
503
                        "delete rowset data schema kv not found, need to delete again to "
4286
503
                        "double "
4287
503
                        "check")
4288
503
                        .tag("instance_id", instance_id_)
4289
503
                        .tag("tablet_id", tablet_id)
4290
503
                        .tag("rowset", rs.ShortDebugString());
4291
                // Currently index_ids is guaranteed to be empty,
4292
                // but we clear it again here as a safeguard against future code changes
4293
                // that might cause index_ids to no longer be empty
4294
503
                index_format = InvertedIndexStorageFormatPB::V2;
4295
503
                index_ids.clear();
4296
18.4E
            } else {
4297
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
4298
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4299
18.4E
                ret = -1;
4300
18.4E
                continue;
4301
18.4E
            }
4302
27.6k
        }
4303
54.2k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
4304
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
4305
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
4306
10
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
4307
10
            continue;
4308
10
        }
4309
323k
        for (int64_t i = 0; i < num_segments; ++i) {
4310
269k
            add_file_to_delete_if_not_packed(rs, segment_path(tablet_id, rowset_id, i),
4311
269k
                                             &file_paths);
4312
269k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
4313
535k
                for (const auto& index_id : index_ids) {
4314
535k
                    add_file_to_delete_if_not_packed(
4315
535k
                            rs,
4316
535k
                            inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
4317
535k
                                                   index_id.second),
4318
535k
                            &file_paths);
4319
535k
                }
4320
268k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
4321
                // try to recycle inverted index v2 when get_ret == 1
4322
                // we treat schema not found as if it has a v2 format inverted index
4323
                // to reduce chance of data leakage
4324
2.50k
                if (inverted_index_get_ret == 1) {
4325
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
4326
2.50k
                            .tag("instance_id", instance_id_)
4327
2.50k
                            .tag("inverted index v2 path",
4328
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, i));
4329
2.50k
                }
4330
2.50k
                add_file_to_delete_if_not_packed(
4331
2.50k
                        rs, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
4332
2.50k
            }
4333
269k
        }
4334
54.2k
    }
4335
4336
57
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
4337
57
                                                 "delete_rowset_data",
4338
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
4338
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
4338
53
                                                 [](const int& ret) { return ret != 0; });
4339
57
    for (auto& [resource_id, file_paths] : resource_file_paths) {
4340
48
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4341
48
            DCHECK(accessor_map_.count(*rid))
4342
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4343
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4344
48
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4345
48
                                     &accessor_map_);
4346
48
            if (!accessor_map_.contains(*rid)) {
4347
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4348
0
                        .tag("resource_id", resource_id)
4349
0
                        .tag("instance_id", instance_id_);
4350
0
                return -1;
4351
0
            }
4352
48
            auto& accessor = accessor_map_[*rid];
4353
48
            int ret = accessor->delete_files(*paths);
4354
48
            if (!ret) {
4355
                // deduplication of different files with the same rowset id
4356
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4357
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4358
48
                std::set<std::string> deleted_rowset_id;
4359
4360
48
                std::for_each(paths->begin(), paths->end(),
4361
48
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4362
855k
                               this](const std::string& path) {
4363
855k
                                  std::vector<std::string> str;
4364
855k
                                  butil::SplitString(path, '/', &str);
4365
855k
                                  std::string rowset_id;
4366
855k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4367
851k
                                      rowset_id = str.back().substr(0, pos);
4368
851k
                                  } else {
4369
4.04k
                                      if (path.find("packed_file/") != std::string::npos) {
4370
0
                                          return; // packed files do not have rowset_id encoded
4371
0
                                      }
4372
4.04k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4373
4.04k
                                      return;
4374
4.04k
                                  }
4375
851k
                                  auto rs_meta = rowsets.find(rowset_id);
4376
851k
                                  if (rs_meta != rowsets.end() &&
4377
856k
                                      !deleted_rowset_id.contains(rowset_id)) {
4378
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
4379
54.1k
                                      metrics_context.total_recycled_data_size +=
4380
54.1k
                                              rs_meta->second.total_disk_size();
4381
54.1k
                                      segment_metrics_context_.total_recycled_num +=
4382
54.1k
                                              rs_meta->second.num_segments();
4383
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
4384
54.1k
                                              rs_meta->second.total_disk_size();
4385
54.1k
                                      metrics_context.total_recycled_num++;
4386
54.1k
                                  }
4387
851k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
4362
7
                               this](const std::string& path) {
4363
7
                                  std::vector<std::string> str;
4364
7
                                  butil::SplitString(path, '/', &str);
4365
7
                                  std::string rowset_id;
4366
7
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4367
7
                                      rowset_id = str.back().substr(0, pos);
4368
7
                                  } else {
4369
0
                                      if (path.find("packed_file/") != std::string::npos) {
4370
0
                                          return; // packed files do not have rowset_id encoded
4371
0
                                      }
4372
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4373
0
                                      return;
4374
0
                                  }
4375
7
                                  auto rs_meta = rowsets.find(rowset_id);
4376
7
                                  if (rs_meta != rowsets.end() &&
4377
7
                                      !deleted_rowset_id.contains(rowset_id)) {
4378
7
                                      deleted_rowset_id.emplace(rowset_id);
4379
7
                                      metrics_context.total_recycled_data_size +=
4380
7
                                              rs_meta->second.total_disk_size();
4381
7
                                      segment_metrics_context_.total_recycled_num +=
4382
7
                                              rs_meta->second.num_segments();
4383
7
                                      segment_metrics_context_.total_recycled_data_size +=
4384
7
                                              rs_meta->second.total_disk_size();
4385
7
                                      metrics_context.total_recycled_num++;
4386
7
                                  }
4387
7
                              });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
4362
855k
                               this](const std::string& path) {
4363
855k
                                  std::vector<std::string> str;
4364
855k
                                  butil::SplitString(path, '/', &str);
4365
855k
                                  std::string rowset_id;
4366
855k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4367
851k
                                      rowset_id = str.back().substr(0, pos);
4368
851k
                                  } else {
4369
4.04k
                                      if (path.find("packed_file/") != std::string::npos) {
4370
0
                                          return; // packed files do not have rowset_id encoded
4371
0
                                      }
4372
4.04k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4373
4.04k
                                      return;
4374
4.04k
                                  }
4375
851k
                                  auto rs_meta = rowsets.find(rowset_id);
4376
851k
                                  if (rs_meta != rowsets.end() &&
4377
856k
                                      !deleted_rowset_id.contains(rowset_id)) {
4378
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
4379
54.1k
                                      metrics_context.total_recycled_data_size +=
4380
54.1k
                                              rs_meta->second.total_disk_size();
4381
54.1k
                                      segment_metrics_context_.total_recycled_num +=
4382
54.1k
                                              rs_meta->second.num_segments();
4383
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
4384
54.1k
                                              rs_meta->second.total_disk_size();
4385
54.1k
                                      metrics_context.total_recycled_num++;
4386
54.1k
                                  }
4387
851k
                              });
4388
48
            }
4389
48
            return ret;
4390
48
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4340
5
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4341
5
            DCHECK(accessor_map_.count(*rid))
4342
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4343
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4344
5
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4345
5
                                     &accessor_map_);
4346
5
            if (!accessor_map_.contains(*rid)) {
4347
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4348
0
                        .tag("resource_id", resource_id)
4349
0
                        .tag("instance_id", instance_id_);
4350
0
                return -1;
4351
0
            }
4352
5
            auto& accessor = accessor_map_[*rid];
4353
5
            int ret = accessor->delete_files(*paths);
4354
5
            if (!ret) {
4355
                // deduplication of different files with the same rowset id
4356
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4357
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4358
5
                std::set<std::string> deleted_rowset_id;
4359
4360
5
                std::for_each(paths->begin(), paths->end(),
4361
5
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4362
5
                               this](const std::string& path) {
4363
5
                                  std::vector<std::string> str;
4364
5
                                  butil::SplitString(path, '/', &str);
4365
5
                                  std::string rowset_id;
4366
5
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4367
5
                                      rowset_id = str.back().substr(0, pos);
4368
5
                                  } else {
4369
5
                                      if (path.find("packed_file/") != std::string::npos) {
4370
5
                                          return; // packed files do not have rowset_id encoded
4371
5
                                      }
4372
5
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4373
5
                                      return;
4374
5
                                  }
4375
5
                                  auto rs_meta = rowsets.find(rowset_id);
4376
5
                                  if (rs_meta != rowsets.end() &&
4377
5
                                      !deleted_rowset_id.contains(rowset_id)) {
4378
5
                                      deleted_rowset_id.emplace(rowset_id);
4379
5
                                      metrics_context.total_recycled_data_size +=
4380
5
                                              rs_meta->second.total_disk_size();
4381
5
                                      segment_metrics_context_.total_recycled_num +=
4382
5
                                              rs_meta->second.num_segments();
4383
5
                                      segment_metrics_context_.total_recycled_data_size +=
4384
5
                                              rs_meta->second.total_disk_size();
4385
5
                                      metrics_context.total_recycled_num++;
4386
5
                                  }
4387
5
                              });
4388
5
            }
4389
5
            return ret;
4390
5
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4340
43
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4341
43
            DCHECK(accessor_map_.count(*rid))
4342
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4343
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4344
43
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4345
43
                                     &accessor_map_);
4346
43
            if (!accessor_map_.contains(*rid)) {
4347
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4348
0
                        .tag("resource_id", resource_id)
4349
0
                        .tag("instance_id", instance_id_);
4350
0
                return -1;
4351
0
            }
4352
43
            auto& accessor = accessor_map_[*rid];
4353
43
            int ret = accessor->delete_files(*paths);
4354
43
            if (!ret) {
4355
                // deduplication of different files with the same rowset id
4356
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4357
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4358
43
                std::set<std::string> deleted_rowset_id;
4359
4360
43
                std::for_each(paths->begin(), paths->end(),
4361
43
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4362
43
                               this](const std::string& path) {
4363
43
                                  std::vector<std::string> str;
4364
43
                                  butil::SplitString(path, '/', &str);
4365
43
                                  std::string rowset_id;
4366
43
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4367
43
                                      rowset_id = str.back().substr(0, pos);
4368
43
                                  } else {
4369
43
                                      if (path.find("packed_file/") != std::string::npos) {
4370
43
                                          return; // packed files do not have rowset_id encoded
4371
43
                                      }
4372
43
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4373
43
                                      return;
4374
43
                                  }
4375
43
                                  auto rs_meta = rowsets.find(rowset_id);
4376
43
                                  if (rs_meta != rowsets.end() &&
4377
43
                                      !deleted_rowset_id.contains(rowset_id)) {
4378
43
                                      deleted_rowset_id.emplace(rowset_id);
4379
43
                                      metrics_context.total_recycled_data_size +=
4380
43
                                              rs_meta->second.total_disk_size();
4381
43
                                      segment_metrics_context_.total_recycled_num +=
4382
43
                                              rs_meta->second.num_segments();
4383
43
                                      segment_metrics_context_.total_recycled_data_size +=
4384
43
                                              rs_meta->second.total_disk_size();
4385
43
                                      metrics_context.total_recycled_num++;
4386
43
                                  }
4387
43
                              });
4388
43
            }
4389
43
            return ret;
4390
43
        });
4391
48
    }
4392
57
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
4393
10
        LOG_INFO(
4394
10
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
4395
10
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
4396
10
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
4397
10
        concurrent_delete_executor.add([&]() -> int {
4398
10
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4399
10
            if (!ret) {
4400
10
                auto rs = rowsets.at(rowset_id);
4401
10
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4402
10
                metrics_context.total_recycled_num++;
4403
10
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4404
10
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4405
10
            }
4406
10
            return ret;
4407
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
4397
10
        concurrent_delete_executor.add([&]() -> int {
4398
10
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4399
10
            if (!ret) {
4400
10
                auto rs = rowsets.at(rowset_id);
4401
10
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4402
10
                metrics_context.total_recycled_num++;
4403
10
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4404
10
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4405
10
            }
4406
10
            return ret;
4407
10
        });
4408
10
    }
4409
4410
57
    bool finished = true;
4411
57
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4412
58
    for (int r : rets) {
4413
58
        if (r != 0) {
4414
0
            ret = -1;
4415
0
            break;
4416
0
        }
4417
58
    }
4418
57
    ret = finished ? ret : -1;
4419
57
    return ret;
4420
57
}
4421
4422
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
4423
3.31k
                                         const std::string& rowset_id) {
4424
3.31k
    auto it = accessor_map_.find(resource_id);
4425
3.31k
    if (it == accessor_map_.end()) {
4426
400
        LOG_WARNING("instance has no such resource id")
4427
400
                .tag("instance_id", instance_id_)
4428
400
                .tag("resource_id", resource_id)
4429
400
                .tag("tablet_id", tablet_id)
4430
400
                .tag("rowset_id", rowset_id);
4431
400
        return -1;
4432
400
    }
4433
2.91k
    auto& accessor = it->second;
4434
2.91k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
4435
3.31k
}
4436
4437
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
4438
4
    if (key.empty()) {
4439
0
        return false;
4440
0
    }
4441
4
    std::string_view key_view = key;
4442
4
    key_view.remove_prefix(1); // remove keyspace prefix
4443
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
4444
4
    if (decode_key(&key_view, &decoded) != 0) {
4445
0
        return false;
4446
0
    }
4447
4
    if (decoded.size() < 4) {
4448
0
        return false;
4449
0
    }
4450
4
    try {
4451
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
4452
4
    } catch (const std::bad_variant_access&) {
4453
0
        return false;
4454
0
    }
4455
4
    return true;
4456
4
}
4457
4458
14
int InstanceRecycler::recycle_packed_files() {
4459
14
    const std::string task_name = "recycle_packed_files";
4460
14
    auto start_tp = steady_clock::now();
4461
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
4462
14
    int ret = 0;
4463
14
    PackedFileRecycleStats stats;
4464
4465
14
    register_recycle_task(task_name, start_time);
4466
14
    DORIS_CLOUD_DEFER {
4467
14
        unregister_recycle_task(task_name);
4468
14
        int64_t cost =
4469
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4470
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4471
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4472
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4473
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4474
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4475
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4476
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4477
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4478
14
                                                             stats.bytes_object_deleted);
4479
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4480
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4481
14
                .tag("instance_id", instance_id_)
4482
14
                .tag("num_scanned", stats.num_scanned)
4483
14
                .tag("num_corrected", stats.num_corrected)
4484
14
                .tag("num_deleted", stats.num_deleted)
4485
14
                .tag("num_failed", stats.num_failed)
4486
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4487
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4488
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4489
14
                .tag("bytes_deleted", stats.bytes_deleted)
4490
14
                .tag("ret", ret);
4491
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
4466
14
    DORIS_CLOUD_DEFER {
4467
14
        unregister_recycle_task(task_name);
4468
14
        int64_t cost =
4469
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4470
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4471
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4472
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4473
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4474
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4475
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4476
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4477
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4478
14
                                                             stats.bytes_object_deleted);
4479
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4480
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4481
14
                .tag("instance_id", instance_id_)
4482
14
                .tag("num_scanned", stats.num_scanned)
4483
14
                .tag("num_corrected", stats.num_corrected)
4484
14
                .tag("num_deleted", stats.num_deleted)
4485
14
                .tag("num_failed", stats.num_failed)
4486
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4487
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4488
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4489
14
                .tag("bytes_deleted", stats.bytes_deleted)
4490
14
                .tag("ret", ret);
4491
14
    };
4492
4493
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4494
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4495
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4496
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
4493
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4494
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4495
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4496
4
    };
4497
4498
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
4499
4500
14
    std::string begin = packed_file_key({instance_id_, ""});
4501
14
    std::string end = packed_file_key({instance_id_, "\xff"});
4502
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
4503
0
        ret = -1;
4504
0
    }
4505
4506
14
    return ret;
4507
14
}
4508
4509
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
4510
                                                  RecyclerMetricsContext& metrics_context,
4511
0
                                                  int64_t partition_id, bool is_empty_tablet) {
4512
0
    std::string tablet_key_begin, tablet_key_end;
4513
4514
0
    if (partition_id > 0) {
4515
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
4516
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
4517
0
    } else {
4518
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
4519
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
4520
0
    }
4521
    // for calculate the total num or bytes of recyled objects
4522
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
4523
0
                                                          std::string_view v) -> int {
4524
0
        doris::TabletMetaCloudPB tablet_meta_pb;
4525
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
4526
0
            return 0;
4527
0
        }
4528
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
4529
4530
0
        if (config::enable_recycler_check_lazy_txn_finished &&
4531
0
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
4532
0
            return 0;
4533
0
        }
4534
4535
0
        if (!is_empty_tablet) {
4536
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
4537
0
                return 0;
4538
0
            }
4539
0
            tablet_metrics_context_.total_need_recycle_num++;
4540
0
        }
4541
0
        return 0;
4542
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_
4543
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
4544
0
    metrics_context.report(true);
4545
0
    tablet_metrics_context_.report(true);
4546
0
    segment_metrics_context_.report(true);
4547
0
    return ret;
4548
0
}
4549
4550
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
4551
0
                                                 RecyclerMetricsContext& metrics_context) {
4552
0
    int ret = 0;
4553
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
4554
0
    std::unique_ptr<Transaction> txn;
4555
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4556
0
        LOG_WARNING("failed to recycle tablet ")
4557
0
                .tag("tablet id", tablet_id)
4558
0
                .tag("instance_id", instance_id_)
4559
0
                .tag("reason", "failed to create txn");
4560
0
        ret = -1;
4561
0
    }
4562
0
    GetRowsetResponse resp;
4563
0
    std::string msg;
4564
0
    MetaServiceCode code = MetaServiceCode::OK;
4565
    // get rowsets in tablet
4566
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4567
0
                        tablet_id, code, msg, &resp);
4568
0
    if (code != MetaServiceCode::OK) {
4569
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4570
0
                .tag("tablet id", tablet_id)
4571
0
                .tag("msg", msg)
4572
0
                .tag("code", code)
4573
0
                .tag("instance id", instance_id_);
4574
0
        ret = -1;
4575
0
    }
4576
0
    for (const auto& rs_meta : resp.rowset_meta()) {
4577
        /*
4578
        * For compatibility, we skip the loop for [0-1] here.
4579
        * The purpose of this loop is to delete object files,
4580
        * and since [0-1] only has meta and doesn't have object files,
4581
        * skipping it doesn't affect system correctness.
4582
        *
4583
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
4584
        * would return error -1 directly, causing the recycle operation to fail.
4585
        *
4586
        * [0-1] doesn't have resource id is a bug.
4587
        * In the future, we will fix this problem, after that,
4588
        * we can remove this if statement.
4589
        *
4590
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
4591
        */
4592
4593
0
        if (rs_meta.end_version() == 1) {
4594
            // Assert that [0-1] has no resource_id to make sure
4595
            // this if statement will not be forgetted to remove
4596
            // when the resource id bug is fixed
4597
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4598
0
            continue;
4599
0
        }
4600
0
        if (!rs_meta.has_resource_id()) {
4601
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4602
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4603
0
                    .tag("instance_id", instance_id_)
4604
0
                    .tag("tablet_id", tablet_id);
4605
0
            continue;
4606
0
        }
4607
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4608
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4609
        // possible if the accessor is not initilized correctly
4610
0
        if (it == accessor_map_.end()) [[unlikely]] {
4611
0
            LOG_WARNING(
4612
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4613
0
                    "recycle process")
4614
0
                    .tag("tablet id", tablet_id)
4615
0
                    .tag("instance_id", instance_id_)
4616
0
                    .tag("resource_id", rs_meta.resource_id())
4617
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4618
0
            continue;
4619
0
        }
4620
4621
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
4622
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4623
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4624
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
4625
0
    }
4626
0
    return ret;
4627
0
}
4628
4629
4.26k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
4630
4.26k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
4631
4.26k
            .tag("instance_id", instance_id_)
4632
4.26k
            .tag("tablet_id", tablet_id);
4633
4634
4.26k
    if (should_recycle_versioned_keys()) {
4635
14
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
4636
14
        if (ret != 0) {
4637
0
            return ret;
4638
0
        }
4639
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
4640
        // during the recycle_versioned_tablet process.
4641
        //
4642
        // .. And remove restore job rowsets of this tablet too
4643
14
    }
4644
4645
4.26k
    int ret = 0;
4646
4.26k
    auto start_time = steady_clock::now();
4647
4648
4.26k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4649
4650
    // collect resource ids
4651
260
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4652
260
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4653
260
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4654
260
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4655
260
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
4656
260
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
4657
4658
260
    std::set<std::string> resource_ids;
4659
260
    int64_t recycle_rowsets_number = 0;
4660
260
    int64_t recycle_segments_number = 0;
4661
260
    int64_t recycle_rowsets_data_size = 0;
4662
260
    int64_t recycle_rowsets_index_size = 0;
4663
260
    int64_t recycle_restore_job_rowsets_number = 0;
4664
260
    int64_t recycle_restore_job_segments_number = 0;
4665
260
    int64_t recycle_restore_job_rowsets_data_size = 0;
4666
260
    int64_t recycle_restore_job_rowsets_index_size = 0;
4667
260
    int64_t max_rowset_version = 0;
4668
260
    int64_t min_rowset_creation_time = INT64_MAX;
4669
260
    int64_t max_rowset_creation_time = 0;
4670
260
    int64_t min_rowset_expiration_time = INT64_MAX;
4671
260
    int64_t max_rowset_expiration_time = 0;
4672
4673
260
    DORIS_CLOUD_DEFER {
4674
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4675
260
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4676
260
                .tag("instance_id", instance_id_)
4677
260
                .tag("tablet_id", tablet_id)
4678
260
                .tag("recycle rowsets number", recycle_rowsets_number)
4679
260
                .tag("recycle segments number", recycle_segments_number)
4680
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4681
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4682
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4683
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4684
260
                .tag("all restore job rowsets recycle data size",
4685
260
                     recycle_restore_job_rowsets_data_size)
4686
260
                .tag("all restore job rowsets recycle index size",
4687
260
                     recycle_restore_job_rowsets_index_size)
4688
260
                .tag("max rowset version", max_rowset_version)
4689
260
                .tag("min rowset creation time", min_rowset_creation_time)
4690
260
                .tag("max rowset creation time", max_rowset_creation_time)
4691
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
4692
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
4693
260
                .tag("task type", metrics_context.operation_type)
4694
260
                .tag("ret", ret);
4695
260
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4673
260
    DORIS_CLOUD_DEFER {
4674
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4675
260
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4676
260
                .tag("instance_id", instance_id_)
4677
260
                .tag("tablet_id", tablet_id)
4678
260
                .tag("recycle rowsets number", recycle_rowsets_number)
4679
260
                .tag("recycle segments number", recycle_segments_number)
4680
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4681
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4682
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4683
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4684
260
                .tag("all restore job rowsets recycle data size",
4685
260
                     recycle_restore_job_rowsets_data_size)
4686
260
                .tag("all restore job rowsets recycle index size",
4687
260
                     recycle_restore_job_rowsets_index_size)
4688
260
                .tag("max rowset version", max_rowset_version)
4689
260
                .tag("min rowset creation time", min_rowset_creation_time)
4690
260
                .tag("max rowset creation time", max_rowset_creation_time)
4691
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
4692
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
4693
260
                .tag("task type", metrics_context.operation_type)
4694
260
                .tag("ret", ret);
4695
260
    };
4696
4697
260
    std::unique_ptr<Transaction> txn;
4698
260
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4699
0
        LOG_WARNING("failed to recycle tablet ")
4700
0
                .tag("tablet id", tablet_id)
4701
0
                .tag("instance_id", instance_id_)
4702
0
                .tag("reason", "failed to create txn");
4703
0
        ret = -1;
4704
0
    }
4705
260
    GetRowsetResponse resp;
4706
260
    std::string msg;
4707
260
    MetaServiceCode code = MetaServiceCode::OK;
4708
    // get rowsets in tablet
4709
260
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4710
260
                        tablet_id, code, msg, &resp);
4711
260
    if (code != MetaServiceCode::OK) {
4712
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4713
0
                .tag("tablet id", tablet_id)
4714
0
                .tag("msg", msg)
4715
0
                .tag("code", code)
4716
0
                .tag("instance id", instance_id_);
4717
0
        ret = -1;
4718
0
    }
4719
260
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
4720
4721
2.55k
    for (const auto& rs_meta : resp.rowset_meta()) {
4722
2.55k
        if (!rs_meta.has_resource_id() || rs_meta.resource_id().empty()) {
4723
3
            if (rs_meta.num_segments() <= 0) {
4724
2
                LOG_INFO("rowset meta has no segments and no resource id, skip this rowset")
4725
2
                        .tag("rs_meta", rs_meta.ShortDebugString())
4726
2
                        .tag("instance_id", instance_id_)
4727
2
                        .tag("tablet_id", tablet_id);
4728
2
                recycle_rowsets_number += 1;
4729
2
                continue;
4730
2
            }
4731
1
            LOG_WARNING("rowset meta has a missing or empty resource id, impossible!")
4732
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
4733
1
                    .tag("instance_id", instance_id_)
4734
1
                    .tag("tablet_id", tablet_id);
4735
1
            return -1;
4736
3
        }
4737
2.54k
        DCHECK(rs_meta.has_resource_id() && !rs_meta.resource_id().empty())
4738
4
                << "rs_meta" << rs_meta.ShortDebugString();
4739
2.54k
        auto it = accessor_map_.find(rs_meta.resource_id());
4740
        // possible if the accessor is not initilized correctly
4741
2.54k
        if (it == accessor_map_.end()) [[unlikely]] {
4742
1
            LOG_WARNING(
4743
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4744
1
                    "recycle process")
4745
1
                    .tag("tablet id", tablet_id)
4746
1
                    .tag("instance_id", instance_id_)
4747
1
                    .tag("resource_id", rs_meta.resource_id())
4748
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4749
1
            return -1;
4750
1
        }
4751
2.54k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4752
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
4753
0
                    .tag("instance_id", instance_id_)
4754
0
                    .tag("tablet_id", tablet_id)
4755
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4756
0
            return -1;
4757
0
        }
4758
2.54k
        recycle_rowsets_number += 1;
4759
2.54k
        recycle_segments_number += rs_meta.num_segments();
4760
2.54k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4761
2.54k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4762
2.54k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4763
2.54k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4764
2.54k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4765
2.54k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4766
2.54k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4767
2.54k
        resource_ids.emplace(rs_meta.resource_id());
4768
2.54k
    }
4769
4770
    // get restore job rowset in tablet
4771
258
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
4772
258
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
4773
258
    if (code != MetaServiceCode::OK) {
4774
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
4775
0
                .tag("tablet id", tablet_id)
4776
0
                .tag("msg", msg)
4777
0
                .tag("code", code)
4778
0
                .tag("instance id", instance_id_);
4779
0
        return -1;
4780
0
    }
4781
4782
258
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
4783
0
        if (!rs_meta.has_resource_id()) {
4784
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4785
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4786
0
                    .tag("instance_id", instance_id_)
4787
0
                    .tag("tablet_id", tablet_id);
4788
0
            return -1;
4789
0
        }
4790
4791
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4792
        // possible if the accessor is not initilized correctly
4793
0
        if (it == accessor_map_.end()) [[unlikely]] {
4794
0
            LOG_WARNING(
4795
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4796
0
                    "recycle process")
4797
0
                    .tag("tablet id", tablet_id)
4798
0
                    .tag("instance_id", instance_id_)
4799
0
                    .tag("resource_id", rs_meta.resource_id())
4800
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4801
0
            return -1;
4802
0
        }
4803
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4804
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
4805
0
                    .tag("instance_id", instance_id_)
4806
0
                    .tag("tablet_id", tablet_id)
4807
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4808
0
            return -1;
4809
0
        }
4810
0
        recycle_restore_job_rowsets_number += 1;
4811
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
4812
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
4813
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
4814
0
        resource_ids.emplace(rs_meta.resource_id());
4815
0
    }
4816
4817
258
    LOG_INFO("recycle tablet start to delete object")
4818
258
            .tag("instance id", instance_id_)
4819
258
            .tag("tablet id", tablet_id)
4820
258
            .tag("recycle tablet resource ids are",
4821
258
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
4822
258
                                 [](std::string rs_id, const auto& it) {
4823
216
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4824
216
                                 }));
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
4822
216
                                 [](std::string rs_id, const auto& it) {
4823
216
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4824
216
                                 }));
4825
4826
258
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
4827
258
            _thread_pool_group.s3_producer_pool,
4828
258
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4829
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
4829
208
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
4830
4831
    // delete all rowset data in this tablet
4832
    // ATTN: there may be data leak if not all accessor initilized successfully
4833
    //       partial data deleted if the tablet is stored cross-storage vault
4834
    //       vault id is not attached to TabletMeta...
4835
258
    for (const auto& resource_id : resource_ids) {
4836
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
4837
217
        concurrent_delete_executor.add(
4838
217
                [&, rs_id = resource_id,
4839
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4840
216
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4841
216
                    if (res != 0) {
4842
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4843
3
                                     << " path=" << accessor_ptr->uri()
4844
3
                                     << " task type=" << metrics_context.operation_type;
4845
3
                        return std::make_pair(-1, rs_id);
4846
3
                    }
4847
213
                    return std::make_pair(0, rs_id);
4848
216
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
4839
216
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4840
216
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4841
216
                    if (res != 0) {
4842
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4843
3
                                     << " path=" << accessor_ptr->uri()
4844
3
                                     << " task type=" << metrics_context.operation_type;
4845
3
                        return std::make_pair(-1, rs_id);
4846
3
                    }
4847
213
                    return std::make_pair(0, rs_id);
4848
216
                });
4849
217
    }
4850
4851
258
    bool finished = true;
4852
258
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
4853
258
    for (auto& r : rets) {
4854
217
        if (r.first != 0) {
4855
3
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
4856
3
            ret = -1;
4857
3
        }
4858
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
4859
217
    }
4860
258
    ret = finished ? ret : -1;
4861
4862
258
    if (ret != 0) { // failed recycle tablet data
4863
3
        LOG_WARNING("ret!=0")
4864
3
                .tag("finished", finished)
4865
3
                .tag("ret", ret)
4866
3
                .tag("instance_id", instance_id_)
4867
3
                .tag("tablet_id", tablet_id);
4868
3
        return ret;
4869
3
    }
4870
4871
255
    tablet_metrics_context_.total_recycled_data_size +=
4872
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4873
255
    tablet_metrics_context_.total_recycled_num += 1;
4874
255
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
4875
255
    segment_metrics_context_.total_recycled_data_size +=
4876
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4877
255
    metrics_context.total_recycled_data_size +=
4878
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4879
255
    tablet_metrics_context_.report();
4880
255
    segment_metrics_context_.report();
4881
255
    metrics_context.report();
4882
4883
255
    txn.reset();
4884
255
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4885
0
        LOG_WARNING("failed to recycle tablet ")
4886
0
                .tag("tablet id", tablet_id)
4887
0
                .tag("instance_id", instance_id_)
4888
0
                .tag("reason", "failed to create txn");
4889
0
        ret = -1;
4890
0
    }
4891
    // delete all rowset kv in this tablet
4892
255
    txn->remove(rs_key0, rs_key1);
4893
255
    txn->remove(recyc_rs_key0, recyc_rs_key1);
4894
255
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
4895
4896
    // remove delete bitmap for MoW table
4897
255
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
4898
255
    txn->remove(pending_key);
4899
255
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
4900
255
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
4901
255
    txn->remove(delete_bitmap_start, delete_bitmap_end);
4902
4903
255
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
4904
255
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
4905
255
    txn->remove(dbm_start_key, dbm_end_key);
4906
255
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
4907
255
              << " end=" << hex(dbm_end_key);
4908
4909
255
    TxnErrorCode err = txn->commit();
4910
255
    if (err != TxnErrorCode::TXN_OK) {
4911
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
4912
0
        ret = -1;
4913
0
    }
4914
4915
255
    if (ret == 0) {
4916
        // All object files under tablet have been deleted
4917
255
        std::lock_guard lock(recycled_tablets_mtx_);
4918
255
        recycled_tablets_.insert(tablet_id);
4919
255
    }
4920
4921
255
    return ret;
4922
258
}
4923
4924
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
4925
14
                                               RecyclerMetricsContext& metrics_context) {
4926
14
    int ret = 0;
4927
14
    auto start_time = steady_clock::now();
4928
4929
14
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4930
4931
    // collect resource ids
4932
11
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4933
11
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4934
11
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4935
11
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4936
4937
11
    int64_t recycle_rowsets_number = 0;
4938
11
    int64_t recycle_segments_number = 0;
4939
11
    int64_t recycle_rowsets_data_size = 0;
4940
11
    int64_t recycle_rowsets_index_size = 0;
4941
11
    int64_t max_rowset_version = 0;
4942
11
    int64_t min_rowset_creation_time = INT64_MAX;
4943
11
    int64_t max_rowset_creation_time = 0;
4944
11
    int64_t min_rowset_expiration_time = INT64_MAX;
4945
11
    int64_t max_rowset_expiration_time = 0;
4946
4947
11
    DORIS_CLOUD_DEFER {
4948
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4949
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4950
11
                .tag("instance_id", instance_id_)
4951
11
                .tag("tablet_id", tablet_id)
4952
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4953
11
                .tag("recycle segments number", recycle_segments_number)
4954
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4955
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4956
11
                .tag("max rowset version", max_rowset_version)
4957
11
                .tag("min rowset creation time", min_rowset_creation_time)
4958
11
                .tag("max rowset creation time", max_rowset_creation_time)
4959
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4960
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4961
11
                .tag("ret", ret);
4962
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4947
11
    DORIS_CLOUD_DEFER {
4948
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4949
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4950
11
                .tag("instance_id", instance_id_)
4951
11
                .tag("tablet_id", tablet_id)
4952
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4953
11
                .tag("recycle segments number", recycle_segments_number)
4954
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4955
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4956
11
                .tag("max rowset version", max_rowset_version)
4957
11
                .tag("min rowset creation time", min_rowset_creation_time)
4958
11
                .tag("max rowset creation time", max_rowset_creation_time)
4959
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4960
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4961
11
                .tag("ret", ret);
4962
11
    };
4963
4964
11
    std::unique_ptr<Transaction> txn;
4965
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4966
0
        LOG_WARNING("failed to recycle tablet ")
4967
0
                .tag("tablet id", tablet_id)
4968
0
                .tag("instance_id", instance_id_)
4969
0
                .tag("reason", "failed to create txn");
4970
0
        ret = -1;
4971
0
    }
4972
4973
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
4974
    // by the related operation logs.
4975
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
4976
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
4977
11
    MetaReader meta_reader(instance_id_);
4978
11
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
4979
11
    if (err == TxnErrorCode::TXN_OK) {
4980
11
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
4981
11
    }
4982
11
    if (err != TxnErrorCode::TXN_OK) {
4983
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4984
0
                .tag("tablet id", tablet_id)
4985
0
                .tag("err", err)
4986
0
                .tag("instance id", instance_id_);
4987
0
        ret = -1;
4988
0
    }
4989
4990
11
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
4991
11
             load_rowset_metas.size(), compact_rowset_metas.size())
4992
11
            .tag("instance_id", instance_id_)
4993
11
            .tag("tablet_id", tablet_id);
4994
4995
11
    SyncExecutor<int> concurrent_delete_executor(
4996
11
            _thread_pool_group.s3_producer_pool,
4997
11
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4998
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
4999
5000
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5001
60
        recycle_rowsets_number += 1;
5002
60
        recycle_segments_number += rs_meta.num_segments();
5003
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5004
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5005
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5006
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5007
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5008
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5009
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5010
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
5000
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5001
60
        recycle_rowsets_number += 1;
5002
60
        recycle_segments_number += rs_meta.num_segments();
5003
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5004
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5005
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5006
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5007
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5008
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5009
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5010
60
    };
5011
5012
11
    std::vector<RowsetDeleteTask> all_tasks;
5013
60
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
5014
60
        update_rowset_stats(rs_meta);
5015
        // Version 0-1 rowset has no resource_id and no actual data files,
5016
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5017
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5018
60
        RowsetDeleteTask task;
5019
60
        task.rowset_meta = rs_meta;
5020
60
        task.versioned_rowset_key =
5021
60
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
5022
60
        task.non_versioned_rowset_key =
5023
60
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5024
60
        task.versionstamp = versionstamp;
5025
60
        all_tasks.push_back(std::move(task));
5026
60
    }
5027
5028
11
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
5029
0
        update_rowset_stats(rs_meta);
5030
        // Version 0-1 rowset has no resource_id and no actual data files,
5031
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5032
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5033
0
        RowsetDeleteTask task;
5034
0
        task.rowset_meta = rs_meta;
5035
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
5036
0
                {instance_id_, tablet_id, rs_meta.end_version()});
5037
0
        task.non_versioned_rowset_key =
5038
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5039
0
        task.versionstamp = versionstamp;
5040
0
        all_tasks.push_back(std::move(task));
5041
0
    }
5042
5043
11
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
5044
0
        RecycleRowsetPB recycle_rowset;
5045
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
5046
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5047
0
            return -1;
5048
0
        }
5049
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
5050
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
5051
                // in old version, keep this key-value pair and it needs to be checked manually
5052
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5053
0
                return -1;
5054
0
            }
5055
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
5056
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5057
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5058
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
5059
0
                return -1;
5060
0
            }
5061
            // decode rowset_id
5062
0
            auto k1 = k;
5063
0
            k1.remove_prefix(1);
5064
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5065
0
            decode_key(&k1, &out);
5066
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5067
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5068
0
            LOG_INFO("delete old-version rowset data")
5069
0
                    .tag("instance_id", instance_id_)
5070
0
                    .tag("tablet_id", tablet_id)
5071
0
                    .tag("rowset_id", rowset_id);
5072
5073
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
5074
            // so we must use prefix deletion directly instead of batch delete.
5075
0
            concurrent_delete_executor.add(
5076
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
5077
                        // delete by prefix, the recycle rowset key will be deleted by range later.
5078
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
5079
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
5080
0
        } else {
5081
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
5082
            // Version 0-1 rowset has no resource_id and no actual data files,
5083
            // but still needs ref_count key cleanup, so we add it to all_tasks.
5084
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
5085
0
            RowsetDeleteTask task;
5086
0
            task.rowset_meta = rowset_meta;
5087
0
            task.recycle_rowset_key = k;
5088
0
            all_tasks.push_back(std::move(task));
5089
0
        }
5090
0
        return 0;
5091
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_
5092
5093
11
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
5094
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
5095
0
                .tag("tablet id", tablet_id)
5096
0
                .tag("instance_id", instance_id_)
5097
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
5098
0
        ret = -1;
5099
0
    }
5100
5101
    // Phase 1: Classify tasks by ref_count
5102
11
    std::vector<RowsetDeleteTask> batch_delete_tasks;
5103
60
    for (auto& task : all_tasks) {
5104
60
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
5105
60
        if (classify_ret < 0) {
5106
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
5107
0
                    .tag("instance_id", instance_id_)
5108
0
                    .tag("tablet_id", tablet_id)
5109
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5110
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
5111
0
                return recycle_rowset_meta_and_data(t);
5112
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_4clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_4clEv
5113
0
        }
5114
60
    }
5115
5116
11
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
5117
5118
11
    LOG_INFO("batch delete plan created")
5119
11
            .tag("instance_id", instance_id_)
5120
11
            .tag("tablet_id", tablet_id)
5121
11
            .tag("plan_count", batch_delete_tasks.size());
5122
5123
    // Phase 2: Execute batch delete using existing delete_rowset_data
5124
11
    if (!batch_delete_tasks.empty()) {
5125
10
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
5126
49
        for (const auto& task : batch_delete_tasks) {
5127
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
5128
49
            if (task.rowset_meta.resource_id().empty()) {
5129
10
                LOG_INFO("skip rowset with empty resource_id in batch delete")
5130
10
                        .tag("instance_id", instance_id_)
5131
10
                        .tag("tablet_id", tablet_id)
5132
10
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5133
10
                continue;
5134
10
            }
5135
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
5136
39
        }
5137
5138
        // Only call delete_rowset_data if there are rowsets with actual data to delete
5139
10
        bool delete_success = true;
5140
10
        if (!rowsets_to_delete.empty()) {
5141
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
5142
9
                                                         "batch_delete_versioned_tablet");
5143
9
            int delete_ret = delete_rowset_data(
5144
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
5145
9
            if (delete_ret != 0) {
5146
0
                LOG_WARNING("batch delete execution failed")
5147
0
                        .tag("instance_id", instance_id_)
5148
0
                        .tag("tablet_id", tablet_id);
5149
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
5150
0
                ret = -1;
5151
0
                delete_success = false;
5152
0
            }
5153
9
        }
5154
5155
        // Phase 3: Only cleanup metadata if data deletion succeeded.
5156
        // If deletion failed, keep recycle_rowset_key so next round will retry.
5157
10
        if (delete_success) {
5158
10
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
5159
10
            if (cleanup_ret != 0) {
5160
0
                LOG_WARNING("batch delete cleanup failed")
5161
0
                        .tag("instance_id", instance_id_)
5162
0
                        .tag("tablet_id", tablet_id);
5163
0
                ret = -1;
5164
0
            }
5165
10
        }
5166
10
    }
5167
5168
    // Always wait for fallback tasks to complete before returning
5169
11
    bool finished = true;
5170
11
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
5171
11
    for (int r : rets) {
5172
0
        if (r != 0) {
5173
0
            ret = -1;
5174
0
        }
5175
0
    }
5176
5177
11
    ret = finished ? ret : -1;
5178
5179
11
    if (ret != 0) { // failed recycle tablet data
5180
0
        LOG_WARNING("recycle versioned tablet failed")
5181
0
                .tag("finished", finished)
5182
0
                .tag("ret", ret)
5183
0
                .tag("instance_id", instance_id_)
5184
0
                .tag("tablet_id", tablet_id);
5185
0
        return ret;
5186
0
    }
5187
5188
11
    tablet_metrics_context_.total_recycled_data_size +=
5189
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5190
11
    tablet_metrics_context_.total_recycled_num += 1;
5191
11
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5192
11
    segment_metrics_context_.total_recycled_data_size +=
5193
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5194
11
    metrics_context.total_recycled_data_size +=
5195
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5196
11
    tablet_metrics_context_.report();
5197
11
    segment_metrics_context_.report();
5198
11
    metrics_context.report();
5199
5200
11
    txn.reset();
5201
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5202
0
        LOG_WARNING("failed to recycle tablet ")
5203
0
                .tag("tablet id", tablet_id)
5204
0
                .tag("instance_id", instance_id_)
5205
0
                .tag("reason", "failed to create txn");
5206
0
        ret = -1;
5207
0
    }
5208
    // delete all rowset kv in this tablet
5209
11
    txn->remove(rs_key0, rs_key1);
5210
11
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5211
5212
    // remove delete bitmap for MoW table
5213
11
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5214
11
    txn->remove(pending_key);
5215
11
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5216
11
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5217
11
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5218
5219
11
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5220
11
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5221
11
    txn->remove(dbm_start_key, dbm_end_key);
5222
11
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5223
11
              << " end=" << hex(dbm_end_key);
5224
5225
11
    std::string versioned_idx_key = versioned::tablet_index_key({instance_id_, tablet_id});
5226
11
    std::string tablet_index_val;
5227
11
    err = txn->get(versioned_idx_key, &tablet_index_val);
5228
11
    if (err != TxnErrorCode::TXN_KEY_NOT_FOUND && err != TxnErrorCode::TXN_OK) {
5229
0
        LOG_WARNING("failed to get tablet index kv")
5230
0
                .tag("instance_id", instance_id_)
5231
0
                .tag("tablet_id", tablet_id)
5232
0
                .tag("err", err);
5233
0
        ret = -1;
5234
11
    } else if (err == TxnErrorCode::TXN_OK) {
5235
        // If the tablet index kv exists, we need to delete it
5236
10
        TabletIndexPB tablet_index_pb;
5237
10
        if (!tablet_index_pb.ParseFromString(tablet_index_val)) {
5238
0
            LOG_WARNING("failed to parse tablet index pb")
5239
0
                    .tag("instance_id", instance_id_)
5240
0
                    .tag("tablet_id", tablet_id);
5241
0
            ret = -1;
5242
10
        } else {
5243
10
            std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
5244
10
                    {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
5245
10
                     tablet_index_pb.index_id(), tablet_index_pb.partition_id(), tablet_id});
5246
10
            txn->remove(versioned_inverted_idx_key);
5247
10
            txn->remove(versioned_idx_key);
5248
10
        }
5249
10
    }
5250
5251
11
    err = txn->commit();
5252
11
    if (err != TxnErrorCode::TXN_OK) {
5253
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5254
0
        ret = -1;
5255
0
    }
5256
5257
11
    if (ret == 0) {
5258
        // All object files under tablet have been deleted
5259
11
        std::lock_guard lock(recycled_tablets_mtx_);
5260
11
        recycled_tablets_.insert(tablet_id);
5261
11
    }
5262
5263
11
    return ret;
5264
11
}
5265
5266
68
int InstanceRecycler::recycle_rowsets() {
5267
68
    if (should_recycle_versioned_keys()) {
5268
5
        return recycle_versioned_rowsets();
5269
5
    }
5270
5271
63
    const std::string task_name = "recycle_rowsets";
5272
63
    int64_t num_scanned = 0;
5273
63
    int64_t num_expired = 0;
5274
63
    int64_t num_prepare = 0;
5275
63
    int64_t num_compacted = 0;
5276
63
    int64_t num_empty_rowset = 0;
5277
63
    size_t total_rowset_key_size = 0;
5278
63
    size_t total_rowset_value_size = 0;
5279
63
    size_t expired_rowset_size = 0;
5280
63
    std::atomic_long num_recycled = 0;
5281
63
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5282
5283
63
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5284
63
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5285
63
    std::string recyc_rs_key0;
5286
63
    std::string recyc_rs_key1;
5287
63
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5288
63
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5289
5290
63
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5291
5292
63
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5293
63
    register_recycle_task(task_name, start_time);
5294
5295
63
    DORIS_CLOUD_DEFER {
5296
63
        unregister_recycle_task(task_name);
5297
63
        int64_t cost =
5298
63
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5299
63
        metrics_context.finish_report();
5300
63
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5301
63
                .tag("instance_id", instance_id_)
5302
63
                .tag("num_scanned", num_scanned)
5303
63
                .tag("num_expired", num_expired)
5304
63
                .tag("num_recycled", num_recycled)
5305
63
                .tag("num_recycled.prepare", num_prepare)
5306
63
                .tag("num_recycled.compacted", num_compacted)
5307
63
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5308
63
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5309
63
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5310
63
                .tag("expired_rowset_meta_size", expired_rowset_size);
5311
63
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5295
7
    DORIS_CLOUD_DEFER {
5296
7
        unregister_recycle_task(task_name);
5297
7
        int64_t cost =
5298
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5299
7
        metrics_context.finish_report();
5300
7
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5301
7
                .tag("instance_id", instance_id_)
5302
7
                .tag("num_scanned", num_scanned)
5303
7
                .tag("num_expired", num_expired)
5304
7
                .tag("num_recycled", num_recycled)
5305
7
                .tag("num_recycled.prepare", num_prepare)
5306
7
                .tag("num_recycled.compacted", num_compacted)
5307
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5308
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5309
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5310
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
5311
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5295
56
    DORIS_CLOUD_DEFER {
5296
56
        unregister_recycle_task(task_name);
5297
56
        int64_t cost =
5298
56
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5299
56
        metrics_context.finish_report();
5300
56
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5301
56
                .tag("instance_id", instance_id_)
5302
56
                .tag("num_scanned", num_scanned)
5303
56
                .tag("num_expired", num_expired)
5304
56
                .tag("num_recycled", num_recycled)
5305
56
                .tag("num_recycled.prepare", num_prepare)
5306
56
                .tag("num_recycled.compacted", num_compacted)
5307
56
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5308
56
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5309
56
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5310
56
                .tag("expired_rowset_meta_size", expired_rowset_size);
5311
56
    };
5312
5313
63
    struct RecycleRowsetEntry {
5314
63
        std::string key;
5315
63
        doris::RowsetMetaCloudPB meta;
5316
63
    };
5317
63
    struct RecycleRowsetDeleteJob {
5318
63
        std::vector<std::string> keys;
5319
63
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
5320
63
    };
5321
    // Store the scanned recycle key with rowset meta. The scanned key is the actual KV key to delete.
5322
63
    std::vector<RecycleRowsetEntry> rowsets;
5323
63
    int64_t current_tablet_id = -1;
5324
63
    int64_t recycled_rowset_count_for_current_tablet = 0;
5325
63
    bool current_tablet_skip_logged = false;
5326
63
    std::string next_scan_begin;
5327
63
    const int64_t rowset_batch_size_per_tablet =
5328
63
            std::max(1, config::recycle_rowsets_per_tablet_batch_size);
5329
63
    const int64_t delete_rowset_batch_size =
5330
63
            std::min(500000, config::recycle_rowsets_delete_batch_size);
5331
4.05k
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5332
4.05k
        if (current_tablet_id != tablet_id) {
5333
27
            current_tablet_id = tablet_id;
5334
27
            recycled_rowset_count_for_current_tablet = 0;
5335
27
            current_tablet_skip_logged = false;
5336
27
        }
5337
4.05k
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5338
7
            if (!current_tablet_skip_logged) {
5339
7
                LOG_INFO(
5340
7
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5341
7
                        .tag("instance_id", instance_id_)
5342
7
                        .tag("tablet_id", tablet_id)
5343
7
                        .tag("limit", rowset_batch_size_per_tablet);
5344
7
                current_tablet_skip_logged = true;
5345
7
            }
5346
7
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5347
7
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5348
7
            return false;
5349
7
        }
5350
4.04k
        ++recycled_rowset_count_for_current_tablet;
5351
4.04k
        return true;
5352
4.05k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_8clEl
Line
Count
Source
5331
7
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5332
7
        if (current_tablet_id != tablet_id) {
5333
7
            current_tablet_id = tablet_id;
5334
7
            recycled_rowset_count_for_current_tablet = 0;
5335
7
            current_tablet_skip_logged = false;
5336
7
        }
5337
7
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5338
0
            if (!current_tablet_skip_logged) {
5339
0
                LOG_INFO(
5340
0
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5341
0
                        .tag("instance_id", instance_id_)
5342
0
                        .tag("tablet_id", tablet_id)
5343
0
                        .tag("limit", rowset_batch_size_per_tablet);
5344
0
                current_tablet_skip_logged = true;
5345
0
            }
5346
0
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5347
0
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5348
0
            return false;
5349
0
        }
5350
7
        ++recycled_rowset_count_for_current_tablet;
5351
7
        return true;
5352
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_8clEl
Line
Count
Source
5331
4.04k
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5332
4.04k
        if (current_tablet_id != tablet_id) {
5333
20
            current_tablet_id = tablet_id;
5334
20
            recycled_rowset_count_for_current_tablet = 0;
5335
20
            current_tablet_skip_logged = false;
5336
20
        }
5337
4.04k
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5338
7
            if (!current_tablet_skip_logged) {
5339
7
                LOG_INFO(
5340
7
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5341
7
                        .tag("instance_id", instance_id_)
5342
7
                        .tag("tablet_id", tablet_id)
5343
7
                        .tag("limit", rowset_batch_size_per_tablet);
5344
7
                current_tablet_skip_logged = true;
5345
7
            }
5346
7
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5347
7
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5348
7
            return false;
5349
7
        }
5350
4.04k
        ++recycled_rowset_count_for_current_tablet;
5351
4.04k
        return true;
5352
4.04k
    };
5353
4.05k
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5354
4.05k
        if (next_scan_begin.empty()) {
5355
4.04k
            return false;
5356
4.04k
        }
5357
7
        *begin = std::move(next_scan_begin);
5358
7
        next_scan_begin.clear();
5359
7
        return true;
5360
4.05k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clEPNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5353
7
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5354
7
        if (next_scan_begin.empty()) {
5355
7
            return false;
5356
7
        }
5357
0
        *begin = std::move(next_scan_begin);
5358
0
        next_scan_begin.clear();
5359
0
        return true;
5360
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clEPNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5353
4.04k
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5354
4.04k
        if (next_scan_begin.empty()) {
5355
4.04k
            return false;
5356
4.04k
        }
5357
7
        *begin = std::move(next_scan_begin);
5358
7
        next_scan_begin.clear();
5359
7
        return true;
5360
4.04k
    };
5361
5362
63
    std::vector<std::string> rowset_keys_to_mark_recycled;
5363
63
    std::vector<std::string> rowset_keys_to_abort;
5364
63
    std::vector<std::string> prepare_rowset_keys_to_delete;
5365
5366
    // Store keys of rowset recycled by background workers
5367
63
    std::mutex async_recycled_rowset_keys_mutex;
5368
63
    std::vector<std::string> async_recycled_rowset_keys;
5369
63
    std::vector<std::string> rowset_keys_without_data;
5370
63
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5371
63
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5372
63
    worker_pool->start();
5373
63
    auto mark_abort_worker_pool = std::make_unique<SimpleThreadPool>(
5374
63
            config::instance_recycler_worker_pool_size, "recycle_rs_mark_abort");
5375
63
    mark_abort_worker_pool->start();
5376
    // TODO bacth delete
5377
4.03k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5378
4.03k
        std::string dbm_start_key =
5379
4.03k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5380
4.03k
        std::string dbm_end_key = dbm_start_key;
5381
4.03k
        encode_int64(INT64_MAX, &dbm_end_key);
5382
4.03k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5383
4.03k
        if (ret != 0) {
5384
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5385
0
                         << instance_id_;
5386
0
        }
5387
4.03k
        return ret;
5388
4.03k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_7clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5377
3
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5378
3
        std::string dbm_start_key =
5379
3
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5380
3
        std::string dbm_end_key = dbm_start_key;
5381
3
        encode_int64(INT64_MAX, &dbm_end_key);
5382
3
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5383
3
        if (ret != 0) {
5384
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5385
0
                         << instance_id_;
5386
0
        }
5387
3
        return ret;
5388
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_7clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5377
4.03k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5378
4.03k
        std::string dbm_start_key =
5379
4.03k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5380
4.03k
        std::string dbm_end_key = dbm_start_key;
5381
4.03k
        encode_int64(INT64_MAX, &dbm_end_key);
5382
4.03k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5383
4.03k
        if (ret != 0) {
5384
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5385
0
                         << instance_id_;
5386
0
        }
5387
4.03k
        return ret;
5388
4.03k
    };
5389
63
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5390
903
                                            int64_t tablet_id, const std::string& rowset_id) {
5391
        // Try to delete rowset data in background thread
5392
903
        int ret = worker_pool->submit_with_timeout(
5393
903
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5394
827
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5395
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5396
0
                        return;
5397
0
                    }
5398
827
                    std::vector<std::string> keys;
5399
827
                    {
5400
827
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5401
827
                        async_recycled_rowset_keys.push_back(std::move(key));
5402
827
                        if (async_recycled_rowset_keys.size() > 100) {
5403
5
                            keys.swap(async_recycled_rowset_keys);
5404
5
                        }
5405
827
                    }
5406
827
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5407
827
                    if (keys.empty()) return;
5408
5
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5409
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5410
0
                                     << instance_id_;
5411
5
                    } else {
5412
5
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5413
5
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5414
5
                                           num_recycled, start_time);
5415
5
                    }
5416
5
                },
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
5393
3
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5394
3
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5395
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5396
0
                        return;
5397
0
                    }
5398
3
                    std::vector<std::string> keys;
5399
3
                    {
5400
3
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5401
3
                        async_recycled_rowset_keys.push_back(std::move(key));
5402
3
                        if (async_recycled_rowset_keys.size() > 100) {
5403
0
                            keys.swap(async_recycled_rowset_keys);
5404
0
                        }
5405
3
                    }
5406
3
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5407
3
                    if (keys.empty()) return;
5408
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5409
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5410
0
                                     << instance_id_;
5411
0
                    } else {
5412
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5413
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5414
0
                                           num_recycled, start_time);
5415
0
                    }
5416
0
                },
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
5393
824
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5394
824
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5395
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5396
0
                        return;
5397
0
                    }
5398
824
                    std::vector<std::string> keys;
5399
824
                    {
5400
824
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5401
824
                        async_recycled_rowset_keys.push_back(std::move(key));
5402
824
                        if (async_recycled_rowset_keys.size() > 100) {
5403
5
                            keys.swap(async_recycled_rowset_keys);
5404
5
                        }
5405
824
                    }
5406
824
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5407
824
                    if (keys.empty()) return;
5408
5
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5409
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5410
0
                                     << instance_id_;
5411
5
                    } else {
5412
5
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5413
5
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5414
5
                                           num_recycled, start_time);
5415
5
                    }
5416
5
                },
5417
903
                0);
5418
903
        if (ret == 0) return 0;
5419
        // Submit task failed, delete rowset data in current thread
5420
76
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5421
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5422
0
            return -1;
5423
0
        }
5424
76
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5425
0
            return -1;
5426
0
        }
5427
76
        rowset_keys_without_data.push_back(std::move(key));
5428
76
        return 0;
5429
76
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
5390
3
                                            int64_t tablet_id, const std::string& rowset_id) {
5391
        // Try to delete rowset data in background thread
5392
3
        int ret = worker_pool->submit_with_timeout(
5393
3
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5394
3
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5395
3
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5396
3
                        return;
5397
3
                    }
5398
3
                    std::vector<std::string> keys;
5399
3
                    {
5400
3
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5401
3
                        async_recycled_rowset_keys.push_back(std::move(key));
5402
3
                        if (async_recycled_rowset_keys.size() > 100) {
5403
3
                            keys.swap(async_recycled_rowset_keys);
5404
3
                        }
5405
3
                    }
5406
3
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5407
3
                    if (keys.empty()) return;
5408
3
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5409
3
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5410
3
                                     << instance_id_;
5411
3
                    } else {
5412
3
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5413
3
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5414
3
                                           num_recycled, start_time);
5415
3
                    }
5416
3
                },
5417
3
                0);
5418
3
        if (ret == 0) return 0;
5419
        // Submit task failed, delete rowset data in current thread
5420
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5421
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5422
0
            return -1;
5423
0
        }
5424
0
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5425
0
            return -1;
5426
0
        }
5427
0
        rowset_keys_without_data.push_back(std::move(key));
5428
0
        return 0;
5429
0
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
5390
900
                                            int64_t tablet_id, const std::string& rowset_id) {
5391
        // Try to delete rowset data in background thread
5392
900
        int ret = worker_pool->submit_with_timeout(
5393
900
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5394
900
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5395
900
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5396
900
                        return;
5397
900
                    }
5398
900
                    std::vector<std::string> keys;
5399
900
                    {
5400
900
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5401
900
                        async_recycled_rowset_keys.push_back(std::move(key));
5402
900
                        if (async_recycled_rowset_keys.size() > 100) {
5403
900
                            keys.swap(async_recycled_rowset_keys);
5404
900
                        }
5405
900
                    }
5406
900
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5407
900
                    if (keys.empty()) return;
5408
900
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5409
900
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5410
900
                                     << instance_id_;
5411
900
                    } else {
5412
900
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5413
900
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5414
900
                                           num_recycled, start_time);
5415
900
                    }
5416
900
                },
5417
900
                0);
5418
900
        if (ret == 0) return 0;
5419
        // Submit task failed, delete rowset data in current thread
5420
76
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5421
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5422
0
            return -1;
5423
0
        }
5424
76
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5425
0
            return -1;
5426
0
        }
5427
76
        rowset_keys_without_data.push_back(std::move(key));
5428
76
        return 0;
5429
76
    };
5430
5431
63
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5432
5433
4.05k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5434
4.05k
        ++num_scanned;
5435
4.05k
        total_rowset_key_size += k.size();
5436
4.05k
        total_rowset_value_size += v.size();
5437
4.05k
        RecycleRowsetPB rowset;
5438
4.05k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5439
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5440
0
            return -1;
5441
0
        }
5442
5443
4.05k
        int64_t current_time = ::time(nullptr);
5444
4.05k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5445
5446
4.05k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5447
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5448
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5449
4.05k
        if (current_time < expiration) { // not expired
5450
0
            return 0;
5451
0
        }
5452
4.05k
        ++num_expired;
5453
4.05k
        expired_rowset_size += v.size();
5454
5455
4.05k
        int64_t tablet_id =
5456
4.05k
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5457
4.05k
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5458
7
            return 0;
5459
7
        }
5460
5461
4.04k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5462
252
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5463
                // in old version, keep this key-value pair and it needs to be checked manually
5464
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5465
0
                return -1;
5466
0
            }
5467
252
            if (rowset.resource_id().empty()) [[unlikely]] {
5468
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5469
2
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5470
2
                          << hex(k) << " value=" << proto_to_json(rowset);
5471
2
                rowset_keys_without_data.emplace_back(k);
5472
2
                return 0;
5473
2
            }
5474
            // decode rowset_id
5475
250
            auto k1 = k;
5476
250
            k1.remove_prefix(1);
5477
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5478
250
            decode_key(&k1, &out);
5479
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5480
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5481
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5482
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5483
250
                      << " task_type=" << metrics_context.operation_type;
5484
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5485
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5486
0
                return -1;
5487
0
            }
5488
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5489
250
            metrics_context.total_recycled_num++;
5490
250
            segment_metrics_context_.total_recycled_data_size +=
5491
250
                    rowset.rowset_meta().total_disk_size();
5492
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5493
250
            return 0;
5494
250
        }
5495
5496
3.79k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5497
3.79k
        if (config::enable_mark_delete_rowset_before_recycle) {
5498
6
            if (need_mark_rowset_as_recycled(rowset)) {
5499
4
                rowset_keys_to_mark_recycled.emplace_back(k);
5500
4
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5501
4
                             "at next turn, instance_id="
5502
4
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5503
4
                          << " version=[" << rowset_meta->start_version() << '-'
5504
4
                          << rowset_meta->end_version() << "]";
5505
4
                return 0;
5506
4
            }
5507
6
        }
5508
5509
3.79k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5510
3.79k
            rowset_meta->end_version() != 1) {
5511
2
            if (make_deferred_abort_task(rowset).has_value()) {
5512
2
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5513
2
                             "instance_id="
5514
2
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5515
2
                          << " version=[" << rowset_meta->start_version() << '-'
5516
2
                          << rowset_meta->end_version() << "]";
5517
2
                rowset_keys_to_abort.emplace_back(k);
5518
2
            }
5519
2
        }
5520
5521
        // TODO(plat1ko): check rowset not referenced
5522
3.79k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5523
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5524
0
                LOG_INFO("recycle rowset that has empty resource id");
5525
0
            } else {
5526
                // other situations, keep this key-value pair and it needs to be checked manually
5527
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5528
0
                return -1;
5529
0
            }
5530
0
        }
5531
3.79k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5532
3.79k
                  << " tablet_id=" << rowset_meta->tablet_id()
5533
3.79k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5534
3.79k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5535
3.79k
                  << "] txn_id=" << rowset_meta->txn_id()
5536
3.79k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5537
3.79k
                  << " rowset_meta_size=" << v.size()
5538
3.79k
                  << " creation_time=" << rowset_meta->creation_time()
5539
3.79k
                  << " task_type=" << metrics_context.operation_type;
5540
3.79k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5541
            // unable to calculate file path, can only be deleted by rowset id prefix
5542
653
            num_prepare += 1;
5543
653
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5544
653
                                             rowset_meta->tablet_id(),
5545
653
                                             rowset_meta->rowset_id_v2()) != 0) {
5546
0
                return -1;
5547
0
            }
5548
3.13k
        } else {
5549
3.13k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5550
3.13k
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
5551
3.13k
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
5552
3.13k
            } else {
5553
3
                ++num_empty_rowset;
5554
3
                rowset_keys_without_data.emplace_back(k);
5555
3
            }
5556
3.13k
        }
5557
3.79k
        return 0;
5558
3.79k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5433
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5434
7
        ++num_scanned;
5435
7
        total_rowset_key_size += k.size();
5436
7
        total_rowset_value_size += v.size();
5437
7
        RecycleRowsetPB rowset;
5438
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5439
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5440
0
            return -1;
5441
0
        }
5442
5443
7
        int64_t current_time = ::time(nullptr);
5444
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5445
5446
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5447
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5448
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5449
7
        if (current_time < expiration) { // not expired
5450
0
            return 0;
5451
0
        }
5452
7
        ++num_expired;
5453
7
        expired_rowset_size += v.size();
5454
5455
7
        int64_t tablet_id =
5456
7
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5457
7
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5458
0
            return 0;
5459
0
        }
5460
5461
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5462
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5463
                // in old version, keep this key-value pair and it needs to be checked manually
5464
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5465
0
                return -1;
5466
0
            }
5467
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5468
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5469
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5470
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5471
0
                rowset_keys_without_data.emplace_back(k);
5472
0
                return 0;
5473
0
            }
5474
            // decode rowset_id
5475
0
            auto k1 = k;
5476
0
            k1.remove_prefix(1);
5477
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5478
0
            decode_key(&k1, &out);
5479
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5480
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5481
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5482
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5483
0
                      << " task_type=" << metrics_context.operation_type;
5484
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5485
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5486
0
                return -1;
5487
0
            }
5488
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5489
0
            metrics_context.total_recycled_num++;
5490
0
            segment_metrics_context_.total_recycled_data_size +=
5491
0
                    rowset.rowset_meta().total_disk_size();
5492
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5493
0
            return 0;
5494
0
        }
5495
5496
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
5497
7
        if (config::enable_mark_delete_rowset_before_recycle) {
5498
6
            if (need_mark_rowset_as_recycled(rowset)) {
5499
4
                rowset_keys_to_mark_recycled.emplace_back(k);
5500
4
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5501
4
                             "at next turn, instance_id="
5502
4
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5503
4
                          << " version=[" << rowset_meta->start_version() << '-'
5504
4
                          << rowset_meta->end_version() << "]";
5505
4
                return 0;
5506
4
            }
5507
6
        }
5508
5509
3
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5510
3
            rowset_meta->end_version() != 1) {
5511
2
            if (make_deferred_abort_task(rowset).has_value()) {
5512
2
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5513
2
                             "instance_id="
5514
2
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5515
2
                          << " version=[" << rowset_meta->start_version() << '-'
5516
2
                          << rowset_meta->end_version() << "]";
5517
2
                rowset_keys_to_abort.emplace_back(k);
5518
2
            }
5519
2
        }
5520
5521
        // TODO(plat1ko): check rowset not referenced
5522
3
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5523
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5524
0
                LOG_INFO("recycle rowset that has empty resource id");
5525
0
            } else {
5526
                // other situations, keep this key-value pair and it needs to be checked manually
5527
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5528
0
                return -1;
5529
0
            }
5530
0
        }
5531
3
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5532
3
                  << " tablet_id=" << rowset_meta->tablet_id()
5533
3
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5534
3
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5535
3
                  << "] txn_id=" << rowset_meta->txn_id()
5536
3
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5537
3
                  << " rowset_meta_size=" << v.size()
5538
3
                  << " creation_time=" << rowset_meta->creation_time()
5539
3
                  << " task_type=" << metrics_context.operation_type;
5540
3
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5541
            // unable to calculate file path, can only be deleted by rowset id prefix
5542
3
            num_prepare += 1;
5543
3
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5544
3
                                             rowset_meta->tablet_id(),
5545
3
                                             rowset_meta->rowset_id_v2()) != 0) {
5546
0
                return -1;
5547
0
            }
5548
3
        } else {
5549
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5550
0
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
5551
0
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
5552
0
            } else {
5553
0
                ++num_empty_rowset;
5554
0
                rowset_keys_without_data.emplace_back(k);
5555
0
            }
5556
0
        }
5557
3
        return 0;
5558
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5433
4.04k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5434
4.04k
        ++num_scanned;
5435
4.04k
        total_rowset_key_size += k.size();
5436
4.04k
        total_rowset_value_size += v.size();
5437
4.04k
        RecycleRowsetPB rowset;
5438
4.04k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5439
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5440
0
            return -1;
5441
0
        }
5442
5443
4.04k
        int64_t current_time = ::time(nullptr);
5444
4.04k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5445
5446
4.04k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5447
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5448
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5449
4.04k
        if (current_time < expiration) { // not expired
5450
0
            return 0;
5451
0
        }
5452
4.04k
        ++num_expired;
5453
4.04k
        expired_rowset_size += v.size();
5454
5455
4.04k
        int64_t tablet_id =
5456
4.04k
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5457
4.04k
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5458
7
            return 0;
5459
7
        }
5460
5461
4.04k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5462
252
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5463
                // in old version, keep this key-value pair and it needs to be checked manually
5464
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5465
0
                return -1;
5466
0
            }
5467
252
            if (rowset.resource_id().empty()) [[unlikely]] {
5468
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5469
2
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5470
2
                          << hex(k) << " value=" << proto_to_json(rowset);
5471
2
                rowset_keys_without_data.emplace_back(k);
5472
2
                return 0;
5473
2
            }
5474
            // decode rowset_id
5475
250
            auto k1 = k;
5476
250
            k1.remove_prefix(1);
5477
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5478
250
            decode_key(&k1, &out);
5479
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5480
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5481
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5482
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5483
250
                      << " task_type=" << metrics_context.operation_type;
5484
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5485
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5486
0
                return -1;
5487
0
            }
5488
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5489
250
            metrics_context.total_recycled_num++;
5490
250
            segment_metrics_context_.total_recycled_data_size +=
5491
250
                    rowset.rowset_meta().total_disk_size();
5492
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5493
250
            return 0;
5494
250
        }
5495
5496
3.78k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5497
3.78k
        if (config::enable_mark_delete_rowset_before_recycle) {
5498
0
            if (need_mark_rowset_as_recycled(rowset)) {
5499
0
                rowset_keys_to_mark_recycled.emplace_back(k);
5500
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5501
0
                             "at next turn, instance_id="
5502
0
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5503
0
                          << " version=[" << rowset_meta->start_version() << '-'
5504
0
                          << rowset_meta->end_version() << "]";
5505
0
                return 0;
5506
0
            }
5507
0
        }
5508
5509
3.78k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5510
3.78k
            rowset_meta->end_version() != 1) {
5511
0
            if (make_deferred_abort_task(rowset).has_value()) {
5512
0
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5513
0
                             "instance_id="
5514
0
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5515
0
                          << " version=[" << rowset_meta->start_version() << '-'
5516
0
                          << rowset_meta->end_version() << "]";
5517
0
                rowset_keys_to_abort.emplace_back(k);
5518
0
            }
5519
0
        }
5520
5521
        // TODO(plat1ko): check rowset not referenced
5522
3.78k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5523
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5524
0
                LOG_INFO("recycle rowset that has empty resource id");
5525
0
            } else {
5526
                // other situations, keep this key-value pair and it needs to be checked manually
5527
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5528
0
                return -1;
5529
0
            }
5530
0
        }
5531
3.78k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5532
3.78k
                  << " tablet_id=" << rowset_meta->tablet_id()
5533
3.78k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5534
3.78k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5535
3.78k
                  << "] txn_id=" << rowset_meta->txn_id()
5536
3.78k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5537
3.78k
                  << " rowset_meta_size=" << v.size()
5538
3.78k
                  << " creation_time=" << rowset_meta->creation_time()
5539
3.78k
                  << " task_type=" << metrics_context.operation_type;
5540
3.78k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5541
            // unable to calculate file path, can only be deleted by rowset id prefix
5542
650
            num_prepare += 1;
5543
650
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5544
650
                                             rowset_meta->tablet_id(),
5545
650
                                             rowset_meta->rowset_id_v2()) != 0) {
5546
0
                return -1;
5547
0
            }
5548
3.13k
        } else {
5549
3.13k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5550
3.13k
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
5551
3.13k
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
5552
3.13k
            } else {
5553
3
                ++num_empty_rowset;
5554
3
                rowset_keys_without_data.emplace_back(k);
5555
3
            }
5556
3.13k
        }
5557
3.78k
        return 0;
5558
3.78k
    };
5559
5560
63
    auto submit_delete_rowset_data_job = [&](std::vector<std::string> rowset_keys,
5561
63
                                             std::map<std::string, RowsetMetaCloudPB> rowsets) {
5562
22
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys),
5563
22
                             rowsets_to_delete = std::move(rowsets)]() {
5564
22
            if (!rowsets_to_delete.empty() &&
5565
22
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5566
17
                                   metrics_context) != 0) {
5567
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5568
0
                return;
5569
0
            }
5570
3.13k
            for (const auto& [_, rs] : rowsets_to_delete) {
5571
3.13k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5572
0
                    return;
5573
0
                }
5574
3.13k
            }
5575
22
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5576
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5577
0
                return;
5578
0
            }
5579
5580
22
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5581
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
5563
22
                             rowsets_to_delete = std::move(rowsets)]() {
5564
22
            if (!rowsets_to_delete.empty() &&
5565
22
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5566
17
                                   metrics_context) != 0) {
5567
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5568
0
                return;
5569
0
            }
5570
3.13k
            for (const auto& [_, rs] : rowsets_to_delete) {
5571
3.13k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5572
0
                    return;
5573
0
                }
5574
3.13k
            }
5575
22
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5576
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5577
0
                return;
5578
0
            }
5579
5580
22
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5581
22
        });
5582
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
5561
22
                                             std::map<std::string, RowsetMetaCloudPB> rowsets) {
5562
22
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys),
5563
22
                             rowsets_to_delete = std::move(rowsets)]() {
5564
22
            if (!rowsets_to_delete.empty() &&
5565
22
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5566
22
                                   metrics_context) != 0) {
5567
22
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5568
22
                return;
5569
22
            }
5570
22
            for (const auto& [_, rs] : rowsets_to_delete) {
5571
22
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5572
22
                    return;
5573
22
                }
5574
22
            }
5575
22
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5576
22
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5577
22
                return;
5578
22
            }
5579
5580
22
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5581
22
        });
5582
22
    };
5583
5584
63
    auto submit_mark_abort_rowset_job = [&](std::vector<std::string> rowset_keys_to_mark,
5585
105
                                            std::vector<std::string> rowset_keys_to_abort) {
5586
105
        if (rowset_keys_to_mark.empty() && rowset_keys_to_abort.empty()) {
5587
99
            return;
5588
99
        }
5589
6
        mark_abort_worker_pool->submit([&, rowset_keys_to_mark = std::move(rowset_keys_to_mark),
5590
6
                                        rowset_keys_to_abort =
5591
6
                                                std::move(rowset_keys_to_abort)]() mutable {
5592
6
            auto start = steady_clock::now();
5593
6
            DORIS_CLOUD_DEFER {
5594
6
                auto cost = duration_cast<milliseconds>(steady_clock::now() - start).count();
5595
6
                LOG(INFO) << "finish mark and abort rowset job, instance_id=" << instance_id_ << ' '
5596
6
                          << "cost_ms=" << cost << ' '
5597
6
                          << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size() << ' '
5598
6
                          << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5599
6
            };
recycler.cpp:_ZZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_ENUlvE_clEvENKUlvE_clEv
Line
Count
Source
5593
6
            DORIS_CLOUD_DEFER {
5594
6
                auto cost = duration_cast<milliseconds>(steady_clock::now() - start).count();
5595
6
                LOG(INFO) << "finish mark and abort rowset job, instance_id=" << instance_id_ << ' '
5596
6
                          << "cost_ms=" << cost << ' '
5597
6
                          << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size() << ' '
5598
6
                          << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5599
6
            };
Unexecuted instantiation: recycler_test.cpp:_ZZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_ENUlvE_clEvENKUlvE_clEv
5600
6
            if (!rowset_keys_to_mark.empty() &&
5601
6
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5602
4
                                                                rowset_keys_to_mark) != 0) {
5603
0
                LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id="
5604
0
                             << instance_id_ << ' '
5605
0
                             << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size();
5606
0
                return;
5607
0
            }
5608
6
            if (!rowset_keys_to_abort.empty() &&
5609
6
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort, true) !=
5610
2
                        0) {
5611
0
                LOG(WARNING) << "failed to batch abort txn or job for related rowset, "
5612
0
                                "instance_id="
5613
0
                             << instance_id_ << ' '
5614
0
                             << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5615
0
                return;
5616
0
            }
5617
6
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_ENUlvE_clEv
Line
Count
Source
5591
6
                                                std::move(rowset_keys_to_abort)]() mutable {
5592
6
            auto start = steady_clock::now();
5593
6
            DORIS_CLOUD_DEFER {
5594
6
                auto cost = duration_cast<milliseconds>(steady_clock::now() - start).count();
5595
6
                LOG(INFO) << "finish mark and abort rowset job, instance_id=" << instance_id_ << ' '
5596
6
                          << "cost_ms=" << cost << ' '
5597
6
                          << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size() << ' '
5598
6
                          << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5599
6
            };
5600
6
            if (!rowset_keys_to_mark.empty() &&
5601
6
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5602
4
                                                                rowset_keys_to_mark) != 0) {
5603
0
                LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id="
5604
0
                             << instance_id_ << ' '
5605
0
                             << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size();
5606
0
                return;
5607
0
            }
5608
6
            if (!rowset_keys_to_abort.empty() &&
5609
6
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort, true) !=
5610
2
                        0) {
5611
0
                LOG(WARNING) << "failed to batch abort txn or job for related rowset, "
5612
0
                                "instance_id="
5613
0
                             << instance_id_ << ' '
5614
0
                             << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5615
0
                return;
5616
0
            }
5617
6
        });
Unexecuted instantiation: recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_ENUlvE_clEv
5618
6
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_
Line
Count
Source
5585
14
                                            std::vector<std::string> rowset_keys_to_abort) {
5586
14
        if (rowset_keys_to_mark.empty() && rowset_keys_to_abort.empty()) {
5587
8
            return;
5588
8
        }
5589
6
        mark_abort_worker_pool->submit([&, rowset_keys_to_mark = std::move(rowset_keys_to_mark),
5590
6
                                        rowset_keys_to_abort =
5591
6
                                                std::move(rowset_keys_to_abort)]() mutable {
5592
6
            auto start = steady_clock::now();
5593
6
            DORIS_CLOUD_DEFER {
5594
6
                auto cost = duration_cast<milliseconds>(steady_clock::now() - start).count();
5595
6
                LOG(INFO) << "finish mark and abort rowset job, instance_id=" << instance_id_ << ' '
5596
6
                          << "cost_ms=" << cost << ' '
5597
6
                          << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size() << ' '
5598
6
                          << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5599
6
            };
5600
6
            if (!rowset_keys_to_mark.empty() &&
5601
6
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5602
6
                                                                rowset_keys_to_mark) != 0) {
5603
6
                LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id="
5604
6
                             << instance_id_ << ' '
5605
6
                             << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size();
5606
6
                return;
5607
6
            }
5608
6
            if (!rowset_keys_to_abort.empty() &&
5609
6
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort, true) !=
5610
6
                        0) {
5611
6
                LOG(WARNING) << "failed to batch abort txn or job for related rowset, "
5612
6
                                "instance_id="
5613
6
                             << instance_id_ << ' '
5614
6
                             << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5615
6
                return;
5616
6
            }
5617
6
        });
5618
6
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_
Line
Count
Source
5585
91
                                            std::vector<std::string> rowset_keys_to_abort) {
5586
91
        if (rowset_keys_to_mark.empty() && rowset_keys_to_abort.empty()) {
5587
91
            return;
5588
91
        }
5589
0
        mark_abort_worker_pool->submit([&, rowset_keys_to_mark = std::move(rowset_keys_to_mark),
5590
0
                                        rowset_keys_to_abort =
5591
0
                                                std::move(rowset_keys_to_abort)]() mutable {
5592
0
            auto start = steady_clock::now();
5593
0
            DORIS_CLOUD_DEFER {
5594
0
                auto cost = duration_cast<milliseconds>(steady_clock::now() - start).count();
5595
0
                LOG(INFO) << "finish mark and abort rowset job, instance_id=" << instance_id_ << ' '
5596
0
                          << "cost_ms=" << cost << ' '
5597
0
                          << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size() << ' '
5598
0
                          << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5599
0
            };
5600
0
            if (!rowset_keys_to_mark.empty() &&
5601
0
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5602
0
                                                                rowset_keys_to_mark) != 0) {
5603
0
                LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id="
5604
0
                             << instance_id_ << ' '
5605
0
                             << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size();
5606
0
                return;
5607
0
            }
5608
0
            if (!rowset_keys_to_abort.empty() &&
5609
0
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort, true) !=
5610
0
                        0) {
5611
0
                LOG(WARNING) << "failed to batch abort txn or job for related rowset, "
5612
0
                                "instance_id="
5613
0
                             << instance_id_ << ' '
5614
0
                             << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5615
0
                return;
5616
0
            }
5617
0
        });
5618
0
    };
5619
5620
63
    bool scan_finished = false;
5621
105
    auto loop_done = [&]() -> int {
5622
105
        std::vector<std::string> mark_keys_to_process;
5623
105
        std::vector<std::string> abort_keys_to_process;
5624
105
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5625
105
        abort_keys_to_process.swap(rowset_keys_to_abort);
5626
105
        submit_mark_abort_rowset_job(std::move(mark_keys_to_process),
5627
105
                                     std::move(abort_keys_to_process));
5628
105
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
5629
42
            return 0;
5630
42
        }
5631
5632
63
        DORIS_CLOUD_DEFER {
5633
            // if return -1 in loop done, rowset info in memory is not cleared,
5634
            // it can lead to memory accumulation
5635
63
            rowset_keys_without_data.clear();
5636
63
            rowsets.clear();
5637
63
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
5632
7
        DORIS_CLOUD_DEFER {
5633
            // if return -1 in loop done, rowset info in memory is not cleared,
5634
            // it can lead to memory accumulation
5635
7
            rowset_keys_without_data.clear();
5636
7
            rowsets.clear();
5637
7
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
5632
56
        DORIS_CLOUD_DEFER {
5633
            // if return -1 in loop done, rowset info in memory is not cleared,
5634
            // it can lead to memory accumulation
5635
56
            rowset_keys_without_data.clear();
5636
56
            rowsets.clear();
5637
56
        };
5638
63
        std::random_device rd;
5639
63
        std::mt19937 g(rd());
5640
63
        std::ranges::shuffle(rowsets, g);
5641
5642
63
        std::vector<std::string> rowset_keys_to_delete;
5643
63
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
5644
        // rowset_id -> rowset_meta
5645
        // store rowset id and meta for statistics rs size when delete
5646
63
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5647
5648
63
        size_t rowsets_per_batch_size = 0;
5649
3.13k
        for (auto& rowset : rowsets) {
5650
3.13k
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
5651
3.13k
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
5652
3.13k
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
5653
3.12k
                continue;
5654
3.12k
            }
5655
5656
8
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5657
8
                                          std::move(rowsets_to_delete));
5658
8
            rowsets_per_batch_size = 0;
5659
8
            rowset_keys_to_delete.clear();
5660
8
            rowsets_to_delete.clear();
5661
8
        }
5662
5663
63
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
5664
9
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5665
9
                                          std::move(rowsets_to_delete));
5666
9
        }
5667
5668
68
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
5669
5
            auto begin = rowset_keys_without_data.begin() + i;
5670
5
            auto end = rowset_keys_without_data.begin() +
5671
5
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
5672
5
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
5673
5
                                                           std::make_move_iterator(end));
5674
5
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
5675
5
        }
5676
5677
63
        return 0;
5678
105
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5621
14
    auto loop_done = [&]() -> int {
5622
14
        std::vector<std::string> mark_keys_to_process;
5623
14
        std::vector<std::string> abort_keys_to_process;
5624
14
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5625
14
        abort_keys_to_process.swap(rowset_keys_to_abort);
5626
14
        submit_mark_abort_rowset_job(std::move(mark_keys_to_process),
5627
14
                                     std::move(abort_keys_to_process));
5628
14
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
5629
7
            return 0;
5630
7
        }
5631
5632
7
        DORIS_CLOUD_DEFER {
5633
            // if return -1 in loop done, rowset info in memory is not cleared,
5634
            // it can lead to memory accumulation
5635
7
            rowset_keys_without_data.clear();
5636
7
            rowsets.clear();
5637
7
        };
5638
7
        std::random_device rd;
5639
7
        std::mt19937 g(rd());
5640
7
        std::ranges::shuffle(rowsets, g);
5641
5642
7
        std::vector<std::string> rowset_keys_to_delete;
5643
7
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
5644
        // rowset_id -> rowset_meta
5645
        // store rowset id and meta for statistics rs size when delete
5646
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5647
5648
7
        size_t rowsets_per_batch_size = 0;
5649
7
        for (auto& rowset : rowsets) {
5650
0
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
5651
0
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
5652
0
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
5653
0
                continue;
5654
0
            }
5655
5656
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5657
0
                                          std::move(rowsets_to_delete));
5658
0
            rowsets_per_batch_size = 0;
5659
0
            rowset_keys_to_delete.clear();
5660
0
            rowsets_to_delete.clear();
5661
0
        }
5662
5663
7
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
5664
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5665
0
                                          std::move(rowsets_to_delete));
5666
0
        }
5667
5668
7
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
5669
0
            auto begin = rowset_keys_without_data.begin() + i;
5670
0
            auto end = rowset_keys_without_data.begin() +
5671
0
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
5672
0
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
5673
0
                                                           std::make_move_iterator(end));
5674
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
5675
0
        }
5676
5677
7
        return 0;
5678
14
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5621
91
    auto loop_done = [&]() -> int {
5622
91
        std::vector<std::string> mark_keys_to_process;
5623
91
        std::vector<std::string> abort_keys_to_process;
5624
91
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5625
91
        abort_keys_to_process.swap(rowset_keys_to_abort);
5626
91
        submit_mark_abort_rowset_job(std::move(mark_keys_to_process),
5627
91
                                     std::move(abort_keys_to_process));
5628
91
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
5629
35
            return 0;
5630
35
        }
5631
5632
56
        DORIS_CLOUD_DEFER {
5633
            // if return -1 in loop done, rowset info in memory is not cleared,
5634
            // it can lead to memory accumulation
5635
56
            rowset_keys_without_data.clear();
5636
56
            rowsets.clear();
5637
56
        };
5638
56
        std::random_device rd;
5639
56
        std::mt19937 g(rd());
5640
56
        std::ranges::shuffle(rowsets, g);
5641
5642
56
        std::vector<std::string> rowset_keys_to_delete;
5643
56
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
5644
        // rowset_id -> rowset_meta
5645
        // store rowset id and meta for statistics rs size when delete
5646
56
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5647
5648
56
        size_t rowsets_per_batch_size = 0;
5649
3.13k
        for (auto& rowset : rowsets) {
5650
3.13k
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
5651
3.13k
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
5652
3.13k
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
5653
3.12k
                continue;
5654
3.12k
            }
5655
5656
8
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5657
8
                                          std::move(rowsets_to_delete));
5658
8
            rowsets_per_batch_size = 0;
5659
8
            rowset_keys_to_delete.clear();
5660
8
            rowsets_to_delete.clear();
5661
8
        }
5662
5663
56
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
5664
9
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5665
9
                                          std::move(rowsets_to_delete));
5666
9
        }
5667
5668
61
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
5669
5
            auto begin = rowset_keys_without_data.begin() + i;
5670
5
            auto end = rowset_keys_without_data.begin() +
5671
5
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
5672
5
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
5673
5
                                                           std::make_move_iterator(end));
5674
5
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
5675
5
        }
5676
5677
56
        return 0;
5678
91
    };
5679
5680
63
    if (config::enable_recycler_stats_metrics) {
5681
0
        scan_and_statistics_rowsets();
5682
0
    }
5683
    // recycle_func and loop_done for scan and recycle
5684
63
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv), loop_done,
5685
63
                               std::move(next_scan_begin_getter));
5686
63
    scan_finished = true;
5687
    // if the size of rowsets is always less than delete_rowset_batch_size
5688
    // it need to submit the task directly
5689
    // else if the size of rowsets is greater than delete_rowset_batch_size,
5690
    // but there are residual, whether due to failed or unsuccessful cleanup, this behavior is idempotent
5691
63
    if (loop_done() != 0) {
5692
0
        ret = -1;
5693
0
    }
5694
5695
63
    mark_abort_worker_pool->stop();
5696
63
    worker_pool->stop();
5697
5698
63
    if (!async_recycled_rowset_keys.empty()) {
5699
7
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5700
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5701
0
            return -1;
5702
7
        } else {
5703
7
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5704
7
        }
5705
7
    }
5706
5707
    // Report final metrics after all concurrent tasks completed
5708
63
    segment_metrics_context_.report();
5709
63
    metrics_context.report();
5710
5711
63
    return ret;
5712
63
}
5713
5714
int InstanceRecycler::next_recycle_rowset_tablet_key(const std::string& instance_id,
5715
1
                                                     int64_t tablet_id, std::string* next_key) {
5716
1
    DCHECK(next_key != nullptr);
5717
1
    if (tablet_id == std::numeric_limits<int64_t>::max()) {
5718
0
        return -1;
5719
0
    }
5720
1
    *next_key = recycle_rowset_key({instance_id, tablet_id + 1, ""});
5721
1
    return 0;
5722
1
}
5723
5724
13
int InstanceRecycler::recycle_restore_jobs() {
5725
13
    const std::string task_name = "recycle_restore_jobs";
5726
13
    int64_t num_scanned = 0;
5727
13
    int64_t num_expired = 0;
5728
13
    int64_t num_recycled = 0;
5729
13
    int64_t num_aborted = 0;
5730
5731
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5732
5733
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
5734
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
5735
13
    std::string restore_job_key0;
5736
13
    std::string restore_job_key1;
5737
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
5738
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
5739
5740
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
5741
5742
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5743
13
    register_recycle_task(task_name, start_time);
5744
5745
13
    DORIS_CLOUD_DEFER {
5746
13
        unregister_recycle_task(task_name);
5747
13
        int64_t cost =
5748
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5749
13
        metrics_context.finish_report();
5750
5751
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5752
13
                .tag("instance_id", instance_id_)
5753
13
                .tag("num_scanned", num_scanned)
5754
13
                .tag("num_expired", num_expired)
5755
13
                .tag("num_recycled", num_recycled)
5756
13
                .tag("num_aborted", num_aborted);
5757
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
5745
13
    DORIS_CLOUD_DEFER {
5746
13
        unregister_recycle_task(task_name);
5747
13
        int64_t cost =
5748
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5749
13
        metrics_context.finish_report();
5750
5751
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5752
13
                .tag("instance_id", instance_id_)
5753
13
                .tag("num_scanned", num_scanned)
5754
13
                .tag("num_expired", num_expired)
5755
13
                .tag("num_recycled", num_recycled)
5756
13
                .tag("num_aborted", num_aborted);
5757
13
    };
5758
5759
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5760
5761
13
    std::vector<std::string_view> restore_job_keys;
5762
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5763
41
        ++num_scanned;
5764
41
        RestoreJobCloudPB restore_job_pb;
5765
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5766
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5767
0
            return -1;
5768
0
        }
5769
41
        int64_t expiration =
5770
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5771
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5772
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5773
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5774
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5775
0
                   << " state=" << restore_job_pb.state();
5776
41
        int64_t current_time = ::time(nullptr);
5777
41
        if (current_time < expiration) { // not expired
5778
0
            return 0;
5779
0
        }
5780
41
        ++num_expired;
5781
5782
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5783
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5784
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5785
5786
41
        std::unique_ptr<Transaction> txn;
5787
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5788
41
        if (err != TxnErrorCode::TXN_OK) {
5789
0
            LOG_WARNING("failed to recycle restore job")
5790
0
                    .tag("err", err)
5791
0
                    .tag("tablet id", tablet_id)
5792
0
                    .tag("instance_id", instance_id_)
5793
0
                    .tag("reason", "failed to create txn");
5794
0
            return -1;
5795
0
        }
5796
5797
41
        std::string val;
5798
41
        err = txn->get(k, &val);
5799
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5800
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5801
0
            return 0;
5802
0
        }
5803
41
        if (err != TxnErrorCode::TXN_OK) {
5804
0
            LOG_WARNING("failed to get kv");
5805
0
            return -1;
5806
0
        }
5807
41
        restore_job_pb.Clear();
5808
41
        if (!restore_job_pb.ParseFromString(val)) {
5809
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5810
0
            return -1;
5811
0
        }
5812
5813
        // PREPARED or COMMITTED, change state to DROPPED and return
5814
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5815
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5816
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5817
0
            restore_job_pb.set_need_recycle_data(true);
5818
0
            txn->put(k, restore_job_pb.SerializeAsString());
5819
0
            err = txn->commit();
5820
0
            if (err != TxnErrorCode::TXN_OK) {
5821
0
                LOG_WARNING("failed to commit txn: {}", err);
5822
0
                return -1;
5823
0
            }
5824
0
            num_aborted++;
5825
0
            return 0;
5826
0
        }
5827
5828
        // Change state to RECYCLING
5829
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5830
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5831
21
            txn->put(k, restore_job_pb.SerializeAsString());
5832
21
            err = txn->commit();
5833
21
            if (err != TxnErrorCode::TXN_OK) {
5834
0
                LOG_WARNING("failed to commit txn: {}", err);
5835
0
                return -1;
5836
0
            }
5837
21
            return 0;
5838
21
        }
5839
5840
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5841
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5842
5843
        // Recycle all data associated with the restore job.
5844
        // This includes rowsets, segments, and related resources.
5845
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5846
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5847
0
            LOG_WARNING("failed to recycle tablet")
5848
0
                    .tag("tablet_id", tablet_id)
5849
0
                    .tag("instance_id", instance_id_);
5850
0
            return -1;
5851
0
        }
5852
5853
        // delete all restore job rowset kv
5854
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5855
5856
20
        err = txn->commit();
5857
20
        if (err != TxnErrorCode::TXN_OK) {
5858
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5859
0
                    .tag("err", err)
5860
0
                    .tag("tablet id", tablet_id)
5861
0
                    .tag("instance_id", instance_id_)
5862
0
                    .tag("reason", "failed to commit txn");
5863
0
            return -1;
5864
0
        }
5865
5866
20
        metrics_context.total_recycled_num = ++num_recycled;
5867
20
        metrics_context.report();
5868
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5869
20
        restore_job_keys.push_back(k);
5870
5871
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5872
20
                  << " tablet_id=" << tablet_id;
5873
20
        return 0;
5874
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
5762
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5763
41
        ++num_scanned;
5764
41
        RestoreJobCloudPB restore_job_pb;
5765
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5766
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5767
0
            return -1;
5768
0
        }
5769
41
        int64_t expiration =
5770
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5771
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5772
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5773
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5774
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5775
0
                   << " state=" << restore_job_pb.state();
5776
41
        int64_t current_time = ::time(nullptr);
5777
41
        if (current_time < expiration) { // not expired
5778
0
            return 0;
5779
0
        }
5780
41
        ++num_expired;
5781
5782
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5783
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5784
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5785
5786
41
        std::unique_ptr<Transaction> txn;
5787
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5788
41
        if (err != TxnErrorCode::TXN_OK) {
5789
0
            LOG_WARNING("failed to recycle restore job")
5790
0
                    .tag("err", err)
5791
0
                    .tag("tablet id", tablet_id)
5792
0
                    .tag("instance_id", instance_id_)
5793
0
                    .tag("reason", "failed to create txn");
5794
0
            return -1;
5795
0
        }
5796
5797
41
        std::string val;
5798
41
        err = txn->get(k, &val);
5799
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5800
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5801
0
            return 0;
5802
0
        }
5803
41
        if (err != TxnErrorCode::TXN_OK) {
5804
0
            LOG_WARNING("failed to get kv");
5805
0
            return -1;
5806
0
        }
5807
41
        restore_job_pb.Clear();
5808
41
        if (!restore_job_pb.ParseFromString(val)) {
5809
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5810
0
            return -1;
5811
0
        }
5812
5813
        // PREPARED or COMMITTED, change state to DROPPED and return
5814
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5815
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5816
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5817
0
            restore_job_pb.set_need_recycle_data(true);
5818
0
            txn->put(k, restore_job_pb.SerializeAsString());
5819
0
            err = txn->commit();
5820
0
            if (err != TxnErrorCode::TXN_OK) {
5821
0
                LOG_WARNING("failed to commit txn: {}", err);
5822
0
                return -1;
5823
0
            }
5824
0
            num_aborted++;
5825
0
            return 0;
5826
0
        }
5827
5828
        // Change state to RECYCLING
5829
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5830
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5831
21
            txn->put(k, restore_job_pb.SerializeAsString());
5832
21
            err = txn->commit();
5833
21
            if (err != TxnErrorCode::TXN_OK) {
5834
0
                LOG_WARNING("failed to commit txn: {}", err);
5835
0
                return -1;
5836
0
            }
5837
21
            return 0;
5838
21
        }
5839
5840
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5841
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5842
5843
        // Recycle all data associated with the restore job.
5844
        // This includes rowsets, segments, and related resources.
5845
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5846
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5847
0
            LOG_WARNING("failed to recycle tablet")
5848
0
                    .tag("tablet_id", tablet_id)
5849
0
                    .tag("instance_id", instance_id_);
5850
0
            return -1;
5851
0
        }
5852
5853
        // delete all restore job rowset kv
5854
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5855
5856
20
        err = txn->commit();
5857
20
        if (err != TxnErrorCode::TXN_OK) {
5858
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5859
0
                    .tag("err", err)
5860
0
                    .tag("tablet id", tablet_id)
5861
0
                    .tag("instance_id", instance_id_)
5862
0
                    .tag("reason", "failed to commit txn");
5863
0
            return -1;
5864
0
        }
5865
5866
20
        metrics_context.total_recycled_num = ++num_recycled;
5867
20
        metrics_context.report();
5868
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5869
20
        restore_job_keys.push_back(k);
5870
5871
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5872
20
                  << " tablet_id=" << tablet_id;
5873
20
        return 0;
5874
20
    };
5875
5876
13
    auto loop_done = [&restore_job_keys, this]() -> int {
5877
3
        if (restore_job_keys.empty()) return 0;
5878
1
        DORIS_CLOUD_DEFER {
5879
1
            restore_job_keys.clear();
5880
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5878
1
        DORIS_CLOUD_DEFER {
5879
1
            restore_job_keys.clear();
5880
1
        };
5881
5882
1
        std::unique_ptr<Transaction> txn;
5883
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5884
1
        if (err != TxnErrorCode::TXN_OK) {
5885
0
            LOG_WARNING("failed to recycle restore job")
5886
0
                    .tag("err", err)
5887
0
                    .tag("instance_id", instance_id_)
5888
0
                    .tag("reason", "failed to create txn");
5889
0
            return -1;
5890
0
        }
5891
20
        for (auto& k : restore_job_keys) {
5892
20
            txn->remove(k);
5893
20
        }
5894
1
        err = txn->commit();
5895
1
        if (err != TxnErrorCode::TXN_OK) {
5896
0
            LOG_WARNING("failed to recycle restore job")
5897
0
                    .tag("err", err)
5898
0
                    .tag("instance_id", instance_id_)
5899
0
                    .tag("reason", "failed to commit txn");
5900
0
            return -1;
5901
0
        }
5902
1
        return 0;
5903
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
5876
3
    auto loop_done = [&restore_job_keys, this]() -> int {
5877
3
        if (restore_job_keys.empty()) return 0;
5878
1
        DORIS_CLOUD_DEFER {
5879
1
            restore_job_keys.clear();
5880
1
        };
5881
5882
1
        std::unique_ptr<Transaction> txn;
5883
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5884
1
        if (err != TxnErrorCode::TXN_OK) {
5885
0
            LOG_WARNING("failed to recycle restore job")
5886
0
                    .tag("err", err)
5887
0
                    .tag("instance_id", instance_id_)
5888
0
                    .tag("reason", "failed to create txn");
5889
0
            return -1;
5890
0
        }
5891
20
        for (auto& k : restore_job_keys) {
5892
20
            txn->remove(k);
5893
20
        }
5894
1
        err = txn->commit();
5895
1
        if (err != TxnErrorCode::TXN_OK) {
5896
0
            LOG_WARNING("failed to recycle restore job")
5897
0
                    .tag("err", err)
5898
0
                    .tag("instance_id", instance_id_)
5899
0
                    .tag("reason", "failed to commit txn");
5900
0
            return -1;
5901
0
        }
5902
1
        return 0;
5903
1
    };
5904
5905
13
    if (config::enable_recycler_stats_metrics) {
5906
0
        scan_and_statistics_restore_jobs();
5907
0
    }
5908
5909
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
5910
13
                            std::move(loop_done));
5911
13
}
5912
5913
11
int InstanceRecycler::recycle_versioned_rowsets() {
5914
11
    const std::string task_name = "recycle_rowsets";
5915
11
    int64_t num_scanned = 0;
5916
11
    int64_t num_expired = 0;
5917
11
    int64_t num_prepare = 0;
5918
11
    int64_t num_compacted = 0;
5919
11
    int64_t num_empty_rowset = 0;
5920
11
    size_t total_rowset_key_size = 0;
5921
11
    size_t total_rowset_value_size = 0;
5922
11
    size_t expired_rowset_size = 0;
5923
11
    std::atomic_long num_recycled = 0;
5924
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5925
5926
11
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5927
11
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5928
11
    std::string recyc_rs_key0;
5929
11
    std::string recyc_rs_key1;
5930
11
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5931
11
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5932
5933
11
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5934
5935
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5936
11
    register_recycle_task(task_name, start_time);
5937
5938
11
    DORIS_CLOUD_DEFER {
5939
11
        unregister_recycle_task(task_name);
5940
11
        int64_t cost =
5941
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5942
11
        metrics_context.finish_report();
5943
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5944
11
                .tag("instance_id", instance_id_)
5945
11
                .tag("num_scanned", num_scanned)
5946
11
                .tag("num_expired", num_expired)
5947
11
                .tag("num_recycled", num_recycled)
5948
11
                .tag("num_recycled.prepare", num_prepare)
5949
11
                .tag("num_recycled.compacted", num_compacted)
5950
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5951
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5952
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5953
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
5954
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
5938
11
    DORIS_CLOUD_DEFER {
5939
11
        unregister_recycle_task(task_name);
5940
11
        int64_t cost =
5941
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5942
11
        metrics_context.finish_report();
5943
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5944
11
                .tag("instance_id", instance_id_)
5945
11
                .tag("num_scanned", num_scanned)
5946
11
                .tag("num_expired", num_expired)
5947
11
                .tag("num_recycled", num_recycled)
5948
11
                .tag("num_recycled.prepare", num_prepare)
5949
11
                .tag("num_recycled.compacted", num_compacted)
5950
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5951
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5952
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5953
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
5954
11
    };
5955
5956
11
    std::vector<std::string> orphan_rowset_keys;
5957
5958
    // Store keys of rowset recycled by background workers
5959
11
    std::mutex async_recycled_rowset_keys_mutex;
5960
11
    std::vector<std::string> async_recycled_rowset_keys;
5961
11
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5962
11
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5963
11
    worker_pool->start();
5964
11
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5965
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5966
        // Try to delete rowset data in background thread
5967
400
        int ret = worker_pool->submit_with_timeout(
5968
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5969
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5970
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5971
400
                        return;
5972
400
                    }
5973
                    // The async recycled rowsets are staled format or has not been used,
5974
                    // so we don't need to check the rowset ref count key.
5975
0
                    std::vector<std::string> keys;
5976
0
                    {
5977
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5978
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5979
0
                        if (async_recycled_rowset_keys.size() > 100) {
5980
0
                            keys.swap(async_recycled_rowset_keys);
5981
0
                        }
5982
0
                    }
5983
0
                    if (keys.empty()) return;
5984
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5985
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5986
0
                                     << instance_id_;
5987
0
                    } else {
5988
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5989
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5990
0
                                           num_recycled, start_time);
5991
0
                    }
5992
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
5968
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5969
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5970
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5971
400
                        return;
5972
400
                    }
5973
                    // The async recycled rowsets are staled format or has not been used,
5974
                    // so we don't need to check the rowset ref count key.
5975
0
                    std::vector<std::string> keys;
5976
0
                    {
5977
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5978
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5979
0
                        if (async_recycled_rowset_keys.size() > 100) {
5980
0
                            keys.swap(async_recycled_rowset_keys);
5981
0
                        }
5982
0
                    }
5983
0
                    if (keys.empty()) return;
5984
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5985
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5986
0
                                     << instance_id_;
5987
0
                    } else {
5988
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5989
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5990
0
                                           num_recycled, start_time);
5991
0
                    }
5992
0
                },
5993
400
                0);
5994
400
        if (ret == 0) return 0;
5995
        // Submit task failed, delete rowset data in current thread
5996
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5997
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5998
0
            return -1;
5999
0
        }
6000
0
        orphan_rowset_keys.push_back(std::move(key));
6001
0
        return 0;
6002
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
5965
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5966
        // Try to delete rowset data in background thread
5967
400
        int ret = worker_pool->submit_with_timeout(
5968
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5969
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5970
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5971
400
                        return;
5972
400
                    }
5973
                    // The async recycled rowsets are staled format or has not been used,
5974
                    // so we don't need to check the rowset ref count key.
5975
400
                    std::vector<std::string> keys;
5976
400
                    {
5977
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5978
400
                        async_recycled_rowset_keys.push_back(std::move(key));
5979
400
                        if (async_recycled_rowset_keys.size() > 100) {
5980
400
                            keys.swap(async_recycled_rowset_keys);
5981
400
                        }
5982
400
                    }
5983
400
                    if (keys.empty()) return;
5984
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5985
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5986
400
                                     << instance_id_;
5987
400
                    } else {
5988
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5989
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5990
400
                                           num_recycled, start_time);
5991
400
                    }
5992
400
                },
5993
400
                0);
5994
400
        if (ret == 0) return 0;
5995
        // Submit task failed, delete rowset data in current thread
5996
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5997
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5998
0
            return -1;
5999
0
        }
6000
0
        orphan_rowset_keys.push_back(std::move(key));
6001
0
        return 0;
6002
0
    };
6003
6004
11
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6005
6006
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6007
2.01k
        ++num_scanned;
6008
2.01k
        total_rowset_key_size += k.size();
6009
2.01k
        total_rowset_value_size += v.size();
6010
2.01k
        RecycleRowsetPB rowset;
6011
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6012
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6013
0
            return -1;
6014
0
        }
6015
6016
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6017
6018
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6019
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6020
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6021
2.01k
        int64_t current_time = ::time(nullptr);
6022
2.01k
        if (current_time < final_expiration) { // not expired
6023
0
            return 0;
6024
0
        }
6025
2.01k
        ++num_expired;
6026
2.01k
        expired_rowset_size += v.size();
6027
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6028
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6029
                // in old version, keep this key-value pair and it needs to be checked manually
6030
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6031
0
                return -1;
6032
0
            }
6033
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6034
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6035
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6036
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6037
0
                orphan_rowset_keys.emplace_back(k);
6038
0
                return -1;
6039
0
            }
6040
            // decode rowset_id
6041
0
            auto k1 = k;
6042
0
            k1.remove_prefix(1);
6043
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6044
0
            decode_key(&k1, &out);
6045
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6046
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6047
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6048
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6049
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6050
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6051
0
                return -1;
6052
0
            }
6053
0
            return 0;
6054
0
        }
6055
        // TODO(plat1ko): check rowset not referenced
6056
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6057
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6058
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6059
0
                LOG_INFO("recycle rowset that has empty resource id");
6060
0
            } else {
6061
                // other situations, keep this key-value pair and it needs to be checked manually
6062
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6063
0
                return -1;
6064
0
            }
6065
0
        }
6066
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6067
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6068
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6069
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6070
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6071
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6072
2.01k
                  << " rowset_meta_size=" << v.size()
6073
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6074
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6075
            // unable to calculate file path, can only be deleted by rowset id prefix
6076
400
            num_prepare += 1;
6077
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6078
400
                                             rowset_meta->tablet_id(),
6079
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6080
0
                return -1;
6081
0
            }
6082
1.61k
        } else {
6083
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6084
1.61k
            worker_pool->submit(
6085
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6086
                        // The load & compact rowset keys are recycled during recycling operation logs.
6087
1.61k
                        RowsetDeleteTask task;
6088
1.61k
                        task.rowset_meta = rowset_meta;
6089
1.61k
                        task.recycle_rowset_key = k;
6090
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6091
1.60k
                            return;
6092
1.60k
                        }
6093
13
                        num_compacted += is_compacted;
6094
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6095
13
                        if (rowset_meta.num_segments() == 0) {
6096
0
                            ++num_empty_rowset;
6097
0
                        }
6098
13
                    });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlvE_clEv
Line
Count
Source
6085
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6086
                        // The load & compact rowset keys are recycled during recycling operation logs.
6087
1.61k
                        RowsetDeleteTask task;
6088
1.61k
                        task.rowset_meta = rowset_meta;
6089
1.61k
                        task.recycle_rowset_key = k;
6090
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6091
1.60k
                            return;
6092
1.60k
                        }
6093
13
                        num_compacted += is_compacted;
6094
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6095
13
                        if (rowset_meta.num_segments() == 0) {
6096
0
                            ++num_empty_rowset;
6097
0
                        }
6098
13
                    });
6099
1.61k
        }
6100
2.01k
        return 0;
6101
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
6006
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6007
2.01k
        ++num_scanned;
6008
2.01k
        total_rowset_key_size += k.size();
6009
2.01k
        total_rowset_value_size += v.size();
6010
2.01k
        RecycleRowsetPB rowset;
6011
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6012
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6013
0
            return -1;
6014
0
        }
6015
6016
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6017
6018
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6019
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6020
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6021
2.01k
        int64_t current_time = ::time(nullptr);
6022
2.01k
        if (current_time < final_expiration) { // not expired
6023
0
            return 0;
6024
0
        }
6025
2.01k
        ++num_expired;
6026
2.01k
        expired_rowset_size += v.size();
6027
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6028
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6029
                // in old version, keep this key-value pair and it needs to be checked manually
6030
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6031
0
                return -1;
6032
0
            }
6033
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6034
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6035
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6036
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6037
0
                orphan_rowset_keys.emplace_back(k);
6038
0
                return -1;
6039
0
            }
6040
            // decode rowset_id
6041
0
            auto k1 = k;
6042
0
            k1.remove_prefix(1);
6043
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6044
0
            decode_key(&k1, &out);
6045
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6046
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6047
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6048
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6049
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6050
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6051
0
                return -1;
6052
0
            }
6053
0
            return 0;
6054
0
        }
6055
        // TODO(plat1ko): check rowset not referenced
6056
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6057
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6058
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6059
0
                LOG_INFO("recycle rowset that has empty resource id");
6060
0
            } else {
6061
                // other situations, keep this key-value pair and it needs to be checked manually
6062
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6063
0
                return -1;
6064
0
            }
6065
0
        }
6066
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6067
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6068
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6069
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6070
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6071
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6072
2.01k
                  << " rowset_meta_size=" << v.size()
6073
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6074
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6075
            // unable to calculate file path, can only be deleted by rowset id prefix
6076
400
            num_prepare += 1;
6077
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6078
400
                                             rowset_meta->tablet_id(),
6079
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6080
0
                return -1;
6081
0
            }
6082
1.61k
        } else {
6083
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6084
1.61k
            worker_pool->submit(
6085
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6086
                        // The load & compact rowset keys are recycled during recycling operation logs.
6087
1.61k
                        RowsetDeleteTask task;
6088
1.61k
                        task.rowset_meta = rowset_meta;
6089
1.61k
                        task.recycle_rowset_key = k;
6090
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6091
1.61k
                            return;
6092
1.61k
                        }
6093
1.61k
                        num_compacted += is_compacted;
6094
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6095
1.61k
                        if (rowset_meta.num_segments() == 0) {
6096
1.61k
                            ++num_empty_rowset;
6097
1.61k
                        }
6098
1.61k
                    });
6099
1.61k
        }
6100
2.01k
        return 0;
6101
2.01k
    };
6102
6103
11
    if (config::enable_recycler_stats_metrics) {
6104
0
        scan_and_statistics_rowsets();
6105
0
    }
6106
6107
11
    auto loop_done = [&]() -> int {
6108
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6109
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6110
0
        }
6111
6
        orphan_rowset_keys.clear();
6112
6
        return 0;
6113
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
Line
Count
Source
6107
6
    auto loop_done = [&]() -> int {
6108
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6109
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6110
0
        }
6111
6
        orphan_rowset_keys.clear();
6112
6
        return 0;
6113
6
    };
6114
6115
    // recycle_func and loop_done for scan and recycle
6116
11
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
6117
11
                               std::move(loop_done));
6118
6119
11
    worker_pool->stop();
6120
6121
11
    if (!async_recycled_rowset_keys.empty()) {
6122
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
6123
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6124
0
            return -1;
6125
0
        } else {
6126
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
6127
0
        }
6128
0
    }
6129
6130
    // Report final metrics after all concurrent tasks completed
6131
11
    segment_metrics_context_.report();
6132
11
    metrics_context.report();
6133
6134
11
    return ret;
6135
11
}
6136
6137
1.61k
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task) {
6138
1.61k
    constexpr int MAX_RETRY = 10;
6139
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
6140
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
6141
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
6142
1.61k
    std::string_view reference_instance_id = instance_id_;
6143
1.61k
    if (rowset_meta.has_reference_instance_id()) {
6144
8
        reference_instance_id = rowset_meta.reference_instance_id();
6145
8
    }
6146
6147
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
6148
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
6149
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
6150
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
6151
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
6152
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
6153
1.61k
        std::unique_ptr<Transaction> txn;
6154
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6155
1.61k
        if (err != TxnErrorCode::TXN_OK) {
6156
0
            LOG_WARNING("failed to create txn").tag("err", err);
6157
0
            return -1;
6158
0
        }
6159
6160
1.61k
        std::string rowset_ref_count_key =
6161
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
6162
1.61k
        int64_t ref_count = 0;
6163
1.61k
        {
6164
1.61k
            std::string value;
6165
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
6166
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6167
                // This is the old version rowset, we could recycle it directly.
6168
1.60k
                ref_count = 1;
6169
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
6170
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
6171
0
                return -1;
6172
10
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
6173
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
6174
0
                return -1;
6175
0
            }
6176
1.61k
        }
6177
6178
1.61k
        if (ref_count == 1) {
6179
            // It would not be added since it is recycling.
6180
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
6181
1.60k
                LOG_WARNING("failed to delete rowset data");
6182
1.60k
                return -1;
6183
1.60k
            }
6184
6185
            // Reset the transaction to avoid timeout.
6186
10
            err = txn_kv_->create_txn(&txn);
6187
10
            if (err != TxnErrorCode::TXN_OK) {
6188
0
                LOG_WARNING("failed to create txn").tag("err", err);
6189
0
                return -1;
6190
0
            }
6191
10
            txn->remove(rowset_ref_count_key);
6192
10
            LOG_INFO("delete rowset data ref count key")
6193
10
                    .tag("txn_id", rowset_meta.txn_id())
6194
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6195
6196
10
            std::string dbm_start_key =
6197
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
6198
10
            std::string dbm_end_key = meta_delete_bitmap_key(
6199
10
                    {reference_instance_id, tablet_id, rowset_id,
6200
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
6201
10
            txn->remove(dbm_start_key, dbm_end_key);
6202
10
            LOG_INFO("remove delete bitmap kv")
6203
10
                    .tag("begin", hex(dbm_start_key))
6204
10
                    .tag("end", hex(dbm_end_key));
6205
6206
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
6207
10
                    {reference_instance_id, tablet_id, rowset_id});
6208
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
6209
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
6210
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
6211
10
            LOG_INFO("remove versioned delete bitmap kv")
6212
10
                    .tag("begin", hex(versioned_dbm_start_key))
6213
10
                    .tag("end", hex(versioned_dbm_end_key));
6214
10
        } else {
6215
            // Decrease the rowset ref count.
6216
            //
6217
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
6218
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
6219
2
            txn->atomic_add(rowset_ref_count_key, -1);
6220
2
            LOG_INFO("decrease rowset data ref count")
6221
2
                    .tag("txn_id", rowset_meta.txn_id())
6222
2
                    .tag("ref_count", ref_count - 1)
6223
2
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6224
2
        }
6225
6226
12
        if (!task.versioned_rowset_key.empty()) {
6227
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
6228
0
                                                          task.versionstamp);
6229
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
6230
0
        }
6231
6232
12
        if (!task.non_versioned_rowset_key.empty()) {
6233
0
            txn->remove(task.non_versioned_rowset_key);
6234
0
            LOG_INFO("remove non versioned rowset key")
6235
0
                    .tag("key", hex(task.non_versioned_rowset_key));
6236
0
        }
6237
6238
        // empty when recycle ref rowsets for deleted instance
6239
13
        if (!task.recycle_rowset_key.empty()) {
6240
13
            txn->remove(task.recycle_rowset_key);
6241
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
6242
13
        }
6243
6244
12
        err = txn->commit();
6245
12
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
6246
            // The rowset ref count key has been changed, we need to retry.
6247
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
6248
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
6249
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
6250
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6251
0
            continue;
6252
12
        } else if (err != TxnErrorCode::TXN_OK) {
6253
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
6254
0
            return -1;
6255
0
        }
6256
12
        LOG_INFO("recycle rowset meta and data success");
6257
12
        return 0;
6258
12
    }
6259
1
    LOG_WARNING("failed to recycle rowset meta and data after retry")
6260
1
            .tag("tablet_id", tablet_id)
6261
1
            .tag("rowset_id", rowset_id)
6262
1
            .tag("retry", MAX_RETRY);
6263
1
    return -1;
6264
1.61k
}
6265
6266
35
int InstanceRecycler::recycle_tmp_rowsets() {
6267
35
    const std::string task_name = "recycle_tmp_rowsets";
6268
35
    int64_t num_scanned = 0;
6269
35
    int64_t num_expired = 0;
6270
35
    std::atomic_long num_recycled = 0;
6271
35
    size_t expired_rowset_size = 0;
6272
35
    size_t total_rowset_key_size = 0;
6273
35
    size_t total_rowset_value_size = 0;
6274
35
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6275
6276
35
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
6277
35
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
6278
35
    std::string tmp_rs_key0;
6279
35
    std::string tmp_rs_key1;
6280
35
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
6281
35
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
6282
6283
35
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
6284
6285
35
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6286
35
    register_recycle_task(task_name, start_time);
6287
6288
35
    DORIS_CLOUD_DEFER {
6289
35
        unregister_recycle_task(task_name);
6290
35
        int64_t cost =
6291
35
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6292
35
        metrics_context.finish_report();
6293
35
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6294
35
                .tag("instance_id", instance_id_)
6295
35
                .tag("num_scanned", num_scanned)
6296
35
                .tag("num_expired", num_expired)
6297
35
                .tag("num_recycled", num_recycled)
6298
35
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6299
35
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6300
35
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6301
35
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6288
12
    DORIS_CLOUD_DEFER {
6289
12
        unregister_recycle_task(task_name);
6290
12
        int64_t cost =
6291
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6292
12
        metrics_context.finish_report();
6293
12
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6294
12
                .tag("instance_id", instance_id_)
6295
12
                .tag("num_scanned", num_scanned)
6296
12
                .tag("num_expired", num_expired)
6297
12
                .tag("num_recycled", num_recycled)
6298
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6299
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6300
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6301
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6288
23
    DORIS_CLOUD_DEFER {
6289
23
        unregister_recycle_task(task_name);
6290
23
        int64_t cost =
6291
23
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6292
23
        metrics_context.finish_report();
6293
23
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6294
23
                .tag("instance_id", instance_id_)
6295
23
                .tag("num_scanned", num_scanned)
6296
23
                .tag("num_expired", num_expired)
6297
23
                .tag("num_recycled", num_recycled)
6298
23
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6299
23
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6300
23
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6301
23
    };
6302
6303
    // Elements in `tmp_rowset_keys` has the same lifetime as `it`
6304
6305
35
    std::vector<std::string> tmp_rowset_keys;
6306
35
    std::vector<std::string> tmp_rowset_ref_count_keys;
6307
35
    std::vector<std::string> tmp_rowset_keys_to_mark_recycled;
6308
35
    std::vector<std::string> tmp_rowset_keys_to_abort;
6309
6310
    // rowset_id -> rowset_meta
6311
    // store tmp_rowset id and meta for statistics rs size when delete
6312
35
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
6313
35
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6314
35
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
6315
35
    worker_pool->start();
6316
6317
35
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6318
6319
35
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &tmp_rowsets,
6320
35
                             &expired_rowset_size, &total_rowset_key_size, &total_rowset_value_size,
6321
35
                             &earlest_ts, &tmp_rowset_ref_count_keys,
6322
35
                             &tmp_rowset_keys_to_mark_recycled, &tmp_rowset_keys_to_abort, this,
6323
53.0k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
6324
53.0k
        ++num_scanned;
6325
53.0k
        total_rowset_key_size += k.size();
6326
53.0k
        total_rowset_value_size += v.size();
6327
53.0k
        doris::RowsetMetaCloudPB rowset;
6328
53.0k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6329
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6330
0
            return -1;
6331
0
        }
6332
53.0k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6333
53.0k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6334
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6335
0
                   << " txn_expiration=" << rowset.txn_expiration()
6336
0
                   << " rowset_creation_time=" << rowset.creation_time();
6337
53.0k
        int64_t current_time = ::time(nullptr);
6338
53.0k
        if (current_time < expiration) { // not expired
6339
0
            return 0;
6340
0
        }
6341
6342
53.0k
        if (config::enable_mark_delete_rowset_before_recycle) {
6343
16
            if (need_mark_rowset_as_recycled(rowset)) {
6344
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6345
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6346
9
                             "at next turn, instance_id="
6347
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6348
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6349
9
                return 0;
6350
9
            }
6351
16
        }
6352
6353
53.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6354
7
            if (make_deferred_abort_task(rowset).has_value()) {
6355
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6356
3
                             "instance_id="
6357
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6358
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6359
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6360
3
            }
6361
7
        }
6362
6363
53.0k
        ++num_expired;
6364
53.0k
        expired_rowset_size += v.size();
6365
53.0k
        if (!rowset.has_resource_id()) {
6366
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6367
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6368
0
                return -1;
6369
0
            }
6370
            // might be a delete pred rowset
6371
0
            tmp_rowset_keys.emplace_back(k);
6372
0
            return 0;
6373
0
        }
6374
        // TODO(plat1ko): check rowset not referenced
6375
53.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6376
53.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6377
53.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6378
53.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6379
53.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6380
53.0k
                  << " num_expired=" << num_expired
6381
53.0k
                  << " task_type=" << metrics_context.operation_type;
6382
6383
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6384
        // Remove the rowset ref count key directly since it has not been used.
6385
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6386
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6387
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6388
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6389
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6390
6391
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6392
53.0k
        return 0;
6393
53.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6323
16
                             &metrics_context](std::string_view k, std::string_view v) -> int {
6324
16
        ++num_scanned;
6325
16
        total_rowset_key_size += k.size();
6326
16
        total_rowset_value_size += v.size();
6327
16
        doris::RowsetMetaCloudPB rowset;
6328
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6329
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6330
0
            return -1;
6331
0
        }
6332
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6333
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6334
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6335
0
                   << " txn_expiration=" << rowset.txn_expiration()
6336
0
                   << " rowset_creation_time=" << rowset.creation_time();
6337
16
        int64_t current_time = ::time(nullptr);
6338
16
        if (current_time < expiration) { // not expired
6339
0
            return 0;
6340
0
        }
6341
6342
16
        if (config::enable_mark_delete_rowset_before_recycle) {
6343
16
            if (need_mark_rowset_as_recycled(rowset)) {
6344
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6345
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6346
9
                             "at next turn, instance_id="
6347
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6348
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6349
9
                return 0;
6350
9
            }
6351
16
        }
6352
6353
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6354
7
            if (make_deferred_abort_task(rowset).has_value()) {
6355
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6356
3
                             "instance_id="
6357
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6358
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6359
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6360
3
            }
6361
7
        }
6362
6363
7
        ++num_expired;
6364
7
        expired_rowset_size += v.size();
6365
7
        if (!rowset.has_resource_id()) {
6366
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6367
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6368
0
                return -1;
6369
0
            }
6370
            // might be a delete pred rowset
6371
0
            tmp_rowset_keys.emplace_back(k);
6372
0
            return 0;
6373
0
        }
6374
        // TODO(plat1ko): check rowset not referenced
6375
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6376
7
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6377
7
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6378
7
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6379
7
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6380
7
                  << " num_expired=" << num_expired
6381
7
                  << " task_type=" << metrics_context.operation_type;
6382
6383
7
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6384
        // Remove the rowset ref count key directly since it has not been used.
6385
7
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6386
7
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6387
7
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6388
7
                  << "key=" << hex(rowset_ref_count_key);
6389
7
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6390
6391
7
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6392
7
        return 0;
6393
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6323
53.0k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
6324
53.0k
        ++num_scanned;
6325
53.0k
        total_rowset_key_size += k.size();
6326
53.0k
        total_rowset_value_size += v.size();
6327
53.0k
        doris::RowsetMetaCloudPB rowset;
6328
53.0k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6329
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6330
0
            return -1;
6331
0
        }
6332
53.0k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6333
53.0k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6334
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6335
0
                   << " txn_expiration=" << rowset.txn_expiration()
6336
0
                   << " rowset_creation_time=" << rowset.creation_time();
6337
53.0k
        int64_t current_time = ::time(nullptr);
6338
53.0k
        if (current_time < expiration) { // not expired
6339
0
            return 0;
6340
0
        }
6341
6342
53.0k
        if (config::enable_mark_delete_rowset_before_recycle) {
6343
0
            if (need_mark_rowset_as_recycled(rowset)) {
6344
0
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6345
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6346
0
                             "at next turn, instance_id="
6347
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6348
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6349
0
                return 0;
6350
0
            }
6351
0
        }
6352
6353
53.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6354
0
            if (make_deferred_abort_task(rowset).has_value()) {
6355
0
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6356
0
                             "instance_id="
6357
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6358
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6359
0
                tmp_rowset_keys_to_abort.emplace_back(k);
6360
0
            }
6361
0
        }
6362
6363
53.0k
        ++num_expired;
6364
53.0k
        expired_rowset_size += v.size();
6365
53.0k
        if (!rowset.has_resource_id()) {
6366
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6367
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6368
0
                return -1;
6369
0
            }
6370
            // might be a delete pred rowset
6371
0
            tmp_rowset_keys.emplace_back(k);
6372
0
            return 0;
6373
0
        }
6374
        // TODO(plat1ko): check rowset not referenced
6375
53.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6376
53.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6377
53.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6378
53.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6379
53.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6380
53.0k
                  << " num_expired=" << num_expired
6381
53.0k
                  << " task_type=" << metrics_context.operation_type;
6382
6383
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6384
        // Remove the rowset ref count key directly since it has not been used.
6385
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6386
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6387
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6388
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6389
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6390
6391
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6392
53.0k
        return 0;
6393
53.0k
    };
6394
6395
    // TODO bacth delete
6396
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6397
51.0k
        std::string dbm_start_key =
6398
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
6399
51.0k
        std::string dbm_end_key = dbm_start_key;
6400
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
6401
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
6402
51.0k
        if (ret != 0) {
6403
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6404
0
                         << instance_id_ << ", tablet_id=" << tablet_id
6405
0
                         << ", rowset_id=" << rowset_id;
6406
0
        }
6407
51.0k
        return ret;
6408
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6396
7
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6397
7
        std::string dbm_start_key =
6398
7
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
6399
7
        std::string dbm_end_key = dbm_start_key;
6400
7
        encode_int64(INT64_MAX, &dbm_end_key);
6401
7
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
6402
7
        if (ret != 0) {
6403
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6404
0
                         << instance_id_ << ", tablet_id=" << tablet_id
6405
0
                         << ", rowset_id=" << rowset_id;
6406
0
        }
6407
7
        return ret;
6408
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6396
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6397
51.0k
        std::string dbm_start_key =
6398
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
6399
51.0k
        std::string dbm_end_key = dbm_start_key;
6400
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
6401
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
6402
51.0k
        if (ret != 0) {
6403
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6404
0
                         << instance_id_ << ", tablet_id=" << tablet_id
6405
0
                         << ", rowset_id=" << rowset_id;
6406
0
        }
6407
51.0k
        return ret;
6408
51.0k
    };
6409
6410
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6411
51.0k
        auto delete_bitmap_start =
6412
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
6413
51.0k
        auto delete_bitmap_end =
6414
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
6415
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
6416
51.0k
        if (ret != 0) {
6417
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
6418
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
6419
0
        }
6420
51.0k
        return ret;
6421
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6410
7
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6411
7
        auto delete_bitmap_start =
6412
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
6413
7
        auto delete_bitmap_end =
6414
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
6415
7
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
6416
7
        if (ret != 0) {
6417
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
6418
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
6419
0
        }
6420
7
        return ret;
6421
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6410
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6411
51.0k
        auto delete_bitmap_start =
6412
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
6413
51.0k
        auto delete_bitmap_end =
6414
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
6415
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
6416
51.0k
        if (ret != 0) {
6417
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
6418
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
6419
0
        }
6420
51.0k
        return ret;
6421
51.0k
    };
6422
6423
35
    auto loop_done = [&]() -> int {
6424
22
        std::vector<std::string> tmp_rowset_keys_to_delete;
6425
22
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6426
22
        std::vector<std::string> mark_keys_to_process;
6427
22
        std::vector<std::string> abort_keys_to_process;
6428
22
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6429
22
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6430
22
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6431
22
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6432
22
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6433
22
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6434
22
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6435
22
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6436
22
                             tmp_rowset_ref_count_keys_to_delete =
6437
22
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6438
22
                             mark_keys_to_process = std::move(mark_keys_to_process),
6439
22
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6440
22
            if (!mark_keys_to_process.empty() &&
6441
22
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6442
7
                                                                  mark_keys_to_process) != 0) {
6443
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6444
0
                             << instance_id_;
6445
0
                return;
6446
0
            }
6447
22
            if (!abort_keys_to_process.empty() &&
6448
22
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6449
3
                                                                      false) != 0) {
6450
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6451
0
                             << instance_id_;
6452
0
                return;
6453
0
            }
6454
22
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6455
22
                                   metrics_context) != 0) {
6456
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6457
2
                return;
6458
2
            }
6459
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6460
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6461
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6462
0
                                 << rs.ShortDebugString();
6463
0
                    return;
6464
0
                }
6465
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6466
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6467
0
                                 << rs.ShortDebugString();
6468
0
                    return;
6469
0
                }
6470
51.0k
            }
6471
20
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6472
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6473
0
                return;
6474
0
            }
6475
20
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6476
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6477
0
                return;
6478
0
            }
6479
20
            num_recycled += tmp_rowset_keys_to_delete.size();
6480
20
            return;
6481
20
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
6439
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6440
12
            if (!mark_keys_to_process.empty() &&
6441
12
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6442
7
                                                                  mark_keys_to_process) != 0) {
6443
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6444
0
                             << instance_id_;
6445
0
                return;
6446
0
            }
6447
12
            if (!abort_keys_to_process.empty() &&
6448
12
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6449
3
                                                                      false) != 0) {
6450
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6451
0
                             << instance_id_;
6452
0
                return;
6453
0
            }
6454
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6455
12
                                   metrics_context) != 0) {
6456
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6457
0
                return;
6458
0
            }
6459
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6460
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6461
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6462
0
                                 << rs.ShortDebugString();
6463
0
                    return;
6464
0
                }
6465
7
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6466
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6467
0
                                 << rs.ShortDebugString();
6468
0
                    return;
6469
0
                }
6470
7
            }
6471
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6472
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6473
0
                return;
6474
0
            }
6475
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6476
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6477
0
                return;
6478
0
            }
6479
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6480
12
            return;
6481
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
6439
10
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6440
10
            if (!mark_keys_to_process.empty() &&
6441
10
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6442
0
                                                                  mark_keys_to_process) != 0) {
6443
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6444
0
                             << instance_id_;
6445
0
                return;
6446
0
            }
6447
10
            if (!abort_keys_to_process.empty() &&
6448
10
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6449
0
                                                                      false) != 0) {
6450
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6451
0
                             << instance_id_;
6452
0
                return;
6453
0
            }
6454
10
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6455
10
                                   metrics_context) != 0) {
6456
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6457
2
                return;
6458
2
            }
6459
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6460
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6461
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6462
0
                                 << rs.ShortDebugString();
6463
0
                    return;
6464
0
                }
6465
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6466
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6467
0
                                 << rs.ShortDebugString();
6468
0
                    return;
6469
0
                }
6470
51.0k
            }
6471
8
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6472
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6473
0
                return;
6474
0
            }
6475
8
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6476
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6477
0
                return;
6478
0
            }
6479
8
            num_recycled += tmp_rowset_keys_to_delete.size();
6480
8
            return;
6481
8
        });
6482
22
        return 0;
6483
22
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEv
Line
Count
Source
6423
12
    auto loop_done = [&]() -> int {
6424
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6425
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6426
12
        std::vector<std::string> mark_keys_to_process;
6427
12
        std::vector<std::string> abort_keys_to_process;
6428
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6429
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6430
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6431
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6432
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6433
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6434
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6435
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6436
12
                             tmp_rowset_ref_count_keys_to_delete =
6437
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6438
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6439
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6440
12
            if (!mark_keys_to_process.empty() &&
6441
12
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6442
12
                                                                  mark_keys_to_process) != 0) {
6443
12
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6444
12
                             << instance_id_;
6445
12
                return;
6446
12
            }
6447
12
            if (!abort_keys_to_process.empty() &&
6448
12
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6449
12
                                                                      false) != 0) {
6450
12
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6451
12
                             << instance_id_;
6452
12
                return;
6453
12
            }
6454
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6455
12
                                   metrics_context) != 0) {
6456
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6457
12
                return;
6458
12
            }
6459
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6460
12
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6461
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6462
12
                                 << rs.ShortDebugString();
6463
12
                    return;
6464
12
                }
6465
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6466
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6467
12
                                 << rs.ShortDebugString();
6468
12
                    return;
6469
12
                }
6470
12
            }
6471
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6472
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6473
12
                return;
6474
12
            }
6475
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6476
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6477
12
                return;
6478
12
            }
6479
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6480
12
            return;
6481
12
        });
6482
12
        return 0;
6483
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEv
Line
Count
Source
6423
10
    auto loop_done = [&]() -> int {
6424
10
        std::vector<std::string> tmp_rowset_keys_to_delete;
6425
10
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6426
10
        std::vector<std::string> mark_keys_to_process;
6427
10
        std::vector<std::string> abort_keys_to_process;
6428
10
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6429
10
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6430
10
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6431
10
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6432
10
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6433
10
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6434
10
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6435
10
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6436
10
                             tmp_rowset_ref_count_keys_to_delete =
6437
10
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6438
10
                             mark_keys_to_process = std::move(mark_keys_to_process),
6439
10
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6440
10
            if (!mark_keys_to_process.empty() &&
6441
10
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6442
10
                                                                  mark_keys_to_process) != 0) {
6443
10
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6444
10
                             << instance_id_;
6445
10
                return;
6446
10
            }
6447
10
            if (!abort_keys_to_process.empty() &&
6448
10
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6449
10
                                                                      false) != 0) {
6450
10
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6451
10
                             << instance_id_;
6452
10
                return;
6453
10
            }
6454
10
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6455
10
                                   metrics_context) != 0) {
6456
10
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6457
10
                return;
6458
10
            }
6459
10
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6460
10
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6461
10
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6462
10
                                 << rs.ShortDebugString();
6463
10
                    return;
6464
10
                }
6465
10
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6466
10
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6467
10
                                 << rs.ShortDebugString();
6468
10
                    return;
6469
10
                }
6470
10
            }
6471
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6472
10
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6473
10
                return;
6474
10
            }
6475
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6476
10
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6477
10
                return;
6478
10
            }
6479
10
            num_recycled += tmp_rowset_keys_to_delete.size();
6480
10
            return;
6481
10
        });
6482
10
        return 0;
6483
10
    };
6484
6485
35
    if (config::enable_recycler_stats_metrics) {
6486
0
        scan_and_statistics_tmp_rowsets();
6487
0
    }
6488
    // recycle_func and loop_done for scan and recycle
6489
35
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
6490
35
                               std::move(loop_done));
6491
6492
35
    worker_pool->stop();
6493
6494
    // Report final metrics after all concurrent tasks completed
6495
35
    segment_metrics_context_.report();
6496
35
    metrics_context.report();
6497
6498
35
    return ret;
6499
35
}
6500
6501
int InstanceRecycler::scan_and_recycle(
6502
        std::string begin, std::string_view end,
6503
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
6504
324
        std::function<int()> loop_done, std::function<bool(std::string*)> next_begin_getter) {
6505
324
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
6506
324
    int ret = 0;
6507
324
    int64_t cnt = 0;
6508
324
    int get_range_retried = 0;
6509
324
    std::string err;
6510
324
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6511
324
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6512
324
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6513
324
                  << " ret=" << ret << " err=" << err;
6514
324
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6510
36
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6511
36
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6512
36
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6513
36
                  << " ret=" << ret << " err=" << err;
6514
36
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6510
288
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6511
288
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6512
288
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6513
288
                  << " ret=" << ret << " err=" << err;
6514
288
    };
6515
6516
324
    std::unique_ptr<RangeGetIterator> it;
6517
502
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
6518
359
        if (get_range_retried > 1000) {
6519
0
            err = "txn_get exceeds max retry(1000), may not scan all keys";
6520
0
            ret = -3;
6521
0
            return ret;
6522
0
        }
6523
359
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
6524
359
        if (get_ret != 0) { // txn kv may complain "Request for future version"
6525
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
6526
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
6527
0
                         << " get_range_retried=" << get_range_retried;
6528
0
            ++get_range_retried;
6529
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6530
0
            continue; // try again
6531
0
        }
6532
359
        if (!it->has_next()) {
6533
181
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
6534
181
            break; // scan finished
6535
181
        }
6536
178
        bool begin_updated = false;
6537
178
        LOG(INFO) << "scan_and_recycle iterator key_range=[" << hex(begin) << "," << hex(end)
6538
178
                  << ") iterator->size()=" << it->size();
6539
97.6k
        while (it->has_next()) {
6540
97.4k
            ++cnt;
6541
            // recycle corresponding resources
6542
97.4k
            auto [k, v] = it->next();
6543
97.4k
            if (!it->has_next()) {
6544
172
                begin = k;
6545
172
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
6546
172
            }
6547
            // FIXME(gavin): if we want to continue scanning, the recycle_func should not return non-zero
6548
97.4k
            if (recycle_func(k, v) != 0) {
6549
4.00k
                err = "recycle_func error";
6550
4.00k
                ret = -1;
6551
4.00k
            }
6552
97.4k
            if (next_begin_getter) {
6553
4.05k
                std::string next_begin;
6554
4.05k
                if (next_begin_getter(&next_begin)) {
6555
7
                    if (next_begin > k) {
6556
7
                        begin = std::move(next_begin);
6557
7
                        begin_updated = true;
6558
7
                        VLOG_DEBUG << "scan_and_recycle updates begin to " << hex(begin)
6559
0
                                   << " after key=" << hex(k);
6560
7
                        break;
6561
7
                    }
6562
0
                    LOG_WARNING("ignore invalid next begin in scan_and_recycle")
6563
0
                            .tag("next_begin", hex(next_begin))
6564
0
                            .tag("current_key", hex(k));
6565
0
                }
6566
4.05k
            }
6567
97.4k
        }
6568
178
        if (!begin_updated) {
6569
171
            begin.push_back('\x00'); // Update to next smallest key for iteration
6570
171
        } else {
6571
7
            it.reset();
6572
7
        }
6573
6574
        // FIXME(gavin): if we want to continue scanning, the loop_done should not return non-zero
6575
        // if we want to continue scanning, the recycle_func should not return non-zero
6576
178
        if (loop_done && loop_done() != 0) {
6577
5
            err = "loop_done error";
6578
5
            ret = -1;
6579
5
        }
6580
178
    }
6581
324
    return ret;
6582
324
}
6583
6584
19
int InstanceRecycler::abort_timeout_txn() {
6585
19
    const std::string task_name = "abort_timeout_txn";
6586
19
    int64_t num_scanned = 0;
6587
19
    int64_t num_timeout = 0;
6588
19
    int64_t num_abort = 0;
6589
19
    int64_t num_advance = 0;
6590
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6591
6592
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6593
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6594
19
    std::string begin_txn_running_key;
6595
19
    std::string end_txn_running_key;
6596
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6597
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6598
6599
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
6600
6601
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6602
19
    register_recycle_task(task_name, start_time);
6603
6604
19
    DORIS_CLOUD_DEFER {
6605
19
        unregister_recycle_task(task_name);
6606
19
        int64_t cost =
6607
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6608
19
        metrics_context.finish_report();
6609
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6610
19
                .tag("instance_id", instance_id_)
6611
19
                .tag("num_scanned", num_scanned)
6612
19
                .tag("num_timeout", num_timeout)
6613
19
                .tag("num_abort", num_abort)
6614
19
                .tag("num_advance", num_advance);
6615
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6604
3
    DORIS_CLOUD_DEFER {
6605
3
        unregister_recycle_task(task_name);
6606
3
        int64_t cost =
6607
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6608
3
        metrics_context.finish_report();
6609
3
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6610
3
                .tag("instance_id", instance_id_)
6611
3
                .tag("num_scanned", num_scanned)
6612
3
                .tag("num_timeout", num_timeout)
6613
3
                .tag("num_abort", num_abort)
6614
3
                .tag("num_advance", num_advance);
6615
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6604
16
    DORIS_CLOUD_DEFER {
6605
16
        unregister_recycle_task(task_name);
6606
16
        int64_t cost =
6607
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6608
16
        metrics_context.finish_report();
6609
16
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6610
16
                .tag("instance_id", instance_id_)
6611
16
                .tag("num_scanned", num_scanned)
6612
16
                .tag("num_timeout", num_timeout)
6613
16
                .tag("num_abort", num_abort)
6614
16
                .tag("num_advance", num_advance);
6615
16
    };
6616
6617
19
    int64_t current_time =
6618
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6619
6620
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
6621
19
                                  &current_time, &metrics_context,
6622
19
                                  this](std::string_view k, std::string_view v) -> int {
6623
9
        ++num_scanned;
6624
6625
9
        std::unique_ptr<Transaction> txn;
6626
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6627
9
        if (err != TxnErrorCode::TXN_OK) {
6628
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6629
0
            return -1;
6630
0
        }
6631
9
        std::string_view k1 = k;
6632
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6633
9
        k1.remove_prefix(1); // Remove key space
6634
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6635
9
        if (decode_key(&k1, &out) != 0) {
6636
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6637
0
            return -1;
6638
0
        }
6639
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6640
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6641
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6642
        // Update txn_info
6643
9
        std::string txn_inf_key, txn_inf_val;
6644
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6645
9
        err = txn->get(txn_inf_key, &txn_inf_val);
6646
9
        if (err != TxnErrorCode::TXN_OK) {
6647
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6648
0
            return -1;
6649
0
        }
6650
9
        TxnInfoPB txn_info;
6651
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
6652
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6653
0
            return -1;
6654
0
        }
6655
6656
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6657
3
            txn.reset();
6658
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6659
3
            std::shared_ptr<TxnLazyCommitTask> task =
6660
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6661
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6662
3
            if (ret.first != MetaServiceCode::OK) {
6663
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6664
0
                             << "msg=" << ret.second;
6665
0
                return -1;
6666
0
            }
6667
3
            ++num_advance;
6668
3
            return 0;
6669
6
        } else {
6670
6
            TxnRunningPB txn_running_pb;
6671
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6672
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6673
0
                return -1;
6674
0
            }
6675
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6676
4
                return 0;
6677
4
            }
6678
2
            ++num_timeout;
6679
6680
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6681
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6682
2
            txn_info.set_finish_time(current_time);
6683
2
            txn_info.set_reason("timeout");
6684
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6685
2
            txn_inf_val.clear();
6686
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6687
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6688
0
                return -1;
6689
0
            }
6690
2
            txn->put(txn_inf_key, txn_inf_val);
6691
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6692
            // Put recycle txn key
6693
2
            std::string recyc_txn_key, recyc_txn_val;
6694
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6695
2
            RecycleTxnPB recycle_txn_pb;
6696
2
            recycle_txn_pb.set_creation_time(current_time);
6697
2
            recycle_txn_pb.set_label(txn_info.label());
6698
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6699
0
                LOG_WARNING("failed to serialize txn recycle info")
6700
0
                        .tag("key", hex(k))
6701
0
                        .tag("db_id", db_id)
6702
0
                        .tag("txn_id", txn_id);
6703
0
                return -1;
6704
0
            }
6705
2
            txn->put(recyc_txn_key, recyc_txn_val);
6706
            // Remove txn running key
6707
2
            txn->remove(k);
6708
2
            err = txn->commit();
6709
2
            if (err != TxnErrorCode::TXN_OK) {
6710
0
                LOG_WARNING("failed to commit txn err={}", err)
6711
0
                        .tag("key", hex(k))
6712
0
                        .tag("db_id", db_id)
6713
0
                        .tag("txn_id", txn_id);
6714
0
                return -1;
6715
0
            }
6716
2
            metrics_context.total_recycled_num = ++num_abort;
6717
2
            metrics_context.report();
6718
2
        }
6719
6720
2
        return 0;
6721
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6622
3
                                  this](std::string_view k, std::string_view v) -> int {
6623
3
        ++num_scanned;
6624
6625
3
        std::unique_ptr<Transaction> txn;
6626
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6627
3
        if (err != TxnErrorCode::TXN_OK) {
6628
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6629
0
            return -1;
6630
0
        }
6631
3
        std::string_view k1 = k;
6632
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6633
3
        k1.remove_prefix(1); // Remove key space
6634
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6635
3
        if (decode_key(&k1, &out) != 0) {
6636
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6637
0
            return -1;
6638
0
        }
6639
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6640
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6641
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6642
        // Update txn_info
6643
3
        std::string txn_inf_key, txn_inf_val;
6644
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6645
3
        err = txn->get(txn_inf_key, &txn_inf_val);
6646
3
        if (err != TxnErrorCode::TXN_OK) {
6647
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6648
0
            return -1;
6649
0
        }
6650
3
        TxnInfoPB txn_info;
6651
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
6652
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6653
0
            return -1;
6654
0
        }
6655
6656
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6657
3
            txn.reset();
6658
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6659
3
            std::shared_ptr<TxnLazyCommitTask> task =
6660
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6661
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6662
3
            if (ret.first != MetaServiceCode::OK) {
6663
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6664
0
                             << "msg=" << ret.second;
6665
0
                return -1;
6666
0
            }
6667
3
            ++num_advance;
6668
3
            return 0;
6669
3
        } else {
6670
0
            TxnRunningPB txn_running_pb;
6671
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6672
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6673
0
                return -1;
6674
0
            }
6675
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6676
0
                return 0;
6677
0
            }
6678
0
            ++num_timeout;
6679
6680
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6681
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6682
0
            txn_info.set_finish_time(current_time);
6683
0
            txn_info.set_reason("timeout");
6684
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6685
0
            txn_inf_val.clear();
6686
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6687
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6688
0
                return -1;
6689
0
            }
6690
0
            txn->put(txn_inf_key, txn_inf_val);
6691
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6692
            // Put recycle txn key
6693
0
            std::string recyc_txn_key, recyc_txn_val;
6694
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6695
0
            RecycleTxnPB recycle_txn_pb;
6696
0
            recycle_txn_pb.set_creation_time(current_time);
6697
0
            recycle_txn_pb.set_label(txn_info.label());
6698
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6699
0
                LOG_WARNING("failed to serialize txn recycle info")
6700
0
                        .tag("key", hex(k))
6701
0
                        .tag("db_id", db_id)
6702
0
                        .tag("txn_id", txn_id);
6703
0
                return -1;
6704
0
            }
6705
0
            txn->put(recyc_txn_key, recyc_txn_val);
6706
            // Remove txn running key
6707
0
            txn->remove(k);
6708
0
            err = txn->commit();
6709
0
            if (err != TxnErrorCode::TXN_OK) {
6710
0
                LOG_WARNING("failed to commit txn err={}", err)
6711
0
                        .tag("key", hex(k))
6712
0
                        .tag("db_id", db_id)
6713
0
                        .tag("txn_id", txn_id);
6714
0
                return -1;
6715
0
            }
6716
0
            metrics_context.total_recycled_num = ++num_abort;
6717
0
            metrics_context.report();
6718
0
        }
6719
6720
0
        return 0;
6721
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6622
6
                                  this](std::string_view k, std::string_view v) -> int {
6623
6
        ++num_scanned;
6624
6625
6
        std::unique_ptr<Transaction> txn;
6626
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6627
6
        if (err != TxnErrorCode::TXN_OK) {
6628
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6629
0
            return -1;
6630
0
        }
6631
6
        std::string_view k1 = k;
6632
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6633
6
        k1.remove_prefix(1); // Remove key space
6634
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6635
6
        if (decode_key(&k1, &out) != 0) {
6636
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6637
0
            return -1;
6638
0
        }
6639
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6640
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6641
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6642
        // Update txn_info
6643
6
        std::string txn_inf_key, txn_inf_val;
6644
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6645
6
        err = txn->get(txn_inf_key, &txn_inf_val);
6646
6
        if (err != TxnErrorCode::TXN_OK) {
6647
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6648
0
            return -1;
6649
0
        }
6650
6
        TxnInfoPB txn_info;
6651
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
6652
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6653
0
            return -1;
6654
0
        }
6655
6656
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6657
0
            txn.reset();
6658
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6659
0
            std::shared_ptr<TxnLazyCommitTask> task =
6660
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6661
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6662
0
            if (ret.first != MetaServiceCode::OK) {
6663
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6664
0
                             << "msg=" << ret.second;
6665
0
                return -1;
6666
0
            }
6667
0
            ++num_advance;
6668
0
            return 0;
6669
6
        } else {
6670
6
            TxnRunningPB txn_running_pb;
6671
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6672
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6673
0
                return -1;
6674
0
            }
6675
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6676
4
                return 0;
6677
4
            }
6678
2
            ++num_timeout;
6679
6680
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6681
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6682
2
            txn_info.set_finish_time(current_time);
6683
2
            txn_info.set_reason("timeout");
6684
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6685
2
            txn_inf_val.clear();
6686
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6687
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6688
0
                return -1;
6689
0
            }
6690
2
            txn->put(txn_inf_key, txn_inf_val);
6691
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6692
            // Put recycle txn key
6693
2
            std::string recyc_txn_key, recyc_txn_val;
6694
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6695
2
            RecycleTxnPB recycle_txn_pb;
6696
2
            recycle_txn_pb.set_creation_time(current_time);
6697
2
            recycle_txn_pb.set_label(txn_info.label());
6698
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6699
0
                LOG_WARNING("failed to serialize txn recycle info")
6700
0
                        .tag("key", hex(k))
6701
0
                        .tag("db_id", db_id)
6702
0
                        .tag("txn_id", txn_id);
6703
0
                return -1;
6704
0
            }
6705
2
            txn->put(recyc_txn_key, recyc_txn_val);
6706
            // Remove txn running key
6707
2
            txn->remove(k);
6708
2
            err = txn->commit();
6709
2
            if (err != TxnErrorCode::TXN_OK) {
6710
0
                LOG_WARNING("failed to commit txn err={}", err)
6711
0
                        .tag("key", hex(k))
6712
0
                        .tag("db_id", db_id)
6713
0
                        .tag("txn_id", txn_id);
6714
0
                return -1;
6715
0
            }
6716
2
            metrics_context.total_recycled_num = ++num_abort;
6717
2
            metrics_context.report();
6718
2
        }
6719
6720
2
        return 0;
6721
6
    };
6722
6723
19
    if (config::enable_recycler_stats_metrics) {
6724
0
        scan_and_statistics_abort_timeout_txn();
6725
0
    }
6726
    // recycle_func and loop_done for scan and recycle
6727
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
6728
19
                            std::move(handle_txn_running_kv));
6729
19
}
6730
6731
19
int InstanceRecycler::recycle_expired_txn_label() {
6732
19
    const std::string task_name = "recycle_expired_txn_label";
6733
19
    int64_t num_scanned = 0;
6734
19
    int64_t num_expired = 0;
6735
19
    std::atomic_long num_recycled = 0;
6736
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6737
19
    int ret = 0;
6738
6739
19
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
6740
19
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6741
19
    std::string begin_recycle_txn_key;
6742
19
    std::string end_recycle_txn_key;
6743
19
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
6744
19
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
6745
19
    std::vector<std::string> recycle_txn_info_keys;
6746
6747
19
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
6748
6749
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6750
19
    register_recycle_task(task_name, start_time);
6751
19
    DORIS_CLOUD_DEFER {
6752
19
        unregister_recycle_task(task_name);
6753
19
        int64_t cost =
6754
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6755
19
        metrics_context.finish_report();
6756
19
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6757
19
                .tag("instance_id", instance_id_)
6758
19
                .tag("num_scanned", num_scanned)
6759
19
                .tag("num_expired", num_expired)
6760
19
                .tag("num_recycled", num_recycled);
6761
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6751
1
    DORIS_CLOUD_DEFER {
6752
1
        unregister_recycle_task(task_name);
6753
1
        int64_t cost =
6754
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6755
1
        metrics_context.finish_report();
6756
1
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6757
1
                .tag("instance_id", instance_id_)
6758
1
                .tag("num_scanned", num_scanned)
6759
1
                .tag("num_expired", num_expired)
6760
1
                .tag("num_recycled", num_recycled);
6761
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6751
18
    DORIS_CLOUD_DEFER {
6752
18
        unregister_recycle_task(task_name);
6753
18
        int64_t cost =
6754
18
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6755
18
        metrics_context.finish_report();
6756
18
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6757
18
                .tag("instance_id", instance_id_)
6758
18
                .tag("num_scanned", num_scanned)
6759
18
                .tag("num_expired", num_expired)
6760
18
                .tag("num_recycled", num_recycled);
6761
18
    };
6762
6763
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6764
6765
19
    SyncExecutor<int> concurrent_delete_executor(
6766
19
            _thread_pool_group.s3_producer_pool,
6767
19
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
6768
23.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
6768
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
6768
23.0k
            [](const int& ret) { return ret != 0; });
6769
6770
19
    int64_t current_time_ms =
6771
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6772
6773
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6774
30.0k
        ++num_scanned;
6775
30.0k
        RecycleTxnPB recycle_txn_pb;
6776
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6777
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6778
0
            return -1;
6779
0
        }
6780
30.0k
        if ((config::force_immediate_recycle) ||
6781
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6782
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6783
30.0k
             current_time_ms)) {
6784
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6785
23.0k
            num_expired++;
6786
23.0k
            recycle_txn_info_keys.emplace_back(k);
6787
23.0k
        }
6788
30.0k
        return 0;
6789
30.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6773
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6774
1
        ++num_scanned;
6775
1
        RecycleTxnPB recycle_txn_pb;
6776
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6777
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6778
0
            return -1;
6779
0
        }
6780
1
        if ((config::force_immediate_recycle) ||
6781
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6782
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6783
1
             current_time_ms)) {
6784
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6785
1
            num_expired++;
6786
1
            recycle_txn_info_keys.emplace_back(k);
6787
1
        }
6788
1
        return 0;
6789
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6773
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6774
30.0k
        ++num_scanned;
6775
30.0k
        RecycleTxnPB recycle_txn_pb;
6776
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6777
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6778
0
            return -1;
6779
0
        }
6780
30.0k
        if ((config::force_immediate_recycle) ||
6781
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6782
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6783
30.0k
             current_time_ms)) {
6784
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6785
23.0k
            num_expired++;
6786
23.0k
            recycle_txn_info_keys.emplace_back(k);
6787
23.0k
        }
6788
30.0k
        return 0;
6789
30.0k
    };
6790
6791
    // int 0 for success, 1 for conflict, -1 for error
6792
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6793
23.0k
        std::string_view k1 = k;
6794
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6795
23.0k
        k1.remove_prefix(1); // Remove key space
6796
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6797
23.0k
        int ret = decode_key(&k1, &out);
6798
23.0k
        if (ret != 0) {
6799
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6800
0
            return -1;
6801
0
        }
6802
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6803
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6804
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6805
23.0k
        std::unique_ptr<Transaction> txn;
6806
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6807
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6808
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6809
0
            return -1;
6810
0
        }
6811
        // Remove txn index kv
6812
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6813
23.0k
        txn->remove(index_key);
6814
        // Remove txn info kv
6815
23.0k
        std::string info_key, info_val;
6816
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6817
23.0k
        err = txn->get(info_key, &info_val);
6818
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6819
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6820
0
            return -1;
6821
0
        }
6822
23.0k
        TxnInfoPB txn_info;
6823
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6824
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6825
0
            return -1;
6826
0
        }
6827
23.0k
        txn->remove(info_key);
6828
        // Remove sub txn index kvs
6829
23.0k
        std::vector<std::string> sub_txn_index_keys;
6830
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6831
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6832
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6833
22.9k
        }
6834
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6835
22.9k
            txn->remove(sub_txn_index_key);
6836
22.9k
        }
6837
        // Update txn label
6838
23.0k
        std::string label_key, label_val;
6839
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6840
23.0k
        err = txn->get(label_key, &label_val);
6841
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6842
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6843
0
                         << " err=" << err;
6844
0
            return -1;
6845
0
        }
6846
23.0k
        TxnLabelPB txn_label;
6847
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6848
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6849
0
            return -1;
6850
0
        }
6851
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6852
23.0k
        if (it != txn_label.txn_ids().end()) {
6853
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6854
23.0k
        }
6855
23.0k
        if (txn_label.txn_ids().empty()) {
6856
23.0k
            txn->remove(label_key);
6857
23.0k
            TEST_SYNC_POINT_CALLBACK(
6858
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6859
23.0k
        } else {
6860
74
            if (!txn_label.SerializeToString(&label_val)) {
6861
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6862
0
                return -1;
6863
0
            }
6864
74
            TEST_SYNC_POINT_CALLBACK(
6865
74
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6866
74
            txn->atomic_set_ver_value(label_key, label_val);
6867
74
            TEST_SYNC_POINT_CALLBACK(
6868
74
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6869
74
        }
6870
        // Remove recycle txn kv
6871
23.0k
        txn->remove(k);
6872
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6873
23.0k
        err = txn->commit();
6874
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6875
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6876
62
                TEST_SYNC_POINT_CALLBACK(
6877
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6878
                // log the txn_id and label
6879
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6880
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6881
62
                             << " txn_label=" << txn_info.label();
6882
62
                return 1;
6883
62
            }
6884
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6885
0
            return -1;
6886
62
        }
6887
23.0k
        ++num_recycled;
6888
6889
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6890
23.0k
        return 0;
6891
23.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6792
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6793
1
        std::string_view k1 = k;
6794
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6795
1
        k1.remove_prefix(1); // Remove key space
6796
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6797
1
        int ret = decode_key(&k1, &out);
6798
1
        if (ret != 0) {
6799
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6800
0
            return -1;
6801
0
        }
6802
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6803
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6804
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6805
1
        std::unique_ptr<Transaction> txn;
6806
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6807
1
        if (err != TxnErrorCode::TXN_OK) {
6808
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6809
0
            return -1;
6810
0
        }
6811
        // Remove txn index kv
6812
1
        auto index_key = txn_index_key({instance_id_, txn_id});
6813
1
        txn->remove(index_key);
6814
        // Remove txn info kv
6815
1
        std::string info_key, info_val;
6816
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6817
1
        err = txn->get(info_key, &info_val);
6818
1
        if (err != TxnErrorCode::TXN_OK) {
6819
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6820
0
            return -1;
6821
0
        }
6822
1
        TxnInfoPB txn_info;
6823
1
        if (!txn_info.ParseFromString(info_val)) {
6824
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6825
0
            return -1;
6826
0
        }
6827
1
        txn->remove(info_key);
6828
        // Remove sub txn index kvs
6829
1
        std::vector<std::string> sub_txn_index_keys;
6830
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6831
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6832
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
6833
0
        }
6834
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6835
0
            txn->remove(sub_txn_index_key);
6836
0
        }
6837
        // Update txn label
6838
1
        std::string label_key, label_val;
6839
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6840
1
        err = txn->get(label_key, &label_val);
6841
1
        if (err != TxnErrorCode::TXN_OK) {
6842
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6843
0
                         << " err=" << err;
6844
0
            return -1;
6845
0
        }
6846
1
        TxnLabelPB txn_label;
6847
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6848
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6849
0
            return -1;
6850
0
        }
6851
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6852
1
        if (it != txn_label.txn_ids().end()) {
6853
1
            txn_label.mutable_txn_ids()->erase(it);
6854
1
        }
6855
1
        if (txn_label.txn_ids().empty()) {
6856
1
            txn->remove(label_key);
6857
1
            TEST_SYNC_POINT_CALLBACK(
6858
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6859
1
        } else {
6860
0
            if (!txn_label.SerializeToString(&label_val)) {
6861
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6862
0
                return -1;
6863
0
            }
6864
0
            TEST_SYNC_POINT_CALLBACK(
6865
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6866
0
            txn->atomic_set_ver_value(label_key, label_val);
6867
0
            TEST_SYNC_POINT_CALLBACK(
6868
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6869
0
        }
6870
        // Remove recycle txn kv
6871
1
        txn->remove(k);
6872
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6873
1
        err = txn->commit();
6874
1
        if (err != TxnErrorCode::TXN_OK) {
6875
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
6876
0
                TEST_SYNC_POINT_CALLBACK(
6877
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6878
                // log the txn_id and label
6879
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6880
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6881
0
                             << " txn_label=" << txn_info.label();
6882
0
                return 1;
6883
0
            }
6884
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6885
0
            return -1;
6886
0
        }
6887
1
        ++num_recycled;
6888
6889
1
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6890
1
        return 0;
6891
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6792
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6793
23.0k
        std::string_view k1 = k;
6794
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6795
23.0k
        k1.remove_prefix(1); // Remove key space
6796
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6797
23.0k
        int ret = decode_key(&k1, &out);
6798
23.0k
        if (ret != 0) {
6799
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6800
0
            return -1;
6801
0
        }
6802
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6803
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6804
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6805
23.0k
        std::unique_ptr<Transaction> txn;
6806
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6807
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6808
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6809
0
            return -1;
6810
0
        }
6811
        // Remove txn index kv
6812
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6813
23.0k
        txn->remove(index_key);
6814
        // Remove txn info kv
6815
23.0k
        std::string info_key, info_val;
6816
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6817
23.0k
        err = txn->get(info_key, &info_val);
6818
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6819
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6820
0
            return -1;
6821
0
        }
6822
23.0k
        TxnInfoPB txn_info;
6823
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6824
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6825
0
            return -1;
6826
0
        }
6827
23.0k
        txn->remove(info_key);
6828
        // Remove sub txn index kvs
6829
23.0k
        std::vector<std::string> sub_txn_index_keys;
6830
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6831
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6832
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6833
22.9k
        }
6834
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6835
22.9k
            txn->remove(sub_txn_index_key);
6836
22.9k
        }
6837
        // Update txn label
6838
23.0k
        std::string label_key, label_val;
6839
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6840
23.0k
        err = txn->get(label_key, &label_val);
6841
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6842
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6843
0
                         << " err=" << err;
6844
0
            return -1;
6845
0
        }
6846
23.0k
        TxnLabelPB txn_label;
6847
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6848
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6849
0
            return -1;
6850
0
        }
6851
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6852
23.0k
        if (it != txn_label.txn_ids().end()) {
6853
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6854
23.0k
        }
6855
23.0k
        if (txn_label.txn_ids().empty()) {
6856
23.0k
            txn->remove(label_key);
6857
23.0k
            TEST_SYNC_POINT_CALLBACK(
6858
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6859
23.0k
        } else {
6860
74
            if (!txn_label.SerializeToString(&label_val)) {
6861
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6862
0
                return -1;
6863
0
            }
6864
74
            TEST_SYNC_POINT_CALLBACK(
6865
74
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6866
74
            txn->atomic_set_ver_value(label_key, label_val);
6867
74
            TEST_SYNC_POINT_CALLBACK(
6868
74
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6869
74
        }
6870
        // Remove recycle txn kv
6871
23.0k
        txn->remove(k);
6872
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6873
23.0k
        err = txn->commit();
6874
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6875
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6876
62
                TEST_SYNC_POINT_CALLBACK(
6877
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6878
                // log the txn_id and label
6879
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6880
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6881
62
                             << " txn_label=" << txn_info.label();
6882
62
                return 1;
6883
62
            }
6884
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6885
0
            return -1;
6886
62
        }
6887
23.0k
        ++num_recycled;
6888
6889
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6890
23.0k
        return 0;
6891
23.0k
    };
6892
6893
19
    auto loop_done = [&]() -> int {
6894
10
        DORIS_CLOUD_DEFER {
6895
10
            recycle_txn_info_keys.clear();
6896
10
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6894
1
        DORIS_CLOUD_DEFER {
6895
1
            recycle_txn_info_keys.clear();
6896
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6894
9
        DORIS_CLOUD_DEFER {
6895
9
            recycle_txn_info_keys.clear();
6896
9
        };
6897
10
        TEST_SYNC_POINT_CALLBACK(
6898
10
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6899
10
                &recycle_txn_info_keys);
6900
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6901
23.0k
            concurrent_delete_executor.add([&]() {
6902
23.0k
                int ret = delete_recycle_txn_kv(k);
6903
23.0k
                if (ret == 1) {
6904
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6905
54
                    for (int i = 1; i <= max_retry; ++i) {
6906
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6907
54
                        ret = delete_recycle_txn_kv(k);
6908
                        // clang-format off
6909
54
                        TEST_SYNC_POINT_CALLBACK(
6910
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6911
                        // clang-format off
6912
54
                        if (ret != 1) {
6913
18
                            break;
6914
18
                        }
6915
                        // random sleep 0-100 ms to retry
6916
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6917
36
                    }
6918
18
                }
6919
23.0k
                if (ret != 0) {
6920
9
                    LOG_WARNING("failed to delete recycle txn kv")
6921
9
                            .tag("instance id", instance_id_)
6922
9
                            .tag("key", hex(k));
6923
9
                    return -1;
6924
9
                }
6925
23.0k
                return 0;
6926
23.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6901
1
            concurrent_delete_executor.add([&]() {
6902
1
                int ret = delete_recycle_txn_kv(k);
6903
1
                if (ret == 1) {
6904
0
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6905
0
                    for (int i = 1; i <= max_retry; ++i) {
6906
0
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6907
0
                        ret = delete_recycle_txn_kv(k);
6908
                        // clang-format off
6909
0
                        TEST_SYNC_POINT_CALLBACK(
6910
0
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6911
                        // clang-format off
6912
0
                        if (ret != 1) {
6913
0
                            break;
6914
0
                        }
6915
                        // random sleep 0-100 ms to retry
6916
0
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6917
0
                    }
6918
0
                }
6919
1
                if (ret != 0) {
6920
0
                    LOG_WARNING("failed to delete recycle txn kv")
6921
0
                            .tag("instance id", instance_id_)
6922
0
                            .tag("key", hex(k));
6923
0
                    return -1;
6924
0
                }
6925
1
                return 0;
6926
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6901
23.0k
            concurrent_delete_executor.add([&]() {
6902
23.0k
                int ret = delete_recycle_txn_kv(k);
6903
23.0k
                if (ret == 1) {
6904
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6905
54
                    for (int i = 1; i <= max_retry; ++i) {
6906
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6907
54
                        ret = delete_recycle_txn_kv(k);
6908
                        // clang-format off
6909
54
                        TEST_SYNC_POINT_CALLBACK(
6910
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6911
                        // clang-format off
6912
54
                        if (ret != 1) {
6913
18
                            break;
6914
18
                        }
6915
                        // random sleep 0-100 ms to retry
6916
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6917
36
                    }
6918
18
                }
6919
23.0k
                if (ret != 0) {
6920
9
                    LOG_WARNING("failed to delete recycle txn kv")
6921
9
                            .tag("instance id", instance_id_)
6922
9
                            .tag("key", hex(k));
6923
9
                    return -1;
6924
9
                }
6925
23.0k
                return 0;
6926
23.0k
            });
6927
23.0k
        }
6928
10
        bool finished = true;
6929
10
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6930
23.0k
        for (int r : rets) {
6931
23.0k
            if (r != 0) {
6932
9
                ret = -1;
6933
9
            }
6934
23.0k
        }
6935
6936
10
        ret = finished ? ret : -1;
6937
6938
        // Update metrics after all concurrent tasks completed
6939
10
        metrics_context.total_recycled_num = num_recycled.load();
6940
10
        metrics_context.report();
6941
6942
10
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6943
6944
10
        if (ret != 0) {
6945
3
            LOG_WARNING("recycle txn kv ret!=0")
6946
3
                    .tag("finished", finished)
6947
3
                    .tag("ret", ret)
6948
3
                    .tag("instance_id", instance_id_);
6949
3
            return ret;
6950
3
        }
6951
7
        return ret;
6952
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6893
1
    auto loop_done = [&]() -> int {
6894
1
        DORIS_CLOUD_DEFER {
6895
1
            recycle_txn_info_keys.clear();
6896
1
        };
6897
1
        TEST_SYNC_POINT_CALLBACK(
6898
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6899
1
                &recycle_txn_info_keys);
6900
1
        for (const auto& k : recycle_txn_info_keys) {
6901
1
            concurrent_delete_executor.add([&]() {
6902
1
                int ret = delete_recycle_txn_kv(k);
6903
1
                if (ret == 1) {
6904
1
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6905
1
                    for (int i = 1; i <= max_retry; ++i) {
6906
1
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6907
1
                        ret = delete_recycle_txn_kv(k);
6908
                        // clang-format off
6909
1
                        TEST_SYNC_POINT_CALLBACK(
6910
1
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6911
                        // clang-format off
6912
1
                        if (ret != 1) {
6913
1
                            break;
6914
1
                        }
6915
                        // random sleep 0-100 ms to retry
6916
1
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6917
1
                    }
6918
1
                }
6919
1
                if (ret != 0) {
6920
1
                    LOG_WARNING("failed to delete recycle txn kv")
6921
1
                            .tag("instance id", instance_id_)
6922
1
                            .tag("key", hex(k));
6923
1
                    return -1;
6924
1
                }
6925
1
                return 0;
6926
1
            });
6927
1
        }
6928
1
        bool finished = true;
6929
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6930
1
        for (int r : rets) {
6931
1
            if (r != 0) {
6932
0
                ret = -1;
6933
0
            }
6934
1
        }
6935
6936
1
        ret = finished ? ret : -1;
6937
6938
        // Update metrics after all concurrent tasks completed
6939
1
        metrics_context.total_recycled_num = num_recycled.load();
6940
1
        metrics_context.report();
6941
6942
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6943
6944
1
        if (ret != 0) {
6945
0
            LOG_WARNING("recycle txn kv ret!=0")
6946
0
                    .tag("finished", finished)
6947
0
                    .tag("ret", ret)
6948
0
                    .tag("instance_id", instance_id_);
6949
0
            return ret;
6950
0
        }
6951
1
        return ret;
6952
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6893
9
    auto loop_done = [&]() -> int {
6894
9
        DORIS_CLOUD_DEFER {
6895
9
            recycle_txn_info_keys.clear();
6896
9
        };
6897
9
        TEST_SYNC_POINT_CALLBACK(
6898
9
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6899
9
                &recycle_txn_info_keys);
6900
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6901
23.0k
            concurrent_delete_executor.add([&]() {
6902
23.0k
                int ret = delete_recycle_txn_kv(k);
6903
23.0k
                if (ret == 1) {
6904
23.0k
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6905
23.0k
                    for (int i = 1; i <= max_retry; ++i) {
6906
23.0k
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6907
23.0k
                        ret = delete_recycle_txn_kv(k);
6908
                        // clang-format off
6909
23.0k
                        TEST_SYNC_POINT_CALLBACK(
6910
23.0k
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6911
                        // clang-format off
6912
23.0k
                        if (ret != 1) {
6913
23.0k
                            break;
6914
23.0k
                        }
6915
                        // random sleep 0-100 ms to retry
6916
23.0k
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6917
23.0k
                    }
6918
23.0k
                }
6919
23.0k
                if (ret != 0) {
6920
23.0k
                    LOG_WARNING("failed to delete recycle txn kv")
6921
23.0k
                            .tag("instance id", instance_id_)
6922
23.0k
                            .tag("key", hex(k));
6923
23.0k
                    return -1;
6924
23.0k
                }
6925
23.0k
                return 0;
6926
23.0k
            });
6927
23.0k
        }
6928
9
        bool finished = true;
6929
9
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6930
23.0k
        for (int r : rets) {
6931
23.0k
            if (r != 0) {
6932
9
                ret = -1;
6933
9
            }
6934
23.0k
        }
6935
6936
9
        ret = finished ? ret : -1;
6937
6938
        // Update metrics after all concurrent tasks completed
6939
9
        metrics_context.total_recycled_num = num_recycled.load();
6940
9
        metrics_context.report();
6941
6942
9
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6943
6944
9
        if (ret != 0) {
6945
3
            LOG_WARNING("recycle txn kv ret!=0")
6946
3
                    .tag("finished", finished)
6947
3
                    .tag("ret", ret)
6948
3
                    .tag("instance_id", instance_id_);
6949
3
            return ret;
6950
3
        }
6951
6
        return ret;
6952
9
    };
6953
6954
19
    if (config::enable_recycler_stats_metrics) {
6955
0
        scan_and_statistics_expired_txn_label();
6956
0
    }
6957
    // recycle_func and loop_done for scan and recycle
6958
19
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
6959
19
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
6960
19
}
6961
6962
struct CopyJobIdTuple {
6963
    std::string instance_id;
6964
    std::string stage_id;
6965
    long table_id;
6966
    std::string copy_id;
6967
    std::string stage_path;
6968
};
6969
struct BatchObjStoreAccessor {
6970
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
6971
                          TxnKv* txn_kv)
6972
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
6973
3
    ~BatchObjStoreAccessor() {
6974
3
        if (!paths_.empty()) {
6975
3
            consume();
6976
3
        }
6977
3
    }
6978
6979
    /**
6980
    * To implicitely do batch work and submit the batch delete task to s3
6981
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
6982
    *
6983
    * @param copy_job The protubuf struct consists of the copy job files.
6984
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
6985
    *            it would last until we finish the delete task, here we need pass one string value
6986
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
6987
    */
6988
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
6989
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
6990
5
        auto& file_keys = copy_file_keys_[key];
6991
5
        file_keys.log_trace =
6992
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
6993
5
                            instance_id, stage_id, table_id, copy_id, path);
6994
5
        std::string_view log_trace = file_keys.log_trace;
6995
2.03k
        for (const auto& file : copy_job.object_files()) {
6996
2.03k
            auto relative_path = file.relative_path();
6997
2.03k
            paths_.push_back(relative_path);
6998
2.03k
            file_keys.keys.push_back(copy_file_key(
6999
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
7000
2.03k
            LOG_INFO(log_trace)
7001
2.03k
                    .tag("relative_path", relative_path)
7002
2.03k
                    .tag("batch_count", batch_count_);
7003
2.03k
        }
7004
5
        LOG_INFO(log_trace)
7005
5
                .tag("objects_num", copy_job.object_files().size())
7006
5
                .tag("batch_count", batch_count_);
7007
        // 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
7008
        // recommend using delete objects when objects num is less than 10)
7009
5
        if (paths_.size() < 1000) {
7010
3
            return;
7011
3
        }
7012
2
        consume();
7013
2
    }
7014
7015
private:
7016
5
    void consume() {
7017
5
        DORIS_CLOUD_DEFER {
7018
5
            paths_.clear();
7019
5
            copy_file_keys_.clear();
7020
5
            batch_count_++;
7021
7022
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
7023
5
                        batch_count_);
7024
5
        };
7025
7026
5
        StopWatch sw;
7027
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
7028
5
        if (0 != accessor_->delete_files(paths_)) {
7029
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
7030
2
                        paths_.size(), batch_count_, sw.elapsed_us());
7031
2
            return;
7032
2
        }
7033
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
7034
3
                    paths_.size(), batch_count_, sw.elapsed_us());
7035
        // delete fdb's keys
7036
3
        for (auto& file_keys : copy_file_keys_) {
7037
3
            auto& [log_trace, keys] = file_keys.second;
7038
3
            std::unique_ptr<Transaction> txn;
7039
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
7040
0
                LOG(WARNING) << "failed to create txn";
7041
0
                continue;
7042
0
            }
7043
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7044
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7045
            // limited, should not cause the txn commit failed.
7046
1.02k
            for (const auto& key : keys) {
7047
1.02k
                txn->remove(key);
7048
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
7049
1.02k
            }
7050
3
            txn->remove(file_keys.first);
7051
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
7052
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
7053
0
                continue;
7054
0
            }
7055
3
        }
7056
3
    }
7057
    std::shared_ptr<StorageVaultAccessor> accessor_;
7058
    // the path of the s3 files to be deleted
7059
    std::vector<std::string> paths_;
7060
    struct CopyFiles {
7061
        std::string log_trace;
7062
        std::vector<std::string> keys;
7063
    };
7064
    // pair<std::string, std::vector<std::string>>
7065
    // first: instance_id_ stage_id table_id query_id
7066
    // second: keys to be deleted
7067
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
7068
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
7069
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
7070
    // which can together uniquely identifies different tasks for tracing log
7071
    uint64_t& batch_count_;
7072
    TxnKv* txn_kv_;
7073
};
7074
7075
13
int InstanceRecycler::recycle_copy_jobs() {
7076
13
    int64_t num_scanned = 0;
7077
13
    int64_t num_finished = 0;
7078
13
    int64_t num_expired = 0;
7079
13
    int64_t num_recycled = 0;
7080
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
7081
13
    uint64_t batch_count = 0;
7082
13
    const std::string task_name = "recycle_copy_jobs";
7083
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7084
7085
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
7086
7087
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7088
13
    register_recycle_task(task_name, start_time);
7089
7090
13
    DORIS_CLOUD_DEFER {
7091
13
        unregister_recycle_task(task_name);
7092
13
        int64_t cost =
7093
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7094
13
        metrics_context.finish_report();
7095
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7096
13
                .tag("instance_id", instance_id_)
7097
13
                .tag("num_scanned", num_scanned)
7098
13
                .tag("num_finished", num_finished)
7099
13
                .tag("num_expired", num_expired)
7100
13
                .tag("num_recycled", num_recycled);
7101
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
7090
13
    DORIS_CLOUD_DEFER {
7091
13
        unregister_recycle_task(task_name);
7092
13
        int64_t cost =
7093
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7094
13
        metrics_context.finish_report();
7095
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7096
13
                .tag("instance_id", instance_id_)
7097
13
                .tag("num_scanned", num_scanned)
7098
13
                .tag("num_finished", num_finished)
7099
13
                .tag("num_expired", num_expired)
7100
13
                .tag("num_recycled", num_recycled);
7101
13
    };
7102
7103
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7104
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7105
13
    std::string key0;
7106
13
    std::string key1;
7107
13
    copy_job_key(key_info0, &key0);
7108
13
    copy_job_key(key_info1, &key1);
7109
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
7110
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
7111
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
7112
16
                         this](std::string_view k, std::string_view v) -> int {
7113
16
        ++num_scanned;
7114
16
        CopyJobPB copy_job;
7115
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7116
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7117
0
            return -1;
7118
0
        }
7119
7120
        // decode copy job key
7121
16
        auto k1 = k;
7122
16
        k1.remove_prefix(1);
7123
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7124
16
        decode_key(&k1, &out);
7125
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7126
        // -> CopyJobPB
7127
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7128
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7129
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7130
7131
16
        bool check_storage = true;
7132
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7133
12
            ++num_finished;
7134
7135
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7136
7
                auto it = stage_accessor_map.find(stage_id);
7137
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7138
7
                std::string_view path;
7139
7
                if (it != stage_accessor_map.end()) {
7140
2
                    accessor = it->second;
7141
5
                } else {
7142
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7143
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7144
5
                                                      &inner_accessor);
7145
5
                    if (ret < 0) { // error
7146
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7147
0
                        return -1;
7148
5
                    } else if (ret == 0) {
7149
3
                        path = inner_accessor->uri();
7150
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7151
3
                                inner_accessor, batch_count, txn_kv_.get());
7152
3
                        stage_accessor_map.emplace(stage_id, accessor);
7153
3
                    } else { // stage not found, skip check storage
7154
2
                        check_storage = false;
7155
2
                    }
7156
5
                }
7157
7
                if (check_storage) {
7158
                    // TODO delete objects with key and etag is not supported
7159
5
                    accessor->add(std::move(copy_job), std::string(k),
7160
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7161
5
                    return 0;
7162
5
                }
7163
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7164
5
                int64_t current_time =
7165
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7166
5
                if (copy_job.finish_time_ms() > 0) {
7167
2
                    if (!config::force_immediate_recycle &&
7168
2
                        current_time < copy_job.finish_time_ms() +
7169
2
                                               config::copy_job_max_retention_second * 1000) {
7170
1
                        return 0;
7171
1
                    }
7172
3
                } else {
7173
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7174
3
                    if (!config::force_immediate_recycle &&
7175
3
                        current_time < copy_job.start_time_ms() +
7176
3
                                               config::copy_job_max_retention_second * 1000) {
7177
1
                        return 0;
7178
1
                    }
7179
3
                }
7180
5
            }
7181
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7182
4
            int64_t current_time =
7183
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7184
            // if copy job is timeout: delete all copy file kvs and copy job kv
7185
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7186
2
                return 0;
7187
2
            }
7188
2
            ++num_expired;
7189
2
        }
7190
7191
        // delete all copy files
7192
7
        std::vector<std::string> copy_file_keys;
7193
70
        for (auto& file : copy_job.object_files()) {
7194
70
            copy_file_keys.push_back(copy_file_key(
7195
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7196
70
        }
7197
7
        std::unique_ptr<Transaction> txn;
7198
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7199
0
            LOG(WARNING) << "failed to create txn";
7200
0
            return -1;
7201
0
        }
7202
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7203
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7204
        // limited, should not cause the txn commit failed.
7205
70
        for (const auto& key : copy_file_keys) {
7206
70
            txn->remove(key);
7207
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7208
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7209
70
                      << ", query_id=" << copy_id;
7210
70
        }
7211
7
        txn->remove(k);
7212
7
        TxnErrorCode err = txn->commit();
7213
7
        if (err != TxnErrorCode::TXN_OK) {
7214
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7215
0
            return -1;
7216
0
        }
7217
7218
7
        metrics_context.total_recycled_num = ++num_recycled;
7219
7
        metrics_context.report();
7220
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7221
7
        return 0;
7222
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
7112
16
                         this](std::string_view k, std::string_view v) -> int {
7113
16
        ++num_scanned;
7114
16
        CopyJobPB copy_job;
7115
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7116
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7117
0
            return -1;
7118
0
        }
7119
7120
        // decode copy job key
7121
16
        auto k1 = k;
7122
16
        k1.remove_prefix(1);
7123
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7124
16
        decode_key(&k1, &out);
7125
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7126
        // -> CopyJobPB
7127
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7128
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7129
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7130
7131
16
        bool check_storage = true;
7132
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7133
12
            ++num_finished;
7134
7135
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7136
7
                auto it = stage_accessor_map.find(stage_id);
7137
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7138
7
                std::string_view path;
7139
7
                if (it != stage_accessor_map.end()) {
7140
2
                    accessor = it->second;
7141
5
                } else {
7142
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7143
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7144
5
                                                      &inner_accessor);
7145
5
                    if (ret < 0) { // error
7146
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7147
0
                        return -1;
7148
5
                    } else if (ret == 0) {
7149
3
                        path = inner_accessor->uri();
7150
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7151
3
                                inner_accessor, batch_count, txn_kv_.get());
7152
3
                        stage_accessor_map.emplace(stage_id, accessor);
7153
3
                    } else { // stage not found, skip check storage
7154
2
                        check_storage = false;
7155
2
                    }
7156
5
                }
7157
7
                if (check_storage) {
7158
                    // TODO delete objects with key and etag is not supported
7159
5
                    accessor->add(std::move(copy_job), std::string(k),
7160
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7161
5
                    return 0;
7162
5
                }
7163
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7164
5
                int64_t current_time =
7165
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7166
5
                if (copy_job.finish_time_ms() > 0) {
7167
2
                    if (!config::force_immediate_recycle &&
7168
2
                        current_time < copy_job.finish_time_ms() +
7169
2
                                               config::copy_job_max_retention_second * 1000) {
7170
1
                        return 0;
7171
1
                    }
7172
3
                } else {
7173
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7174
3
                    if (!config::force_immediate_recycle &&
7175
3
                        current_time < copy_job.start_time_ms() +
7176
3
                                               config::copy_job_max_retention_second * 1000) {
7177
1
                        return 0;
7178
1
                    }
7179
3
                }
7180
5
            }
7181
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7182
4
            int64_t current_time =
7183
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7184
            // if copy job is timeout: delete all copy file kvs and copy job kv
7185
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7186
2
                return 0;
7187
2
            }
7188
2
            ++num_expired;
7189
2
        }
7190
7191
        // delete all copy files
7192
7
        std::vector<std::string> copy_file_keys;
7193
70
        for (auto& file : copy_job.object_files()) {
7194
70
            copy_file_keys.push_back(copy_file_key(
7195
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7196
70
        }
7197
7
        std::unique_ptr<Transaction> txn;
7198
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7199
0
            LOG(WARNING) << "failed to create txn";
7200
0
            return -1;
7201
0
        }
7202
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7203
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7204
        // limited, should not cause the txn commit failed.
7205
70
        for (const auto& key : copy_file_keys) {
7206
70
            txn->remove(key);
7207
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7208
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7209
70
                      << ", query_id=" << copy_id;
7210
70
        }
7211
7
        txn->remove(k);
7212
7
        TxnErrorCode err = txn->commit();
7213
7
        if (err != TxnErrorCode::TXN_OK) {
7214
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7215
0
            return -1;
7216
0
        }
7217
7218
7
        metrics_context.total_recycled_num = ++num_recycled;
7219
7
        metrics_context.report();
7220
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7221
7
        return 0;
7222
7
    };
7223
7224
13
    if (config::enable_recycler_stats_metrics) {
7225
0
        scan_and_statistics_copy_jobs();
7226
0
    }
7227
    // recycle_func and loop_done for scan and recycle
7228
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
7229
13
}
7230
7231
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
7232
                                             const StagePB::StageType& stage_type,
7233
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
7234
5
#ifdef UNIT_TEST
7235
    // In unit test, external use the same accessor as the internal stage
7236
5
    auto it = accessor_map_.find(stage_id);
7237
5
    if (it != accessor_map_.end()) {
7238
3
        *accessor = it->second;
7239
3
    } else {
7240
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
7241
2
        return 1;
7242
2
    }
7243
#else
7244
    // init s3 accessor and add to accessor map
7245
    auto stage_it =
7246
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
7247
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
7248
7249
    if (stage_it == instance_info_.stages().end()) {
7250
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
7251
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
7252
        return 1;
7253
    }
7254
7255
    const auto& object_store_info = stage_it->obj_info();
7256
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
7257
7258
    S3Conf s3_conf;
7259
    if (stage_type == StagePB::EXTERNAL) {
7260
        if (stage_access_type == StagePB::AKSK) {
7261
            auto conf = S3Conf::from_obj_store_info(object_store_info);
7262
            if (!conf) {
7263
                return -1;
7264
            }
7265
7266
            s3_conf = std::move(*conf);
7267
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
7268
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
7269
            if (!conf) {
7270
                return -1;
7271
            }
7272
7273
            s3_conf = std::move(*conf);
7274
            if (instance_info_.ram_user().has_encryption_info()) {
7275
                AkSkPair plain_ak_sk_pair;
7276
                int ret = decrypt_ak_sk_helper(
7277
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
7278
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
7279
                if (ret != 0) {
7280
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
7281
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
7282
                    return -1;
7283
                }
7284
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
7285
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
7286
            } else {
7287
                s3_conf.ak = instance_info_.ram_user().ak();
7288
                s3_conf.sk = instance_info_.ram_user().sk();
7289
            }
7290
        } else {
7291
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
7292
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
7293
            return -1;
7294
        }
7295
    } else if (stage_type == StagePB::INTERNAL) {
7296
        int idx = stoi(object_store_info.id());
7297
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7298
            LOG(WARNING) << "invalid idx: " << idx;
7299
            return -1;
7300
        }
7301
7302
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7303
        auto conf = S3Conf::from_obj_store_info(old_obj);
7304
        if (!conf) {
7305
            return -1;
7306
        }
7307
7308
        s3_conf = std::move(*conf);
7309
        s3_conf.prefix = object_store_info.prefix();
7310
    } else {
7311
        LOG(WARNING) << "unknown stage type " << stage_type;
7312
        return -1;
7313
    }
7314
7315
    std::shared_ptr<S3Accessor> s3_accessor;
7316
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
7317
    if (ret != 0) {
7318
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
7319
        return -1;
7320
    }
7321
7322
    *accessor = std::move(s3_accessor);
7323
#endif
7324
3
    return 0;
7325
5
}
7326
7327
11
int InstanceRecycler::recycle_stage() {
7328
11
    int64_t num_scanned = 0;
7329
11
    int64_t num_recycled = 0;
7330
11
    const std::string task_name = "recycle_stage";
7331
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7332
7333
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
7334
7335
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7336
11
    register_recycle_task(task_name, start_time);
7337
7338
11
    DORIS_CLOUD_DEFER {
7339
11
        unregister_recycle_task(task_name);
7340
11
        int64_t cost =
7341
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7342
11
        metrics_context.finish_report();
7343
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7344
11
                .tag("instance_id", instance_id_)
7345
11
                .tag("num_scanned", num_scanned)
7346
11
                .tag("num_recycled", num_recycled);
7347
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
7338
11
    DORIS_CLOUD_DEFER {
7339
11
        unregister_recycle_task(task_name);
7340
11
        int64_t cost =
7341
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7342
11
        metrics_context.finish_report();
7343
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7344
11
                .tag("instance_id", instance_id_)
7345
11
                .tag("num_scanned", num_scanned)
7346
11
                .tag("num_recycled", num_recycled);
7347
11
    };
7348
7349
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7350
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7351
11
    std::string key0 = recycle_stage_key(key_info0);
7352
11
    std::string key1 = recycle_stage_key(key_info1);
7353
7354
11
    std::vector<std::string_view> stage_keys;
7355
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
7356
11
                         this](std::string_view k, std::string_view v) -> int {
7357
1
        ++num_scanned;
7358
1
        RecycleStagePB recycle_stage;
7359
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7360
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7361
0
            return -1;
7362
0
        }
7363
7364
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7365
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7366
0
            LOG(WARNING) << "invalid idx: " << idx;
7367
0
            return -1;
7368
0
        }
7369
7370
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7371
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7372
1
                [&] {
7373
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7374
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7375
1
                    if (!s3_conf) {
7376
1
                        return -1;
7377
1
                    }
7378
7379
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7380
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7381
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7382
1
                    if (ret != 0) {
7383
1
                        return -1;
7384
1
                    }
7385
7386
1
                    accessor = std::move(s3_accessor);
7387
1
                    return 0;
7388
1
                }(),
7389
1
                "recycle_stage:get_accessor", &accessor);
7390
7391
1
        if (ret != 0) {
7392
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7393
0
            return ret;
7394
0
        }
7395
7396
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7397
1
                .tag("instance_id", instance_id_)
7398
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7399
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7400
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7401
1
                .tag("obj_info_id", idx)
7402
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7403
1
        ret = accessor->delete_all();
7404
1
        if (ret != 0) {
7405
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7406
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7407
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7408
0
                         << ", ret=" << ret;
7409
0
            return -1;
7410
0
        }
7411
1
        metrics_context.total_recycled_num = ++num_recycled;
7412
1
        metrics_context.report();
7413
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7414
1
        stage_keys.push_back(k);
7415
1
        return 0;
7416
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7356
1
                         this](std::string_view k, std::string_view v) -> int {
7357
1
        ++num_scanned;
7358
1
        RecycleStagePB recycle_stage;
7359
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7360
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7361
0
            return -1;
7362
0
        }
7363
7364
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7365
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7366
0
            LOG(WARNING) << "invalid idx: " << idx;
7367
0
            return -1;
7368
0
        }
7369
7370
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7371
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7372
1
                [&] {
7373
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7374
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7375
1
                    if (!s3_conf) {
7376
1
                        return -1;
7377
1
                    }
7378
7379
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7380
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7381
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7382
1
                    if (ret != 0) {
7383
1
                        return -1;
7384
1
                    }
7385
7386
1
                    accessor = std::move(s3_accessor);
7387
1
                    return 0;
7388
1
                }(),
7389
1
                "recycle_stage:get_accessor", &accessor);
7390
7391
1
        if (ret != 0) {
7392
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7393
0
            return ret;
7394
0
        }
7395
7396
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7397
1
                .tag("instance_id", instance_id_)
7398
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7399
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7400
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7401
1
                .tag("obj_info_id", idx)
7402
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7403
1
        ret = accessor->delete_all();
7404
1
        if (ret != 0) {
7405
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7406
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7407
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7408
0
                         << ", ret=" << ret;
7409
0
            return -1;
7410
0
        }
7411
1
        metrics_context.total_recycled_num = ++num_recycled;
7412
1
        metrics_context.report();
7413
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7414
1
        stage_keys.push_back(k);
7415
1
        return 0;
7416
1
    };
7417
7418
11
    auto loop_done = [&stage_keys, this]() -> int {
7419
1
        if (stage_keys.empty()) return 0;
7420
1
        DORIS_CLOUD_DEFER {
7421
1
            stage_keys.clear();
7422
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
7420
1
        DORIS_CLOUD_DEFER {
7421
1
            stage_keys.clear();
7422
1
        };
7423
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7424
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7425
0
            return -1;
7426
0
        }
7427
1
        return 0;
7428
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
7418
1
    auto loop_done = [&stage_keys, this]() -> int {
7419
1
        if (stage_keys.empty()) return 0;
7420
1
        DORIS_CLOUD_DEFER {
7421
1
            stage_keys.clear();
7422
1
        };
7423
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7424
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7425
0
            return -1;
7426
0
        }
7427
1
        return 0;
7428
1
    };
7429
11
    if (config::enable_recycler_stats_metrics) {
7430
0
        scan_and_statistics_stage();
7431
0
    }
7432
    // recycle_func and loop_done for scan and recycle
7433
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
7434
11
}
7435
7436
10
int InstanceRecycler::recycle_expired_stage_objects() {
7437
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
7438
7439
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7440
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7441
7442
10
    DORIS_CLOUD_DEFER {
7443
10
        int64_t cost =
7444
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7445
10
        metrics_context.finish_report();
7446
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7447
10
                .tag("instance_id", instance_id_);
7448
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
7442
10
    DORIS_CLOUD_DEFER {
7443
10
        int64_t cost =
7444
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7445
10
        metrics_context.finish_report();
7446
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7447
10
                .tag("instance_id", instance_id_);
7448
10
    };
7449
7450
10
    int ret = 0;
7451
7452
10
    if (config::enable_recycler_stats_metrics) {
7453
0
        scan_and_statistics_expired_stage_objects();
7454
0
    }
7455
7456
10
    for (const auto& stage : instance_info_.stages()) {
7457
0
        std::stringstream ss;
7458
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
7459
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
7460
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
7461
0
           << ", prefix=" << stage.obj_info().prefix();
7462
7463
0
        if (stopped()) {
7464
0
            break;
7465
0
        }
7466
0
        if (stage.type() == StagePB::EXTERNAL) {
7467
0
            continue;
7468
0
        }
7469
0
        int idx = stoi(stage.obj_info().id());
7470
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7471
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
7472
0
            continue;
7473
0
        }
7474
7475
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7476
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7477
0
        if (!s3_conf) {
7478
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
7479
0
            continue;
7480
0
        }
7481
7482
0
        s3_conf->prefix = stage.obj_info().prefix();
7483
0
        std::shared_ptr<S3Accessor> accessor;
7484
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
7485
0
        if (ret1 != 0) {
7486
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
7487
0
            ret = -1;
7488
0
            continue;
7489
0
        }
7490
7491
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7492
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
7493
0
            ret = -1;
7494
0
            continue;
7495
0
        }
7496
7497
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
7498
0
        int64_t expiration_time =
7499
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
7500
0
                config::internal_stage_objects_expire_time_second;
7501
0
        if (config::force_immediate_recycle) {
7502
0
            expiration_time = INT64_MAX;
7503
0
        }
7504
0
        ret1 = accessor->delete_all(expiration_time);
7505
0
        if (ret1 != 0) {
7506
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
7507
0
                         << ss.str();
7508
0
            ret = -1;
7509
0
            continue;
7510
0
        }
7511
0
        metrics_context.total_recycled_num++;
7512
0
        metrics_context.report();
7513
0
    }
7514
10
    return ret;
7515
10
}
7516
7517
235
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
7518
235
    std::lock_guard lock(recycle_tasks_mutex);
7519
235
    running_recycle_tasks[task_name] = start_time;
7520
235
}
7521
7522
235
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
7523
235
    std::lock_guard lock(recycle_tasks_mutex);
7524
235
    DCHECK(running_recycle_tasks[task_name] > 0);
7525
235
    running_recycle_tasks.erase(task_name);
7526
235
}
7527
7528
3
bool InstanceRecycler::check_recycle_tasks() {
7529
3
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
7530
3
    {
7531
3
        std::lock_guard lock(recycle_tasks_mutex);
7532
3
        tmp_running_recycle_tasks = running_recycle_tasks;
7533
3
    }
7534
7535
3
    bool found = false;
7536
3
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7537
3
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
7538
2
        int64_t cost = now - start_time;
7539
2
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
7540
2
            LOG_INFO("recycle task cost too much time cost={}s", cost)
7541
2
                    .tag("instance_id", instance_id_)
7542
2
                    .tag("task", task_name);
7543
2
            found = true;
7544
2
        }
7545
2
    }
7546
7547
3
    return found;
7548
3
}
7549
7550
// Scan and statistics indexes that need to be recycled
7551
1
int InstanceRecycler::scan_and_statistics_indexes() {
7552
1
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
7553
1
    RecyclerMetricsContext stream_metrics_context(instance_id_, "recycle_stream");
7554
7555
1
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
7556
1
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
7557
1
    std::string index_key0;
7558
1
    std::string index_key1;
7559
1
    recycle_index_key(index_key_info0, &index_key0);
7560
1
    recycle_index_key(index_key_info1, &index_key1);
7561
1
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7562
7563
1
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7564
1
        RecycleIndexPB index_pb;
7565
1
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7566
0
            return 0;
7567
0
        }
7568
1
        int64_t current_time = ::time(nullptr);
7569
1
        if (current_time <
7570
1
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7571
0
            return 0;
7572
0
        }
7573
        // decode index_id
7574
1
        auto k1 = k;
7575
1
        k1.remove_prefix(1);
7576
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7577
1
        decode_key(&k1, &out);
7578
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7579
1
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7580
1
        std::unique_ptr<Transaction> txn;
7581
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7582
1
        if (err != TxnErrorCode::TXN_OK) {
7583
0
            return 0;
7584
0
        }
7585
1
        std::string val;
7586
1
        err = txn->get(k, &val);
7587
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7588
0
            return 0;
7589
0
        }
7590
1
        if (err != TxnErrorCode::TXN_OK) {
7591
0
            return 0;
7592
0
        }
7593
1
        index_pb.Clear();
7594
1
        if (!index_pb.ParseFromString(val)) {
7595
0
            return 0;
7596
0
        }
7597
1
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
7598
1
            if (!index_pb.has_db_id() || !index_pb.has_stream_db_id()) {
7599
0
                LOG_WARNING("table stream recycle index is missing binding")
7600
0
                        .tag("instance_id", instance_id_)
7601
0
                        .tag("stream_id", index_id);
7602
0
                return 0;
7603
0
            }
7604
2
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7605
2
                std::string end = prefix;
7606
2
                end.push_back('\xff');
7607
2
                auto count_offset = [&stream_metrics_context](std::string_view key,
7608
6
                                                              std::string_view value) {
7609
6
                    stream_metrics_context.total_need_recycle_num++;
7610
6
                    stream_metrics_context.total_need_recycle_data_size +=
7611
6
                            key.size() + value.size();
7612
6
                    return 0;
7613
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
7608
6
                                                              std::string_view value) {
7609
6
                    stream_metrics_context.total_need_recycle_num++;
7610
6
                    stream_metrics_context.total_need_recycle_data_size +=
7611
6
                            key.size() + value.size();
7612
6
                    return 0;
7613
6
                };
7614
2
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7615
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
7604
2
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7605
2
                std::string end = prefix;
7606
2
                end.push_back('\xff');
7607
2
                auto count_offset = [&stream_metrics_context](std::string_view key,
7608
2
                                                              std::string_view value) {
7609
2
                    stream_metrics_context.total_need_recycle_num++;
7610
2
                    stream_metrics_context.total_need_recycle_data_size +=
7611
2
                            key.size() + value.size();
7612
2
                    return 0;
7613
2
                };
7614
2
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7615
2
            };
7616
1
            const std::string latest_prefix = table_stream_offset_key_prefix(
7617
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7618
1
                    index_id);
7619
1
            const std::string versioned_prefix = versioned::table_stream_offset_key_prefix(
7620
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7621
1
                    index_id);
7622
1
            if (scan_offset_prefix(latest_prefix) != 0 ||
7623
1
                scan_offset_prefix(versioned_prefix) != 0) {
7624
0
                LOG_WARNING("failed to scan table stream offsets for recycle statistics")
7625
0
                        .tag("instance_id", instance_id_)
7626
0
                        .tag("stream_id", index_id);
7627
0
            }
7628
1
            return 0;
7629
1
        }
7630
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7631
0
            return 0;
7632
0
        }
7633
0
        metrics_context.total_need_recycle_num++;
7634
0
        return 0;
7635
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
7563
1
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7564
1
        RecycleIndexPB index_pb;
7565
1
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7566
0
            return 0;
7567
0
        }
7568
1
        int64_t current_time = ::time(nullptr);
7569
1
        if (current_time <
7570
1
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7571
0
            return 0;
7572
0
        }
7573
        // decode index_id
7574
1
        auto k1 = k;
7575
1
        k1.remove_prefix(1);
7576
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7577
1
        decode_key(&k1, &out);
7578
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7579
1
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7580
1
        std::unique_ptr<Transaction> txn;
7581
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7582
1
        if (err != TxnErrorCode::TXN_OK) {
7583
0
            return 0;
7584
0
        }
7585
1
        std::string val;
7586
1
        err = txn->get(k, &val);
7587
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7588
0
            return 0;
7589
0
        }
7590
1
        if (err != TxnErrorCode::TXN_OK) {
7591
0
            return 0;
7592
0
        }
7593
1
        index_pb.Clear();
7594
1
        if (!index_pb.ParseFromString(val)) {
7595
0
            return 0;
7596
0
        }
7597
1
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
7598
1
            if (!index_pb.has_db_id() || !index_pb.has_stream_db_id()) {
7599
0
                LOG_WARNING("table stream recycle index is missing binding")
7600
0
                        .tag("instance_id", instance_id_)
7601
0
                        .tag("stream_id", index_id);
7602
0
                return 0;
7603
0
            }
7604
1
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7605
1
                std::string end = prefix;
7606
1
                end.push_back('\xff');
7607
1
                auto count_offset = [&stream_metrics_context](std::string_view key,
7608
1
                                                              std::string_view value) {
7609
1
                    stream_metrics_context.total_need_recycle_num++;
7610
1
                    stream_metrics_context.total_need_recycle_data_size +=
7611
1
                            key.size() + value.size();
7612
1
                    return 0;
7613
1
                };
7614
1
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7615
1
            };
7616
1
            const std::string latest_prefix = table_stream_offset_key_prefix(
7617
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7618
1
                    index_id);
7619
1
            const std::string versioned_prefix = versioned::table_stream_offset_key_prefix(
7620
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7621
1
                    index_id);
7622
1
            if (scan_offset_prefix(latest_prefix) != 0 ||
7623
1
                scan_offset_prefix(versioned_prefix) != 0) {
7624
0
                LOG_WARNING("failed to scan table stream offsets for recycle statistics")
7625
0
                        .tag("instance_id", instance_id_)
7626
0
                        .tag("stream_id", index_id);
7627
0
            }
7628
1
            return 0;
7629
1
        }
7630
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7631
0
            return 0;
7632
0
        }
7633
0
        metrics_context.total_need_recycle_num++;
7634
0
        return 0;
7635
0
    };
7636
7637
1
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
7638
1
    metrics_context.report(true);
7639
1
    stream_metrics_context.report(true);
7640
1
    segment_metrics_context_.report(true);
7641
1
    tablet_metrics_context_.report(true);
7642
1
    return ret;
7643
1
}
7644
7645
// Scan and statistics partitions that need to be recycled
7646
0
int InstanceRecycler::scan_and_statistics_partitions() {
7647
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
7648
7649
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
7650
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
7651
0
    std::string part_key0;
7652
0
    std::string part_key1;
7653
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7654
7655
0
    recycle_partition_key(part_key_info0, &part_key0);
7656
0
    recycle_partition_key(part_key_info1, &part_key1);
7657
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
7658
0
        RecyclePartitionPB part_pb;
7659
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
7660
0
            return 0;
7661
0
        }
7662
0
        int64_t current_time = ::time(nullptr);
7663
0
        if (current_time <
7664
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
7665
0
            return 0;
7666
0
        }
7667
        // decode partition_id
7668
0
        auto k1 = k;
7669
0
        k1.remove_prefix(1);
7670
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7671
0
        decode_key(&k1, &out);
7672
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
7673
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
7674
        // Change state to RECYCLING
7675
0
        std::unique_ptr<Transaction> txn;
7676
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7677
0
        if (err != TxnErrorCode::TXN_OK) {
7678
0
            return 0;
7679
0
        }
7680
0
        std::string val;
7681
0
        err = txn->get(k, &val);
7682
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7683
0
            return 0;
7684
0
        }
7685
0
        if (err != TxnErrorCode::TXN_OK) {
7686
0
            return 0;
7687
0
        }
7688
0
        part_pb.Clear();
7689
0
        if (!part_pb.ParseFromString(val)) {
7690
0
            return 0;
7691
0
        }
7692
        // Partitions with PREPARED state MUST have no data
7693
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
7694
0
        int ret = 0;
7695
0
        for (int64_t index_id : part_pb.index_id()) {
7696
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
7697
0
                                            partition_id, is_empty_tablet) != 0) {
7698
0
                ret = 0;
7699
0
            }
7700
0
        }
7701
0
        metrics_context.total_need_recycle_num++;
7702
0
        return ret;
7703
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_
7704
7705
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
7706
0
    metrics_context.report(true);
7707
0
    segment_metrics_context_.report(true);
7708
0
    tablet_metrics_context_.report(true);
7709
0
    return ret;
7710
0
}
7711
7712
// Scan and statistics rowsets that need to be recycled
7713
0
int InstanceRecycler::scan_and_statistics_rowsets() {
7714
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
7715
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
7716
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
7717
0
    std::string recyc_rs_key0;
7718
0
    std::string recyc_rs_key1;
7719
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
7720
0
                recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
7721
0
       int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7722
7723
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
7724
0
        RecycleRowsetPB rowset;
7725
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7726
0
            return 0;
7727
0
        }
7728
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
7729
0
        int64_t current_time = ::time(nullptr);
7730
0
        if (current_time <
7731
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
7732
0
            return 0;
7733
0
        }
7734
7735
0
        if (!rowset.has_type()) {
7736
0
            if (!rowset.has_resource_id()) [[unlikely]] {
7737
0
                return 0;
7738
0
            }
7739
0
            if (rowset.resource_id().empty()) [[unlikely]] {
7740
0
                return 0;
7741
0
            }
7742
0
            metrics_context.total_need_recycle_num++;
7743
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7744
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
7745
0
            segment_metrics_context_.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7746
0
            return 0;
7747
0
        }
7748
7749
0
        if(!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled()) {
7750
0
            return 0;
7751
0
        }
7752
7753
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
7754
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
7755
0
                return 0;
7756
0
            }
7757
0
        }
7758
0
        metrics_context.total_need_recycle_num++;
7759
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
7760
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
7761
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
7762
0
        return 0;
7763
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_
7764
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
7765
0
    metrics_context.report(true);
7766
0
    segment_metrics_context_.report(true);
7767
0
    return ret;
7768
0
}
7769
7770
// Scan and statistics tmp_rowsets that need to be recycled
7771
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
7772
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
7773
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
7774
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
7775
0
    std::string tmp_rs_key0;
7776
0
    std::string tmp_rs_key1;
7777
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
7778
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
7779
7780
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7781
7782
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
7783
0
        doris::RowsetMetaCloudPB rowset;
7784
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7785
0
            return 0;
7786
0
        }
7787
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
7788
0
        int64_t current_time = ::time(nullptr);
7789
0
        if (current_time < expiration) {
7790
0
            return 0;
7791
0
        }
7792
7793
0
        DCHECK_GT(rowset.txn_id(), 0)
7794
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
7795
7796
0
        if(!rowset.has_is_recycled() || !rowset.is_recycled()) {
7797
0
            return 0;
7798
0
        }
7799
7800
0
        if (!rowset.has_resource_id()) {
7801
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
7802
0
                return 0;
7803
0
            }
7804
0
            return 0;
7805
0
        }
7806
7807
0
        metrics_context.total_need_recycle_num++;
7808
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
7809
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
7810
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
7811
0
        return 0;
7812
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_
7813
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
7814
0
    metrics_context.report(true);
7815
0
    segment_metrics_context_.report(true);
7816
0
    return ret;
7817
0
}
7818
7819
// Scan and statistics abort_timeout_txn that need to be recycled
7820
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
7821
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
7822
7823
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
7824
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7825
0
    std::string begin_txn_running_key;
7826
0
    std::string end_txn_running_key;
7827
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
7828
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
7829
7830
0
    int64_t current_time =
7831
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7832
7833
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
7834
0
                                               std::string_view k, std::string_view v) -> int {
7835
0
        std::unique_ptr<Transaction> txn;
7836
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7837
0
        if (err != TxnErrorCode::TXN_OK) {
7838
0
            return 0;
7839
0
        }
7840
0
        std::string_view k1 = k;
7841
0
        k1.remove_prefix(1);
7842
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7843
0
        if (decode_key(&k1, &out) != 0) {
7844
0
            return 0;
7845
0
        }
7846
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7847
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7848
        // Update txn_info
7849
0
        std::string txn_inf_key, txn_inf_val;
7850
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
7851
0
        err = txn->get(txn_inf_key, &txn_inf_val);
7852
0
        if (err != TxnErrorCode::TXN_OK) {
7853
0
            return 0;
7854
0
        }
7855
0
        TxnInfoPB txn_info;
7856
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
7857
0
            return 0;
7858
0
        }
7859
7860
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
7861
0
            TxnRunningPB txn_running_pb;
7862
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7863
0
                return 0;
7864
0
            }
7865
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7866
0
                return 0;
7867
0
            }
7868
0
            metrics_context.total_need_recycle_num++;
7869
0
        }
7870
0
        return 0;
7871
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_
7872
7873
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key, std::move(handle_abort_timeout_txn_kv));
7874
0
    metrics_context.report(true);
7875
0
    return ret;
7876
0
}
7877
7878
// Scan and statistics expired_txn_label that need to be recycled
7879
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
7880
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
7881
7882
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7883
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7884
0
    std::string begin_recycle_txn_key;
7885
0
    std::string end_recycle_txn_key;
7886
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7887
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7888
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7889
0
    int64_t current_time_ms =
7890
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7891
7892
    // for calculate the total num or bytes of recyled objects
7893
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
7894
0
        RecycleTxnPB recycle_txn_pb;
7895
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7896
0
            return 0;
7897
0
        }
7898
0
        if ((config::force_immediate_recycle) ||
7899
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7900
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7901
0
             current_time_ms)) {
7902
0
            metrics_context.total_need_recycle_num++;
7903
0
        }
7904
0
        return 0;
7905
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_
7906
7907
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key, std::move(handle_expired_txn_label_kv));
7908
0
    metrics_context.report(true);
7909
0
    return ret;
7910
0
}
7911
7912
// Scan and statistics copy_jobs that need to be recycled
7913
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
7914
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
7915
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7916
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7917
0
    std::string key0;
7918
0
    std::string key1;
7919
0
    copy_job_key(key_info0, &key0);
7920
0
    copy_job_key(key_info1, &key1);
7921
7922
    // for calculate the total num or bytes of recyled objects
7923
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
7924
0
        CopyJobPB copy_job;
7925
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7926
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7927
0
            return 0;
7928
0
        }
7929
7930
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7931
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
7932
0
                int64_t current_time =
7933
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7934
0
                if (copy_job.finish_time_ms() > 0) {
7935
0
                    if (!config::force_immediate_recycle &&
7936
0
                        current_time < copy_job.finish_time_ms() +
7937
0
                                               config::copy_job_max_retention_second * 1000) {
7938
0
                        return 0;
7939
0
                    }
7940
0
                } else {
7941
0
                    if (!config::force_immediate_recycle &&
7942
0
                        current_time < copy_job.start_time_ms() +
7943
0
                                               config::copy_job_max_retention_second * 1000) {
7944
0
                        return 0;
7945
0
                    }
7946
0
                }
7947
0
            }
7948
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7949
0
            int64_t current_time =
7950
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7951
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7952
0
                return 0;
7953
0
            }
7954
0
        }
7955
0
        metrics_context.total_need_recycle_num++;
7956
0
        return 0;
7957
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_
7958
7959
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7960
0
    metrics_context.report(true);
7961
0
    return ret;
7962
0
}
7963
7964
// Scan and statistics stage that need to be recycled
7965
0
int InstanceRecycler::scan_and_statistics_stage() {
7966
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
7967
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7968
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7969
0
    std::string key0 = recycle_stage_key(key_info0);
7970
0
    std::string key1 = recycle_stage_key(key_info1);
7971
7972
    // for calculate the total num or bytes of recyled objects
7973
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
7974
0
                                                        std::string_view v) -> int {
7975
0
        RecycleStagePB recycle_stage;
7976
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7977
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7978
0
            return 0;
7979
0
        }
7980
7981
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
7982
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7983
0
            LOG(WARNING) << "invalid idx: " << idx;
7984
0
            return 0;
7985
0
        }
7986
7987
0
        std::shared_ptr<StorageVaultAccessor> accessor;
7988
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7989
0
                [&] {
7990
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7991
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7992
0
                    if (!s3_conf) {
7993
0
                        return 0;
7994
0
                    }
7995
7996
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7997
0
                    std::shared_ptr<S3Accessor> s3_accessor;
7998
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7999
0
                    if (ret != 0) {
8000
0
                        return 0;
8001
0
                    }
8002
8003
0
                    accessor = std::move(s3_accessor);
8004
0
                    return 0;
8005
0
                }(),
8006
0
                "recycle_stage:get_accessor", &accessor);
8007
8008
0
        if (ret != 0) {
8009
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
8010
0
            return 0;
8011
0
        }
8012
8013
0
        metrics_context.total_need_recycle_num++;
8014
0
        return 0;
8015
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_
8016
8017
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
8018
0
    metrics_context.report(true);
8019
0
    return ret;
8020
0
}
8021
8022
// Scan and statistics expired_stage_objects that need to be recycled
8023
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
8024
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
8025
8026
    // for calculate the total num or bytes of recyled objects
8027
0
    auto scan_and_statistics = [&metrics_context, this]() {
8028
0
        for (const auto& stage : instance_info_.stages()) {
8029
0
            if (stopped()) {
8030
0
                break;
8031
0
            }
8032
0
            if (stage.type() == StagePB::EXTERNAL) {
8033
0
                continue;
8034
0
            }
8035
0
            int idx = stoi(stage.obj_info().id());
8036
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
8037
0
                continue;
8038
0
            }
8039
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
8040
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8041
0
            if (!s3_conf) {
8042
0
                continue;
8043
0
            }
8044
0
            s3_conf->prefix = stage.obj_info().prefix();
8045
0
            std::shared_ptr<S3Accessor> accessor;
8046
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
8047
0
            if (ret1 != 0) {
8048
0
                continue;
8049
0
            }
8050
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
8051
0
                continue;
8052
0
            }
8053
0
            metrics_context.total_need_recycle_num++;
8054
0
        }
8055
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
8056
8057
0
    scan_and_statistics();
8058
0
    metrics_context.report(true);
8059
0
    return 0;
8060
0
}
8061
8062
// Scan and statistics versions that need to be recycled
8063
0
int InstanceRecycler::scan_and_statistics_versions() {
8064
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
8065
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
8066
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
8067
8068
0
    int64_t last_scanned_table_id = 0;
8069
0
    bool is_recycled = false; // Is last scanned kv recycled
8070
    // for calculate the total num or bytes of recyled objects
8071
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
8072
0
                                       std::string_view k, std::string_view) {
8073
0
        auto k1 = k;
8074
0
        k1.remove_prefix(1);
8075
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
8076
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8077
0
        decode_key(&k1, &out);
8078
0
        DCHECK_EQ(out.size(), 6) << k;
8079
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
8080
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
8081
0
            metrics_context.total_need_recycle_num +=
8082
0
                    is_recycled; // Version kv of this table has been recycled
8083
0
            return 0;
8084
0
        }
8085
0
        last_scanned_table_id = table_id;
8086
0
        is_recycled = false;
8087
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
8088
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
8089
0
        std::unique_ptr<Transaction> txn;
8090
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8091
0
        if (err != TxnErrorCode::TXN_OK) {
8092
0
            return 0;
8093
0
        }
8094
0
        std::unique_ptr<RangeGetIterator> iter;
8095
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
8096
0
        if (err != TxnErrorCode::TXN_OK) {
8097
0
            return 0;
8098
0
        }
8099
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
8100
0
            return 0;
8101
0
        }
8102
0
        metrics_context.total_need_recycle_num++;
8103
0
        is_recycled = true;
8104
0
        return 0;
8105
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_
8106
8107
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
8108
0
    metrics_context.report(true);
8109
0
    return ret;
8110
0
}
8111
8112
// Scan and statistics restore jobs that need to be recycled
8113
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
8114
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
8115
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
8116
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
8117
0
    std::string restore_job_key0;
8118
0
    std::string restore_job_key1;
8119
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
8120
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
8121
8122
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8123
8124
    // for calculate the total num or bytes of recyled objects
8125
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
8126
0
        RestoreJobCloudPB restore_job_pb;
8127
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
8128
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
8129
0
            return 0;
8130
0
        }
8131
0
        int64_t expiration =
8132
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
8133
0
        int64_t current_time = ::time(nullptr);
8134
0
        if (current_time < expiration) { // not expired
8135
0
            return 0;
8136
0
        }
8137
0
        metrics_context.total_need_recycle_num++;
8138
0
        if(restore_job_pb.need_recycle_data()) {
8139
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
8140
0
        }
8141
0
        return 0;
8142
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_
8143
8144
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
8145
0
    metrics_context.report(true);
8146
0
    return ret;
8147
0
}
8148
8149
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
8150
3
    if (!should_recycle_versioned_keys()) {
8151
0
        return;
8152
0
    }
8153
8154
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
8155
8156
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
8157
3
    if (recycle_checker.init() != 0) {
8158
0
        return;
8159
0
    }
8160
8161
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
8162
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
8163
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
8164
8165
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
8166
8
    for (; iter->valid(); iter->next()) {
8167
5
        OperationLogPB operation_log;
8168
5
        if (!iter->parse_value(&operation_log)) {
8169
0
            continue;
8170
0
        }
8171
8172
5
        std::string_view key = iter->key();
8173
5
        Versionstamp log_versionstamp;
8174
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
8175
0
            continue;
8176
0
        }
8177
8178
5
        OperationLogReferenceInfo ref_info;
8179
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
8180
5
                                         &ref_info)) {
8181
4
            metrics_context.total_need_recycle_num++;
8182
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
8183
4
        }
8184
5
    }
8185
8186
3
    metrics_context.report(true);
8187
3
}
8188
8189
int InstanceRecycler::classify_rowset_task_by_ref_count(
8190
60
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
8191
60
    constexpr int MAX_RETRY = 10;
8192
60
    const auto& rowset_meta = task.rowset_meta;
8193
60
    int64_t tablet_id = rowset_meta.tablet_id();
8194
60
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
8195
60
    std::string_view reference_instance_id = instance_id_;
8196
60
    if (rowset_meta.has_reference_instance_id()) {
8197
5
        reference_instance_id = rowset_meta.reference_instance_id();
8198
5
    }
8199
8200
61
    for (int i = 0; i < MAX_RETRY; ++i) {
8201
61
        std::unique_ptr<Transaction> txn;
8202
61
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8203
61
        if (err != TxnErrorCode::TXN_OK) {
8204
0
            LOG_WARNING("failed to create txn when classifying rowset task")
8205
0
                    .tag("instance_id", instance_id_)
8206
0
                    .tag("tablet_id", tablet_id)
8207
0
                    .tag("rowset_id", rowset_id)
8208
0
                    .tag("err", err);
8209
0
            return -1;
8210
0
        }
8211
8212
61
        std::string rowset_ref_count_key =
8213
61
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
8214
61
        task.rowset_ref_count_key = rowset_ref_count_key;
8215
8216
61
        int64_t ref_count = 0;
8217
61
        {
8218
61
            std::string value;
8219
61
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
8220
61
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
8221
0
                ref_count = 1;
8222
61
            } else if (err != TxnErrorCode::TXN_OK) {
8223
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
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
61
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
8230
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
8231
0
                        .tag("instance_id", instance_id_)
8232
0
                        .tag("tablet_id", tablet_id)
8233
0
                        .tag("rowset_id", rowset_id)
8234
0
                        .tag("value", hex(value));
8235
0
                return -1;
8236
0
            }
8237
61
        }
8238
8239
61
        if (ref_count > 1) {
8240
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
8241
12
            txn->atomic_add(rowset_ref_count_key, -1);
8242
12
            LOG_INFO("decrease rowset data ref count in classification phase")
8243
12
                    .tag("instance_id", instance_id_)
8244
12
                    .tag("tablet_id", tablet_id)
8245
12
                    .tag("rowset_id", rowset_id)
8246
12
                    .tag("ref_count", ref_count - 1)
8247
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
8248
8249
12
            if (!task.recycle_rowset_key.empty()) {
8250
0
                txn->remove(task.recycle_rowset_key);
8251
0
                LOG_INFO("remove recycle rowset key in classification phase")
8252
0
                        .tag("key", hex(task.recycle_rowset_key));
8253
0
            }
8254
12
            if (!task.non_versioned_rowset_key.empty()) {
8255
12
                txn->remove(task.non_versioned_rowset_key);
8256
12
                LOG_INFO("remove non versioned rowset key in classification phase")
8257
12
                        .tag("key", hex(task.non_versioned_rowset_key));
8258
12
            }
8259
8260
12
            err = txn->commit();
8261
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
8262
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
8263
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
8264
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
8265
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
8266
1
                continue;
8267
11
            } else if (err != TxnErrorCode::TXN_OK) {
8268
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
8269
0
                        .tag("instance_id", instance_id_)
8270
0
                        .tag("tablet_id", tablet_id)
8271
0
                        .tag("rowset_id", rowset_id)
8272
0
                        .tag("err", err);
8273
0
                return -1;
8274
0
            }
8275
11
            return 1; // handled, not added to batch delete
8276
49
        } else {
8277
            // ref_count == 1: Add to batch delete plan without modifying any KV.
8278
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
8279
49
            LOG_INFO("add rowset to batch delete plan")
8280
49
                    .tag("instance_id", instance_id_)
8281
49
                    .tag("tablet_id", tablet_id)
8282
49
                    .tag("rowset_id", rowset_id)
8283
49
                    .tag("resource_id", rowset_meta.resource_id())
8284
49
                    .tag("ref_count", ref_count);
8285
8286
49
            batch_delete_tasks.push_back(std::move(task));
8287
49
            return 0; // added to batch delete
8288
49
        }
8289
61
    }
8290
8291
0
    LOG_WARNING("failed to classify rowset task after retry")
8292
0
            .tag("instance_id", instance_id_)
8293
0
            .tag("tablet_id", tablet_id)
8294
0
            .tag("rowset_id", rowset_id)
8295
0
            .tag("retry", MAX_RETRY);
8296
0
    return -1;
8297
60
}
8298
8299
10
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
8300
10
    int ret = 0;
8301
49
    for (const auto& task : tasks) {
8302
49
        int64_t tablet_id = task.rowset_meta.tablet_id();
8303
49
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
8304
8305
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
8306
        // so we don't need to call it again here.
8307
8308
        // Remove all metadata keys in one transaction
8309
49
        std::unique_ptr<Transaction> txn;
8310
49
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8311
49
        if (err != TxnErrorCode::TXN_OK) {
8312
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
8313
0
                    .tag("instance_id", instance_id_)
8314
0
                    .tag("tablet_id", tablet_id)
8315
0
                    .tag("rowset_id", rowset_id)
8316
0
                    .tag("err", err);
8317
0
            ret = -1;
8318
0
            continue;
8319
0
        }
8320
8321
49
        std::string_view reference_instance_id = instance_id_;
8322
49
        if (task.rowset_meta.has_reference_instance_id()) {
8323
0
            reference_instance_id = task.rowset_meta.reference_instance_id();
8324
0
        }
8325
8326
49
        txn->remove(task.rowset_ref_count_key);
8327
49
        LOG_INFO("delete rowset data ref count key in cleanup phase")
8328
49
                .tag("instance_id", instance_id_)
8329
49
                .tag("tablet_id", tablet_id)
8330
49
                .tag("rowset_id", rowset_id)
8331
49
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
8332
8333
49
        std::string dbm_start_key =
8334
49
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
8335
49
        std::string dbm_end_key = meta_delete_bitmap_key(
8336
49
                {reference_instance_id, tablet_id, rowset_id,
8337
49
                 std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
8338
49
        txn->remove(dbm_start_key, dbm_end_key);
8339
49
        LOG_INFO("remove delete bitmap kv in cleanup phase")
8340
49
                .tag("instance_id", instance_id_)
8341
49
                .tag("tablet_id", tablet_id)
8342
49
                .tag("rowset_id", rowset_id)
8343
49
                .tag("begin", hex(dbm_start_key))
8344
49
                .tag("end", hex(dbm_end_key));
8345
8346
49
        std::string versioned_dbm_start_key =
8347
49
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
8348
49
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
8349
49
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
8350
49
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
8351
49
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
8352
49
                .tag("instance_id", instance_id_)
8353
49
                .tag("tablet_id", tablet_id)
8354
49
                .tag("rowset_id", rowset_id)
8355
49
                .tag("begin", hex(versioned_dbm_start_key))
8356
49
                .tag("end", hex(versioned_dbm_end_key));
8357
8358
        // Remove versioned meta rowset key
8359
49
        if (!task.versioned_rowset_key.empty()) {
8360
49
            versioned::document_remove<RowsetMetaCloudPB>(
8361
49
                txn.get(), task.versioned_rowset_key, task.versionstamp);
8362
49
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
8363
49
                    .tag("instance_id", instance_id_)
8364
49
                    .tag("tablet_id", tablet_id)
8365
49
                    .tag("rowset_id", rowset_id)
8366
49
                    .tag("key_prefix", hex(task.versioned_rowset_key));
8367
49
        }
8368
8369
49
        if (!task.non_versioned_rowset_key.empty()) {
8370
49
            txn->remove(task.non_versioned_rowset_key);
8371
49
            LOG_INFO("remove non versioned rowset key in cleanup phase")
8372
49
                    .tag("instance_id", instance_id_)
8373
49
                    .tag("tablet_id", tablet_id)
8374
49
                    .tag("rowset_id", rowset_id)
8375
49
                    .tag("key", hex(task.non_versioned_rowset_key));
8376
49
        }
8377
8378
        // Remove recycle_rowset_key last to ensure retry safety:
8379
        // if cleanup fails, this key remains and triggers next round retry.
8380
49
        if (!task.recycle_rowset_key.empty()) {
8381
0
            txn->remove(task.recycle_rowset_key);
8382
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
8383
0
                    .tag("instance_id", instance_id_)
8384
0
                    .tag("tablet_id", tablet_id)
8385
0
                    .tag("rowset_id", rowset_id)
8386
0
                    .tag("key", hex(task.recycle_rowset_key));
8387
0
        }
8388
8389
49
        err = txn->commit();
8390
49
        if (err != TxnErrorCode::TXN_OK) {
8391
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
8392
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
8393
0
                    .tag("instance_id", instance_id_)
8394
0
                    .tag("tablet_id", tablet_id)
8395
0
                    .tag("rowset_id", rowset_id)
8396
0
                    .tag("err", err);
8397
0
            ret = -1;
8398
0
            continue;
8399
0
        }
8400
8401
49
        LOG_INFO("cleanup rowset metadata success")
8402
49
                .tag("instance_id", instance_id_)
8403
49
                .tag("tablet_id", tablet_id)
8404
49
                .tag("rowset_id", rowset_id);
8405
49
    }
8406
10
    return ret;
8407
10
}
8408
8409
} // namespace doris::cloud