Coverage Report

Created: 2026-07-23 12:55

/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 <utility>
46
#include <variant>
47
48
#include "common/defer.h"
49
#include "common/stopwatch.h"
50
#include "meta-service/meta_service.h"
51
#include "meta-service/meta_service_helper.h"
52
#include "meta-service/meta_service_schema.h"
53
#include "meta-store/blob_message.h"
54
#include "meta-store/meta_reader.h"
55
#include "meta-store/txn_kv.h"
56
#include "meta-store/txn_kv_error.h"
57
#include "meta-store/versioned_value.h"
58
#include "recycler/checker.h"
59
#ifdef ENABLE_HDFS_STORAGE_VAULT
60
#include "recycler/hdfs_accessor.h"
61
#endif
62
#include "recycler/s3_accessor.h"
63
#include "recycler/storage_vault_accessor.h"
64
#ifdef UNIT_TEST
65
#include "../test/mock_accessor.h"
66
#endif
67
#include "common/bvars.h"
68
#include "common/config.h"
69
#include "common/encryption_util.h"
70
#include "common/logging.h"
71
#include "common/simple_thread_pool.h"
72
#include "common/util.h"
73
#include "cpp/sync_point.h"
74
#include "meta-store/codec.h"
75
#include "meta-store/document_message.h"
76
#include "meta-store/keys.h"
77
#include "recycler/recycler_service.h"
78
#include "recycler/sync_executor.h"
79
#include "recycler/util.h"
80
#include "snapshot/snapshot_manager_factory.h"
81
82
namespace doris::cloud {
83
84
using namespace std::chrono;
85
86
namespace {
87
88
0
int64_t packed_file_retry_sleep_ms() {
89
0
    const int64_t min_ms = std::max<int64_t>(0, config::packed_file_txn_retry_sleep_min_ms);
90
0
    const int64_t max_ms = std::max<int64_t>(min_ms, config::packed_file_txn_retry_sleep_max_ms);
91
0
    thread_local std::mt19937_64 gen(std::random_device {}());
92
0
    std::uniform_int_distribution<int64_t> dist(min_ms, max_ms);
93
0
    return dist(gen);
94
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
95
96
0
void sleep_for_packed_file_retry() {
97
0
    std::this_thread::sleep_for(std::chrono::milliseconds(packed_file_retry_sleep_ms()));
98
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
99
100
37
bool filter_out_instance(const std::string& instance_id) {
101
37
    if (config::recycle_whitelist.empty()) {
102
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
103
35
               config::recycle_blacklist.end();
104
35
    }
105
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
106
2
           config::recycle_whitelist.end();
107
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
100
37
bool filter_out_instance(const std::string& instance_id) {
101
37
    if (config::recycle_whitelist.empty()) {
102
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
103
35
               config::recycle_blacklist.end();
104
35
    }
105
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
106
2
           config::recycle_whitelist.end();
107
37
}
108
109
868k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
110
868k
    const auto& locations = rowset.packed_slice_locations();
111
868k
    auto it = locations.find(path);
112
868k
    return it != locations.end() && it->second.has_packed_file_path() &&
113
868k
           !it->second.packed_file_path().empty();
114
868k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
109
7
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
110
7
    const auto& locations = rowset.packed_slice_locations();
111
7
    auto it = locations.find(path);
112
7
    return it != locations.end() && it->second.has_packed_file_path() &&
113
7
           !it->second.packed_file_path().empty();
114
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
109
868k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
110
868k
    const auto& locations = rowset.packed_slice_locations();
111
868k
    auto it = locations.find(path);
112
868k
    return it != locations.end() && it->second.has_packed_file_path() &&
113
868k
           !it->second.packed_file_path().empty();
114
868k
}
115
116
void add_file_to_delete_if_not_packed(const doris::RowsetMetaCloudPB& rowset,
117
                                      const std::string& path,
118
866k
                                      std::vector<std::string>* file_paths) {
119
868k
    if (!is_packed_slice_path(rowset, path)) {
120
868k
        file_paths->push_back(path);
121
868k
    }
122
866k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
118
7
                                      std::vector<std::string>* file_paths) {
119
7
    if (!is_packed_slice_path(rowset, path)) {
120
7
        file_paths->push_back(path);
121
7
    }
122
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
118
866k
                                      std::vector<std::string>* file_paths) {
119
868k
    if (!is_packed_slice_path(rowset, path)) {
120
868k
        file_paths->push_back(path);
121
868k
    }
122
866k
}
123
124
} // namespace
125
126
// return 0 for success get a key, 1 for key not found, negative for error
127
0
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
128
0
    std::unique_ptr<Transaction> txn;
129
0
    TxnErrorCode err = txn_kv->create_txn(&txn);
130
0
    if (err != TxnErrorCode::TXN_OK) {
131
0
        return -1;
132
0
    }
133
0
    switch (txn->get(key, &val, true)) {
134
0
    case TxnErrorCode::TXN_OK:
135
0
        return 0;
136
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
137
0
        return 1;
138
0
    default:
139
0
        return -1;
140
0
    };
141
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
142
143
// 0 for success, negative for error
144
static int txn_get(TxnKv* txn_kv, std::string_view begin, std::string_view end,
145
340
                   std::unique_ptr<RangeGetIterator>& it) {
146
340
    std::unique_ptr<Transaction> txn;
147
340
    TxnErrorCode err = txn_kv->create_txn(&txn);
148
340
    if (err != TxnErrorCode::TXN_OK) {
149
0
        return -1;
150
0
    }
151
340
    switch (txn->get(begin, end, &it, true)) {
152
340
    case TxnErrorCode::TXN_OK:
153
340
        return 0;
154
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
155
0
        return 1;
156
0
    default:
157
0
        return -1;
158
340
    };
159
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
145
31
                   std::unique_ptr<RangeGetIterator>& it) {
146
31
    std::unique_ptr<Transaction> txn;
147
31
    TxnErrorCode err = txn_kv->create_txn(&txn);
148
31
    if (err != TxnErrorCode::TXN_OK) {
149
0
        return -1;
150
0
    }
151
31
    switch (txn->get(begin, end, &it, true)) {
152
31
    case TxnErrorCode::TXN_OK:
153
31
        return 0;
154
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
155
0
        return 1;
156
0
    default:
157
0
        return -1;
158
31
    };
159
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
145
309
                   std::unique_ptr<RangeGetIterator>& it) {
146
309
    std::unique_ptr<Transaction> txn;
147
309
    TxnErrorCode err = txn_kv->create_txn(&txn);
148
309
    if (err != TxnErrorCode::TXN_OK) {
149
0
        return -1;
150
0
    }
151
309
    switch (txn->get(begin, end, &it, true)) {
152
309
    case TxnErrorCode::TXN_OK:
153
309
        return 0;
154
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
155
0
        return 1;
156
0
    default:
157
0
        return -1;
158
309
    };
159
0
}
160
161
// return 0 for success otherwise error
162
6
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
163
6
    std::unique_ptr<Transaction> txn;
164
6
    TxnErrorCode err = txn_kv->create_txn(&txn);
165
6
    if (err != TxnErrorCode::TXN_OK) {
166
0
        return -1;
167
0
    }
168
10
    for (auto k : keys) {
169
10
        txn->remove(k);
170
10
    }
171
6
    switch (txn->commit()) {
172
6
    case TxnErrorCode::TXN_OK:
173
6
        return 0;
174
0
    case TxnErrorCode::TXN_CONFLICT:
175
0
        return -1;
176
0
    default:
177
0
        return -1;
178
6
    }
179
6
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
162
1
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
163
1
    std::unique_ptr<Transaction> txn;
164
1
    TxnErrorCode err = txn_kv->create_txn(&txn);
165
1
    if (err != TxnErrorCode::TXN_OK) {
166
0
        return -1;
167
0
    }
168
1
    for (auto k : keys) {
169
1
        txn->remove(k);
170
1
    }
171
1
    switch (txn->commit()) {
172
1
    case TxnErrorCode::TXN_OK:
173
1
        return 0;
174
0
    case TxnErrorCode::TXN_CONFLICT:
175
0
        return -1;
176
0
    default:
177
0
        return -1;
178
1
    }
179
1
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
162
5
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
163
5
    std::unique_ptr<Transaction> txn;
164
5
    TxnErrorCode err = txn_kv->create_txn(&txn);
165
5
    if (err != TxnErrorCode::TXN_OK) {
166
0
        return -1;
167
0
    }
168
9
    for (auto k : keys) {
169
9
        txn->remove(k);
170
9
    }
171
5
    switch (txn->commit()) {
172
5
    case TxnErrorCode::TXN_OK:
173
5
        return 0;
174
0
    case TxnErrorCode::TXN_CONFLICT:
175
0
        return -1;
176
0
    default:
177
0
        return -1;
178
5
    }
179
5
}
180
181
// return 0 for success otherwise error
182
139
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
183
139
    std::unique_ptr<Transaction> txn;
184
139
    TxnErrorCode err = txn_kv->create_txn(&txn);
185
139
    if (err != TxnErrorCode::TXN_OK) {
186
0
        return -1;
187
0
    }
188
106k
    for (auto& k : keys) {
189
106k
        txn->remove(k);
190
106k
    }
191
139
    switch (txn->commit()) {
192
139
    case TxnErrorCode::TXN_OK:
193
139
        return 0;
194
0
    case TxnErrorCode::TXN_CONFLICT:
195
0
        return -1;
196
0
    default:
197
0
        return -1;
198
139
    }
199
139
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
182
33
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
183
33
    std::unique_ptr<Transaction> txn;
184
33
    TxnErrorCode err = txn_kv->create_txn(&txn);
185
33
    if (err != TxnErrorCode::TXN_OK) {
186
0
        return -1;
187
0
    }
188
33
    for (auto& k : keys) {
189
16
        txn->remove(k);
190
16
    }
191
33
    switch (txn->commit()) {
192
33
    case TxnErrorCode::TXN_OK:
193
33
        return 0;
194
0
    case TxnErrorCode::TXN_CONFLICT:
195
0
        return -1;
196
0
    default:
197
0
        return -1;
198
33
    }
199
33
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
182
106
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
183
106
    std::unique_ptr<Transaction> txn;
184
106
    TxnErrorCode err = txn_kv->create_txn(&txn);
185
106
    if (err != TxnErrorCode::TXN_OK) {
186
0
        return -1;
187
0
    }
188
106k
    for (auto& k : keys) {
189
106k
        txn->remove(k);
190
106k
    }
191
106
    switch (txn->commit()) {
192
106
    case TxnErrorCode::TXN_OK:
193
106
        return 0;
194
0
    case TxnErrorCode::TXN_CONFLICT:
195
0
        return -1;
196
0
    default:
197
0
        return -1;
198
106
    }
199
106
}
200
201
// return 0 for success otherwise error
202
[[maybe_unused]] static int txn_remove(TxnKv* txn_kv, std::string_view begin,
203
106k
                                       std::string_view end) {
204
106k
    std::unique_ptr<Transaction> txn;
205
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
206
106k
    if (err != TxnErrorCode::TXN_OK) {
207
0
        return -1;
208
0
    }
209
106k
    txn->remove(begin, end);
210
106k
    switch (txn->commit()) {
211
106k
    case TxnErrorCode::TXN_OK:
212
106k
        return 0;
213
0
    case TxnErrorCode::TXN_CONFLICT:
214
0
        return -1;
215
0
    default:
216
0
        return -1;
217
106k
    }
218
106k
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
203
16
                                       std::string_view end) {
204
16
    std::unique_ptr<Transaction> txn;
205
16
    TxnErrorCode err = txn_kv->create_txn(&txn);
206
16
    if (err != TxnErrorCode::TXN_OK) {
207
0
        return -1;
208
0
    }
209
16
    txn->remove(begin, end);
210
16
    switch (txn->commit()) {
211
16
    case TxnErrorCode::TXN_OK:
212
16
        return 0;
213
0
    case TxnErrorCode::TXN_CONFLICT:
214
0
        return -1;
215
0
    default:
216
0
        return -1;
217
16
    }
218
16
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
203
106k
                                       std::string_view end) {
204
106k
    std::unique_ptr<Transaction> txn;
205
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
206
106k
    if (err != TxnErrorCode::TXN_OK) {
207
0
        return -1;
208
0
    }
209
106k
    txn->remove(begin, end);
210
106k
    switch (txn->commit()) {
211
106k
    case TxnErrorCode::TXN_OK:
212
106k
        return 0;
213
0
    case TxnErrorCode::TXN_CONFLICT:
214
0
        return -1;
215
0
    default:
216
0
        return -1;
217
106k
    }
218
106k
}
219
220
void scan_restore_job_rowset(
221
        Transaction* txn, const std::string& instance_id, int64_t tablet_id, MetaServiceCode& code,
222
        std::string& msg,
223
        std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>* restore_job_rs_metas);
224
225
static inline void check_recycle_task(const std::string& instance_id, const std::string& task_name,
226
                                      int64_t num_scanned, int64_t num_recycled,
227
47
                                      int64_t start_time) {
228
47
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
229
0
        int64_t cost =
230
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
231
0
        if (cost > config::recycle_task_threshold_seconds) {
232
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
233
0
                    .tag("instance_id", instance_id)
234
0
                    .tag("task", task_name)
235
0
                    .tag("num_scanned", num_scanned)
236
0
                    .tag("num_recycled", num_recycled);
237
0
        }
238
0
    }
239
47
    return;
240
47
}
recycler.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
227
2
                                      int64_t start_time) {
228
2
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
229
0
        int64_t cost =
230
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
231
0
        if (cost > config::recycle_task_threshold_seconds) {
232
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
233
0
                    .tag("instance_id", instance_id)
234
0
                    .tag("task", task_name)
235
0
                    .tag("num_scanned", num_scanned)
236
0
                    .tag("num_recycled", num_recycled);
237
0
        }
238
0
    }
239
2
    return;
240
2
}
recycler_test.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
227
45
                                      int64_t start_time) {
228
45
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
229
0
        int64_t cost =
230
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
231
0
        if (cost > config::recycle_task_threshold_seconds) {
232
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
233
0
                    .tag("instance_id", instance_id)
234
0
                    .tag("task", task_name)
235
0
                    .tag("num_scanned", num_scanned)
236
0
                    .tag("num_recycled", num_recycled);
237
0
        }
238
0
    }
239
45
    return;
240
45
}
241
242
6
Recycler::Recycler(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
243
6
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
244
245
6
    auto s3_producer_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
246
6
                                                               "s3_producer_pool");
247
6
    s3_producer_pool->start();
248
6
    auto recycle_tablet_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
249
6
                                                                  "recycle_tablet_pool");
250
6
    recycle_tablet_pool->start();
251
6
    auto group_recycle_function_pool = std::make_shared<SimpleThreadPool>(
252
6
            config::recycle_pool_parallelism, "group_recycle_function_pool");
253
6
    group_recycle_function_pool->start();
254
6
    _thread_pool_group =
255
6
            RecyclerThreadPoolGroup(std::move(s3_producer_pool), std::move(recycle_tablet_pool),
256
6
                                    std::move(group_recycle_function_pool));
257
258
6
    auto resource_mgr = std::make_shared<ResourceManager>(txn_kv_);
259
6
    txn_lazy_committer_ = std::make_shared<TxnLazyCommitter>(txn_kv_, std::move(resource_mgr));
260
6
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
261
6
}
262
263
6
Recycler::~Recycler() {
264
6
    if (!stopped()) {
265
0
        stop();
266
0
    }
267
6
}
268
269
5
void Recycler::instance_scanner_callback() {
270
    // sleep 60 seconds before scheduling for the launch procedure to complete:
271
    // some bad hdfs connection may cause some log to stdout stderr
272
    // which may pollute .out file and affect the script to check success
273
5
    std::this_thread::sleep_for(
274
5
            std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
275
1.26k
    while (!stopped()) {
276
1.26k
        if (config::enable_recycler) {
277
3
            std::vector<InstanceInfoPB> instances;
278
3
            get_all_instances(txn_kv_.get(), instances);
279
            // TODO(plat1ko): delete job recycle kv of non-existent instances
280
3
            LOG(INFO) << "Recycler get instances: " << [&instances] {
281
3
                std::stringstream ss;
282
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
283
3
                return ss.str();
284
3
            }();
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
Line
Count
Source
280
3
            LOG(INFO) << "Recycler get instances: " << [&instances] {
281
3
                std::stringstream ss;
282
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
283
3
                return ss.str();
284
3
            }();
285
3
            if (!instances.empty()) {
286
                // enqueue instances
287
3
                std::lock_guard lock(mtx_);
288
30
                for (auto& instance : instances) {
289
30
                    if (filter_out_instance(instance.instance_id())) continue;
290
30
                    auto [_, success] = pending_instance_set_.insert(instance.instance_id());
291
                    // skip instance already in pending queue
292
30
                    if (success) {
293
30
                        pending_instance_queue_.push_back(std::move(instance));
294
30
                    }
295
30
                }
296
3
                pending_instance_cond_.notify_all();
297
3
            }
298
1.26k
        } else {
299
1.26k
            LOG(WARNING) << "Skip recycler since enable_recycler is false";
300
1.26k
        }
301
1.26k
        {
302
1.26k
            std::unique_lock lock(mtx_);
303
1.26k
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
304
2.52k
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
304
2.52k
                               [&]() { return stopped(); });
305
1.26k
        }
306
1.26k
    }
307
5
}
308
309
9
void Recycler::recycle_callback() {
310
40
    while (!stopped()) {
311
37
        InstanceInfoPB instance;
312
37
        {
313
37
            std::unique_lock lock(mtx_);
314
37
            pending_instance_cond_.wait(
315
49
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
315
49
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
316
37
            if (stopped()) {
317
6
                return;
318
6
            }
319
31
            instance = std::move(pending_instance_queue_.front());
320
31
            pending_instance_queue_.pop_front();
321
31
            pending_instance_set_.erase(instance.instance_id());
322
31
        }
323
0
        auto& instance_id = instance.instance_id();
324
31
        {
325
31
            std::lock_guard lock(mtx_);
326
            // skip instance in recycling
327
31
            if (recycling_instance_map_.count(instance_id)) continue;
328
31
        }
329
31
        if (!config::enable_recycler) {
330
1
            LOG(WARNING) << "Skip recycle instance_id=" << instance_id
331
1
                         << " since enable_recycler is false";
332
1
            continue;
333
1
        }
334
30
        auto instance_recycler = std::make_shared<InstanceRecycler>(
335
30
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
336
337
30
        if (int r = instance_recycler->init(); r != 0) {
338
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
339
0
                         << " ret=" << r;
340
0
            continue;
341
0
        }
342
30
        std::string recycle_job_key;
343
30
        job_recycle_key({instance_id}, &recycle_job_key);
344
30
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
345
30
                                               ip_port_, config::recycle_interval_seconds * 1000);
346
30
        if (ret != 0) { // Prepare failed
347
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
348
20
                         << " ret=" << ret;
349
20
            continue;
350
20
        } else {
351
10
            std::lock_guard lock(mtx_);
352
10
            recycling_instance_map_.emplace(instance_id, instance_recycler);
353
10
        }
354
10
        if (stopped()) return;
355
10
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
356
10
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
357
10
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
358
10
        g_bvar_recycler_instance_recycle_task_status.put({"submitted"}, 1);
359
10
        ret = instance_recycler->do_recycle();
360
        // If instance recycler has been aborted, don't finish this job
361
362
10
        if (!instance_recycler->stopped()) {
363
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
364
10
                                        ret == 0, ctime_ms);
365
10
        }
366
10
        if (instance_recycler->stopped() || ret != 0) {
367
0
            g_bvar_recycler_instance_recycle_task_status.put({"error"}, 1);
368
0
        }
369
10
        {
370
10
            std::lock_guard lock(mtx_);
371
10
            recycling_instance_map_.erase(instance_id);
372
10
        }
373
374
10
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
375
10
        auto elpased_ms = now - ctime_ms;
376
10
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
377
10
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
378
10
        g_bvar_recycler_instance_next_ts.put({instance_id},
379
10
                                             now + config::recycle_interval_seconds * 1000);
380
10
        g_bvar_recycler_instance_recycle_task_status.put({"completed"}, 1);
381
10
        LOG(INFO) << "recycle instance done, "
382
10
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
383
10
                  << " now: " << now;
384
385
10
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
386
387
10
        LOG_WARNING("finish recycle instance")
388
10
                .tag("instance_id", instance_id)
389
10
                .tag("cost_ms", elpased_ms);
390
10
    }
391
9
}
392
393
4
void Recycler::lease_recycle_jobs() {
394
54
    while (!stopped()) {
395
50
        std::vector<std::string> instances;
396
50
        instances.reserve(recycling_instance_map_.size());
397
50
        {
398
50
            std::lock_guard lock(mtx_);
399
50
            for (auto& [id, _] : recycling_instance_map_) {
400
30
                instances.push_back(id);
401
30
            }
402
50
        }
403
50
        for (auto& i : instances) {
404
30
            std::string recycle_job_key;
405
30
            job_recycle_key({i}, &recycle_job_key);
406
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
407
30
            if (ret == 1) {
408
0
                std::lock_guard lock(mtx_);
409
0
                if (auto it = recycling_instance_map_.find(i);
410
0
                    it != recycling_instance_map_.end()) {
411
0
                    it->second->stop();
412
0
                }
413
0
            }
414
30
        }
415
50
        {
416
50
            std::unique_lock lock(mtx_);
417
50
            notifier_.wait_for(lock,
418
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
419
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
419
100
                               [&]() { return stopped(); });
420
50
        }
421
50
    }
422
4
}
423
424
4
void Recycler::check_recycle_tasks() {
425
7
    while (!stopped()) {
426
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
427
3
        {
428
3
            std::lock_guard lock(mtx_);
429
3
            recycling_instance_map = recycling_instance_map_;
430
3
        }
431
3
        for (auto& entry : recycling_instance_map) {
432
0
            entry.second->check_recycle_tasks();
433
0
        }
434
435
3
        std::unique_lock lock(mtx_);
436
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
437
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
437
6
                           [&]() { return stopped(); });
438
3
    }
439
4
}
440
441
4
int Recycler::start(brpc::Server* server) {
442
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
443
4
    S3Environment::getInstance();
444
445
4
    if (config::enable_checker) {
446
0
        checker_ = std::make_unique<Checker>(txn_kv_);
447
0
        int ret = checker_->start();
448
0
        std::string msg;
449
0
        if (ret != 0) {
450
0
            msg = "failed to start checker";
451
0
            LOG(ERROR) << msg;
452
0
            std::cerr << msg << std::endl;
453
0
            return ret;
454
0
        }
455
0
        msg = "checker started";
456
0
        LOG(INFO) << msg;
457
0
        std::cout << msg << std::endl;
458
0
    }
459
460
4
    if (server) {
461
        // Add service
462
1
        auto recycler_service =
463
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
464
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
465
1
    }
466
467
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
467
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
468
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
469
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
469
8
        workers_.emplace_back([this] { recycle_callback(); });
470
8
    }
471
472
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
473
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
474
475
4
    if (config::enable_snapshot_data_migrator) {
476
0
        snapshot_data_migrator_ = std::make_shared<SnapshotDataMigrator>(txn_kv_);
477
0
        int ret = snapshot_data_migrator_->start();
478
0
        if (ret != 0) {
479
0
            LOG(ERROR) << "failed to start snapshot data migrator";
480
0
            return ret;
481
0
        }
482
0
        LOG(INFO) << "snapshot data migrator started";
483
0
    }
484
485
4
    if (config::enable_snapshot_chain_compactor) {
486
0
        snapshot_chain_compactor_ = std::make_shared<SnapshotChainCompactor>(txn_kv_);
487
0
        int ret = snapshot_chain_compactor_->start();
488
0
        if (ret != 0) {
489
0
            LOG(ERROR) << "failed to start snapshot chain compactor";
490
0
            return ret;
491
0
        }
492
0
        LOG(INFO) << "snapshot chain compactor started";
493
0
    }
494
495
4
    return 0;
496
4
}
497
498
4
void Recycler::stop() {
499
4
    stopped_ = true;
500
4
    notifier_.notify_all();
501
4
    pending_instance_cond_.notify_all();
502
4
    {
503
4
        std::lock_guard lock(mtx_);
504
4
        for (auto& [_, recycler] : recycling_instance_map_) {
505
0
            recycler->stop();
506
0
        }
507
4
    }
508
20
    for (auto& w : workers_) {
509
20
        if (w.joinable()) w.join();
510
20
    }
511
4
    if (checker_) {
512
0
        checker_->stop();
513
0
    }
514
4
    if (snapshot_data_migrator_) {
515
0
        snapshot_data_migrator_->stop();
516
0
    }
517
4
    if (snapshot_chain_compactor_) {
518
0
        snapshot_chain_compactor_->stop();
519
0
    }
520
4
}
521
522
class InstanceRecycler::InvertedIndexIdCache {
523
public:
524
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
525
135
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
526
527
    // Return 0 if success, 1 if schema kv not found, negative for error
528
    // For the same index_id, schema_version, res, since `get` is not completely atomic
529
    // one thread has not finished inserting, and another thread has not get the index_id and schema_version,
530
    // resulting in repeated addition and inaccuracy.
531
    // however, this approach can reduce the lock range and sacrifice a bit of meta repeated get to improve concurrency performance.
532
    // repeated addition does not affect correctness.
533
28.4k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
534
28.4k
        {
535
28.4k
            std::lock_guard lock(mtx_);
536
28.4k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
537
4.02k
                return 0;
538
4.02k
            }
539
24.3k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
540
24.3k
                it != inverted_index_id_map_.end()) {
541
17.9k
                res = it->second;
542
17.9k
                return 0;
543
17.9k
            }
544
24.3k
        }
545
        // Get schema from kv
546
        // TODO(plat1ko): Single flight
547
6.39k
        std::unique_ptr<Transaction> txn;
548
6.39k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
549
6.39k
        if (err != TxnErrorCode::TXN_OK) {
550
0
            LOG(WARNING) << "failed to create txn, err=" << err;
551
0
            return -1;
552
0
        }
553
6.39k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
554
6.39k
        ValueBuf val_buf;
555
6.39k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
556
6.39k
        if (err != TxnErrorCode::TXN_OK) {
557
500
            LOG(WARNING) << "failed to get schema, err=" << err;
558
500
            return static_cast<int>(err);
559
500
        }
560
5.89k
        doris::TabletSchemaCloudPB schema;
561
5.89k
        if (!parse_schema_value(val_buf, &schema)) {
562
0
            LOG(WARNING) << "malformed schema value, key=" << hex(schema_key);
563
0
            return -1;
564
0
        }
565
5.89k
        if (schema.index_size() > 0) {
566
4.22k
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
567
4.22k
            if (schema.has_inverted_index_storage_format()) {
568
4.21k
                index_format = schema.inverted_index_storage_format();
569
4.21k
            }
570
4.22k
            res.first = index_format;
571
4.22k
            res.second.reserve(schema.index_size());
572
10.6k
            for (auto& i : schema.index()) {
573
10.6k
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
574
10.6k
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
575
10.6k
                }
576
10.6k
            }
577
4.22k
        }
578
5.89k
        insert(index_id, schema_version, res);
579
5.89k
        return 0;
580
5.89k
    }
581
582
    // Empty `ids` means this schema has no inverted index
583
5.89k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
584
5.89k
        if (index_info.second.empty()) {
585
1.67k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
586
1.67k
            std::lock_guard lock(mtx_);
587
1.67k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
588
4.22k
        } else {
589
4.22k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
590
4.22k
            std::lock_guard lock(mtx_);
591
4.22k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
592
4.22k
        }
593
5.89k
    }
594
595
private:
596
    std::string instance_id_;
597
    std::shared_ptr<TxnKv> txn_kv_;
598
599
    std::mutex mtx_;
600
    using Key = std::pair<int64_t, int32_t>; // <index_id, schema_version>
601
    struct HashOfKey {
602
58.6k
        size_t operator()(const Key& key) const {
603
58.6k
            size_t seed = 0;
604
58.6k
            seed = std::hash<int64_t> {}(key.first);
605
58.6k
            seed = std::hash<int32_t> {}(key.second);
606
58.6k
            return seed;
607
58.6k
        }
608
    };
609
    // <index_id, schema_version> -> inverted_index_ids
610
    std::unordered_map<Key, InvertedIndexInfo, HashOfKey> inverted_index_id_map_;
611
    // Store <index_id, schema_version> of schema which doesn't have inverted index
612
    std::unordered_set<Key, HashOfKey> schemas_without_inverted_index_;
613
};
614
615
InstanceRecycler::InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
616
                                   RecyclerThreadPoolGroup thread_pool_group,
617
                                   std::shared_ptr<TxnLazyCommitter> txn_lazy_committer)
618
        : txn_kv_(std::move(txn_kv)),
619
          instance_id_(instance.instance_id()),
620
          instance_info_(instance),
621
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
622
          _thread_pool_group(std::move(thread_pool_group)),
623
          txn_lazy_committer_(std::move(txn_lazy_committer)),
624
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
625
135
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
626
135
    delete_bitmap_lock_white_list_->init();
627
135
    resource_mgr_->init();
628
629
135
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
630
631
    // Since the recycler's resource manager could not be notified when instance info changes,
632
    // we need to refresh the instance info here to ensure the resource manager has the latest info.
633
135
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
634
135
};
635
636
135
InstanceRecycler::~InstanceRecycler() = default;
637
638
119
int InstanceRecycler::init_obj_store_accessors() {
639
119
    for (const auto& obj_info : instance_info_.obj_info()) {
640
78
#ifdef UNIT_TEST
641
78
        auto accessor = std::make_shared<MockAccessor>();
642
#else
643
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
644
        if (!s3_conf) {
645
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
646
            return -1;
647
        }
648
649
        std::shared_ptr<S3Accessor> accessor;
650
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
651
        if (ret != 0) {
652
            LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
653
                         << " resource_id=" << obj_info.id();
654
            return ret;
655
        }
656
#endif
657
78
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
658
78
    }
659
660
119
    return 0;
661
119
}
662
663
119
int InstanceRecycler::init_storage_vault_accessors() {
664
119
    if (instance_info_.resource_ids().empty()) {
665
112
        return 0;
666
112
    }
667
668
7
    FullRangeGetOptions opts(txn_kv_);
669
7
    opts.prefetch = true;
670
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
671
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
672
673
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
674
18
        auto [k, v] = *kv;
675
18
        StorageVaultPB vault;
676
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
677
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
678
0
            return -1;
679
0
        }
680
18
        std::string recycler_storage_vault_white_list = accumulate(
681
18
                config::recycler_storage_vault_white_list.begin(),
682
18
                config::recycler_storage_vault_white_list.end(), std::string(),
683
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
683
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
684
18
        LOG_INFO("config::recycler_storage_vault_white_list")
685
18
                .tag("", recycler_storage_vault_white_list);
686
18
        if (!config::recycler_storage_vault_white_list.empty()) {
687
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
688
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
689
8
                it == config::recycler_storage_vault_white_list.end()) {
690
2
                LOG_WARNING(
691
2
                        "failed to init accessor for vault because this vault is not in "
692
2
                        "config::recycler_storage_vault_white_list. ")
693
2
                        .tag(" vault name:", vault.name())
694
2
                        .tag(" config::recycler_storage_vault_white_list:",
695
2
                             recycler_storage_vault_white_list);
696
2
                continue;
697
2
            }
698
8
        }
699
16
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
700
16
                                 &accessor_map_, &vault);
701
16
        if (vault.has_hdfs_info()) {
702
9
#ifdef ENABLE_HDFS_STORAGE_VAULT
703
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
704
9
            int ret = accessor->init();
705
9
            if (ret != 0) {
706
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
707
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
708
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
709
4
                continue;
710
4
            }
711
5
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
712
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
713
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
714
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
715
#else
716
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
717
                       << "but HDFS storage vaults were detected";
718
#endif
719
7
        } else if (vault.has_obj_info()) {
720
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
721
7
            if (!s3_conf) {
722
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
723
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
724
1
                continue;
725
1
            }
726
727
6
            std::shared_ptr<S3Accessor> accessor;
728
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
729
6
            if (ret != 0) {
730
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
731
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
732
0
                             << " ret=" << ret
733
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
734
0
                continue;
735
0
            }
736
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
737
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
738
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
739
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
740
6
        }
741
16
    }
742
743
7
    if (!it->is_valid()) {
744
0
        LOG_WARNING("failed to get storage vault kv");
745
0
        return -1;
746
0
    }
747
748
7
    if (accessor_map_.empty()) {
749
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
750
1
        return -2;
751
1
    }
752
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
753
6
             instance_id_);
754
755
6
    return 0;
756
7
}
757
758
119
int InstanceRecycler::init() {
759
119
    int ret = init_obj_store_accessors();
760
119
    if (ret != 0) {
761
0
        return ret;
762
0
    }
763
764
119
    return init_storage_vault_accessors();
765
119
}
766
767
template <typename... Func>
768
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
769
120
    return [funcs...]() {
770
120
        return [](std::initializer_list<int> ret_vals) {
771
120
            int i = 0;
772
140
            for (int ret : ret_vals) {
773
140
                if (ret != 0) {
774
0
                    i = ret;
775
0
                }
776
140
            }
777
120
            return i;
778
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
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
0
                    i = ret;
775
0
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
0
                    i = ret;
775
0
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
20
            for (int ret : ret_vals) {
773
20
                if (ret != 0) {
774
0
                    i = ret;
775
0
                }
776
20
            }
777
10
            return i;
778
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
0
                    i = ret;
775
0
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
0
                    i = ret;
775
0
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
0
                    i = ret;
775
0
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
20
            for (int ret : ret_vals) {
773
20
                if (ret != 0) {
774
0
                    i = ret;
775
0
                }
776
20
            }
777
10
            return i;
778
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
0
                    i = ret;
775
0
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
0
                    i = ret;
775
0
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
0
                    i = ret;
775
0
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
0
                    i = ret;
775
0
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
0
                    i = ret;
775
0
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
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
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
780
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
768
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
780
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
768
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
780
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
768
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
780
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
768
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
780
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
768
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
780
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
768
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
780
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
768
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
780
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
768
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
780
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
768
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
780
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
768
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
780
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
768
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
780
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
768
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
769
10
    return [funcs...]() {
770
10
        return [](std::initializer_list<int> ret_vals) {
771
10
            int i = 0;
772
10
            for (int ret : ret_vals) {
773
10
                if (ret != 0) {
774
10
                    i = ret;
775
10
                }
776
10
            }
777
10
            return i;
778
10
        }({funcs()...});
779
10
    };
780
10
}
781
782
10
int InstanceRecycler::do_recycle() {
783
10
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
784
10
    tablet_metrics_context_.reset();
785
10
    segment_metrics_context_.reset();
786
10
    DORIS_CLOUD_DEFER {
787
10
        tablet_metrics_context_.finish_report();
788
10
        segment_metrics_context_.finish_report();
789
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
786
10
    DORIS_CLOUD_DEFER {
787
10
        tablet_metrics_context_.finish_report();
788
10
        segment_metrics_context_.finish_report();
789
10
    };
790
10
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
791
0
        int res = recycle_cluster_snapshots();
792
0
        if (res != 0) {
793
0
            return -1;
794
0
        }
795
0
        return recycle_deleted_instance();
796
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
797
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
798
10
                                        fmt::format("instance id {}", instance_id_),
799
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
799
120
                                        [](int r) { return r != 0; });
800
10
        sync_executor
801
10
                .add(task_wrapper(
802
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
802
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
803
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
803
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
804
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
805
                                   // becase they may both recycle the same set of tablets
806
                        // recycle dropped table or idexes(mv, rollup)
807
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
807
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
808
                        // recycle dropped partitions
809
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
809
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
810
10
                .add(task_wrapper(
811
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
811
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
812
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
812
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
813
10
                .add(task_wrapper(
814
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
814
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
815
10
                .add(task_wrapper(
816
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
816
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
817
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
817
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
818
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
818
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
819
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
819
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
820
10
                .add(task_wrapper(
821
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
821
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
822
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
822
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
823
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
823
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
824
10
        bool finished = true;
825
10
        std::vector<int> rets = sync_executor.when_all(&finished);
826
120
        for (int ret : rets) {
827
120
            if (ret != 0) {
828
0
                return ret;
829
0
            }
830
120
        }
831
10
        return finished ? 0 : -1;
832
10
    } else {
833
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
834
0
                     << " instance_id=" << instance_id_;
835
0
        return -1;
836
0
    }
837
10
}
838
839
/**
840
* 1. delete all remote data
841
* 2. delete all kv
842
* 3. remove instance kv
843
*/
844
5
int InstanceRecycler::recycle_deleted_instance() {
845
5
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
846
847
5
    int ret = 0;
848
5
    auto start_time = steady_clock::now();
849
850
5
    DORIS_CLOUD_DEFER {
851
5
        auto cost = duration<float>(steady_clock::now() - start_time).count();
852
5
        LOG(WARNING) << (ret == 0 ? "successfully" : "failed to")
853
5
                     << " recycle deleted instance, cost=" << cost
854
5
                     << "s, instance_id=" << instance_id_;
855
5
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
850
5
    DORIS_CLOUD_DEFER {
851
5
        auto cost = duration<float>(steady_clock::now() - start_time).count();
852
5
        LOG(WARNING) << (ret == 0 ? "successfully" : "failed to")
853
5
                     << " recycle deleted instance, cost=" << cost
854
5
                     << "s, instance_id=" << instance_id_;
855
5
    };
856
857
    // Step 1: Recycle tmp rowsets (contains ref count but txn is not committed)
858
5
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
859
5
        int res = recycle_tmp_rowsets();
860
5
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
861
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
862
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
863
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
864
            // and cannot be recycled.
865
5
            res = recycle_tmp_rowsets();
866
5
        }
867
5
        return res;
868
5
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_1clEv
Line
Count
Source
858
5
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
859
5
        int res = recycle_tmp_rowsets();
860
5
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
861
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
862
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
863
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
864
            // and cannot be recycled.
865
5
            res = recycle_tmp_rowsets();
866
5
        }
867
5
        return res;
868
5
    };
869
5
    if (recycle_tmp_rowsets_with_mark_delete_enabled() != 0) {
870
0
        LOG_WARNING("failed to recycle tmp rowsets").tag("instance_id", instance_id_);
871
0
        ret = -1;
872
0
        return -1;
873
0
    }
874
875
    // Step 2: Recycle versioned rowsets in recycle space (already marked for deletion)
876
5
    if (recycle_versioned_rowsets() != 0) {
877
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
878
0
        ret = -1;
879
0
        return -1;
880
0
    }
881
882
    // Step 3: Recycle operation logs (can recycle logs not referenced by snapshots)
883
5
    if (recycle_operation_logs() != 0) {
884
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
885
0
        ret = -1;
886
0
        return -1;
887
0
    }
888
889
    // Step 4: Check if there are still cluster snapshots
890
5
    bool has_snapshots = false;
891
5
    if (has_cluster_snapshots(&has_snapshots) != 0) {
892
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
893
0
        ret = -1;
894
0
        return -1;
895
5
    } else if (has_snapshots) {
896
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
897
1
        return 0;
898
1
    }
899
900
4
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
901
4
                            instance_info().snapshot_switch_status() !=
902
1
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
903
4
    if (snapshot_enabled) {
904
1
        bool has_unrecycled_rowsets = false;
905
1
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
906
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
907
0
            ret = -1;
908
0
            return -1;
909
1
        } else if (has_unrecycled_rowsets) {
910
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
911
0
                    .tag("instance_id", instance_id_);
912
0
            return ret;
913
0
        }
914
3
    } else { // delete all remote data if snapshot is disabled
915
3
        for (auto& [_, accessor] : accessor_map_) {
916
3
            if (stopped()) {
917
0
                return ret;
918
0
            }
919
920
3
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
921
3
            int del_ret = accessor->delete_all();
922
3
            if (del_ret == 0) {
923
3
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
924
3
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
925
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
926
                // so the recycling has been successful.
927
0
                ret = -1;
928
0
            }
929
3
        }
930
931
3
        if (ret != 0) {
932
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
933
0
            return ret;
934
0
        }
935
3
    }
936
937
    // Check successor instance, if exists, skip deleting kv because successor instance may still need the data in kv
938
4
    if (instance_info_.has_successor_instance_id() &&
939
4
        !instance_info_.successor_instance_id().empty()) {
940
0
        std::string key = instance_key(instance_info_.successor_instance_id());
941
0
        std::unique_ptr<Transaction> txn;
942
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
943
0
        if (err != TxnErrorCode::TXN_OK) {
944
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_
945
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
946
0
                         << " err=" << err;
947
0
            ret = -1;
948
0
            return -1;
949
0
        }
950
951
0
        std::string value;
952
0
        err = txn->get(key, &value);
953
0
        if (err == TxnErrorCode::TXN_OK) {
954
0
            LOG(INFO) << "instance successor instance is still exist, skip deleting kv,"
955
0
                      << " instance_id=" << instance_id_
956
0
                      << " successor_instance_id=" << instance_info_.successor_instance_id();
957
0
            return 0;
958
0
        } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
959
0
            LOG(WARNING) << "failed to get successor instance, instance_id=" << instance_id_
960
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
961
0
                         << " err=" << err;
962
0
            ret = -1;
963
0
            return -1;
964
0
        }
965
0
    }
966
967
    // delete all kv
968
4
    std::unique_ptr<Transaction> txn;
969
4
    TxnErrorCode err = txn_kv_->create_txn(&txn);
970
4
    if (err != TxnErrorCode::TXN_OK) {
971
0
        LOG(WARNING) << "failed to create txn";
972
0
        ret = -1;
973
0
        return -1;
974
0
    }
975
4
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
976
    // delete kv before deleting objects to prevent the checker from misjudging data loss
977
4
    std::string start_txn_key = txn_key_prefix(instance_id_);
978
4
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
979
4
    txn->remove(start_txn_key, end_txn_key);
980
4
    std::string start_version_key = version_key_prefix(instance_id_);
981
4
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
982
4
    txn->remove(start_version_key, end_version_key);
983
4
    std::string start_meta_key = meta_key_prefix(instance_id_);
984
4
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
985
4
    txn->remove(start_meta_key, end_meta_key);
986
4
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
987
4
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
988
4
    txn->remove(start_recycle_key, end_recycle_key);
989
4
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
990
4
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
991
4
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
992
4
    std::string start_copy_key = copy_key_prefix(instance_id_);
993
4
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
994
4
    txn->remove(start_copy_key, end_copy_key);
995
    // should not remove job key range, because we need to reserve job recycle kv
996
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
997
4
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
998
4
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
999
4
    txn->remove(start_job_tablet_key, end_job_tablet_key);
1000
4
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
1001
4
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
1002
4
    std::string start_vault_key = storage_vault_key(key_info0);
1003
4
    std::string end_vault_key = storage_vault_key(key_info1);
1004
4
    txn->remove(start_vault_key, end_vault_key);
1005
4
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
1006
4
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
1007
4
    txn->remove(versioned_version_key_start, versioned_version_key_end);
1008
4
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
1009
4
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
1010
4
    txn->remove(versioned_index_key_start, versioned_index_key_end);
1011
4
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
1012
4
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
1013
4
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
1014
4
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
1015
4
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
1016
4
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
1017
4
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
1018
4
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
1019
4
    txn->remove(versioned_data_key_start, versioned_data_key_end);
1020
4
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
1021
4
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
1022
4
    txn->remove(versioned_log_key_start, versioned_log_key_end);
1023
4
    err = txn->commit();
1024
4
    if (err != TxnErrorCode::TXN_OK) {
1025
0
        LOG(WARNING) << "failed to delete all kv, instance_id=" << instance_id_ << ", err=" << err;
1026
0
        ret = -1;
1027
0
    }
1028
1029
4
    if (ret == 0) {
1030
        // remove instance kv
1031
        // ATTN: MUST ensure that cloud platform won't regenerate the same instance id
1032
4
        err = txn_kv_->create_txn(&txn);
1033
4
        if (err != TxnErrorCode::TXN_OK) {
1034
0
            LOG(WARNING) << "failed to create txn";
1035
0
            ret = -1;
1036
0
            return ret;
1037
0
        }
1038
4
        std::string key;
1039
4
        instance_key({instance_id_}, &key);
1040
4
        txn->atomic_add(system_meta_service_instance_update_key(), 1);
1041
4
        txn->remove(key);
1042
4
        err = txn->commit();
1043
4
        if (err != TxnErrorCode::TXN_OK) {
1044
0
            LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
1045
0
                         << " err=" << err;
1046
0
            ret = -1;
1047
0
        }
1048
4
    }
1049
4
    return ret;
1050
4
}
1051
1052
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
1053
9
                                          bool* exists, PackedFileRecycleStats* stats) {
1054
9
    if (exists == nullptr) {
1055
0
        return -1;
1056
0
    }
1057
9
    *exists = false;
1058
1059
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
1060
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1061
9
    std::string scan_begin = begin;
1062
1063
9
    while (true) {
1064
9
        std::unique_ptr<RangeGetIterator> it_range;
1065
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
1066
9
        if (get_ret < 0) {
1067
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1068
0
                    .tag("instance_id", instance_id_)
1069
0
                    .tag("tablet_id", tablet_id)
1070
0
                    .tag("ret", get_ret);
1071
0
            return -1;
1072
0
        }
1073
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1074
6
            return 0;
1075
6
        }
1076
1077
3
        std::string last_key;
1078
3
        while (it_range->has_next()) {
1079
3
            auto [k, v] = it_range->next();
1080
3
            last_key.assign(k.data(), k.size());
1081
3
            doris::RowsetMetaCloudPB rowset_meta;
1082
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1083
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1084
0
                        .tag("instance_id", instance_id_)
1085
0
                        .tag("tablet_id", tablet_id)
1086
0
                        .tag("key", hex(k));
1087
0
                continue;
1088
0
            }
1089
3
            if (stats) {
1090
3
                ++stats->rowset_scan_count;
1091
3
            }
1092
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1093
3
                *exists = true;
1094
3
                return 0;
1095
3
            }
1096
3
        }
1097
1098
0
        if (!it_range->more()) {
1099
0
            return 0;
1100
0
        }
1101
1102
        // Continue scanning from the next key to keep each transaction short.
1103
0
        scan_begin = std::move(last_key);
1104
0
        scan_begin.push_back('\x00');
1105
0
    }
1106
9
}
1107
1108
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1109
                                                          const std::string& rowset_id,
1110
                                                          int64_t txn_id, bool* recycle_exists,
1111
11
                                                          bool* tmp_exists) {
1112
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1113
0
        return -1;
1114
0
    }
1115
11
    *recycle_exists = false;
1116
11
    *tmp_exists = false;
1117
1118
11
    if (txn_id <= 0) {
1119
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1120
0
                .tag("instance_id", instance_id_)
1121
0
                .tag("tablet_id", tablet_id)
1122
0
                .tag("rowset_id", rowset_id)
1123
0
                .tag("txn_id", txn_id);
1124
0
        return -1;
1125
0
    }
1126
1127
11
    std::unique_ptr<Transaction> txn;
1128
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1129
11
    if (err != TxnErrorCode::TXN_OK) {
1130
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1131
0
                .tag("instance_id", instance_id_)
1132
0
                .tag("tablet_id", tablet_id)
1133
0
                .tag("rowset_id", rowset_id)
1134
0
                .tag("txn_id", txn_id)
1135
0
                .tag("err", err);
1136
0
        return -1;
1137
0
    }
1138
1139
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1140
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1141
11
    if (ret == TxnErrorCode::TXN_OK) {
1142
1
        *recycle_exists = true;
1143
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1144
0
        LOG_WARNING("failed to check recycle rowset existence")
1145
0
                .tag("instance_id", instance_id_)
1146
0
                .tag("tablet_id", tablet_id)
1147
0
                .tag("rowset_id", rowset_id)
1148
0
                .tag("key", hex(recycle_key))
1149
0
                .tag("err", ret);
1150
0
        return -1;
1151
0
    }
1152
1153
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1154
11
    ret = key_exists(txn.get(), tmp_key, true);
1155
11
    if (ret == TxnErrorCode::TXN_OK) {
1156
1
        *tmp_exists = true;
1157
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1158
0
        LOG_WARNING("failed to check tmp rowset existence")
1159
0
                .tag("instance_id", instance_id_)
1160
0
                .tag("tablet_id", tablet_id)
1161
0
                .tag("txn_id", txn_id)
1162
0
                .tag("key", hex(tmp_key))
1163
0
                .tag("err", ret);
1164
0
        return -1;
1165
0
    }
1166
1167
11
    return 0;
1168
11
}
1169
1170
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1171
8
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1172
8
    if (!hint.empty()) {
1173
8
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1174
8
            return {hint, it->second};
1175
8
        }
1176
8
    }
1177
1178
0
    return {"", nullptr};
1179
8
}
1180
1181
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1182
                                               const std::string& packed_file_path,
1183
3
                                               PackedFileRecycleStats* stats) {
1184
3
    bool local_changed = false;
1185
3
    int64_t left_num = 0;
1186
3
    int64_t left_bytes = 0;
1187
3
    bool all_small_files_confirmed = true;
1188
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1189
1190
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1191
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1192
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1193
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1194
14
        LOG_INFO("packed slice correction status")
1195
14
                .tag("instance_id", instance_id_)
1196
14
                .tag("packed_file_path", packed_file_path)
1197
14
                .tag("small_file_path", file.path())
1198
14
                .tag("tablet_id", tablet_id)
1199
14
                .tag("rowset_id", rowset_id)
1200
14
                .tag("txn_id", txn_id)
1201
14
                .tag("size", file.size())
1202
14
                .tag("deleted", file.deleted())
1203
14
                .tag("corrected", file.corrected())
1204
14
                .tag("confirmed_this_round", confirmed_this_round);
1205
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
1190
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1191
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1192
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1193
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1194
14
        LOG_INFO("packed slice correction status")
1195
14
                .tag("instance_id", instance_id_)
1196
14
                .tag("packed_file_path", packed_file_path)
1197
14
                .tag("small_file_path", file.path())
1198
14
                .tag("tablet_id", tablet_id)
1199
14
                .tag("rowset_id", rowset_id)
1200
14
                .tag("txn_id", txn_id)
1201
14
                .tag("size", file.size())
1202
14
                .tag("deleted", file.deleted())
1203
14
                .tag("corrected", file.corrected())
1204
14
                .tag("confirmed_this_round", confirmed_this_round);
1205
14
    };
1206
1207
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1208
14
        auto* small_file = packed_info->mutable_slices(i);
1209
14
        if (small_file->deleted()) {
1210
3
            log_small_file_status(*small_file, small_file->corrected());
1211
3
            continue;
1212
3
        }
1213
1214
11
        if (small_file->corrected()) {
1215
0
            left_num++;
1216
0
            left_bytes += small_file->size();
1217
0
            log_small_file_status(*small_file, true);
1218
0
            continue;
1219
0
        }
1220
1221
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1222
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1223
0
                    .tag("instance_id", instance_id_)
1224
0
                    .tag("small_file_path", small_file->path())
1225
0
                    .tag("index", i);
1226
0
            return -1;
1227
0
        }
1228
1229
11
        int64_t tablet_id = small_file->tablet_id();
1230
11
        const std::string& rowset_id = small_file->rowset_id();
1231
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1232
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1233
0
                    .tag("instance_id", instance_id_)
1234
0
                    .tag("small_file_path", small_file->path())
1235
0
                    .tag("index", i)
1236
0
                    .tag("tablet_id", tablet_id)
1237
0
                    .tag("rowset_id", rowset_id)
1238
0
                    .tag("has_txn_id", small_file->has_txn_id())
1239
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1240
0
            return -1;
1241
0
        }
1242
11
        int64_t txn_id = small_file->txn_id();
1243
11
        bool recycle_exists = false;
1244
11
        bool tmp_exists = false;
1245
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1246
11
                                                &tmp_exists) != 0) {
1247
0
            return -1;
1248
0
        }
1249
1250
11
        bool small_file_confirmed = false;
1251
11
        if (tmp_exists) {
1252
1
            left_num++;
1253
1
            left_bytes += small_file->size();
1254
1
            small_file_confirmed = true;
1255
10
        } else if (recycle_exists) {
1256
1
            left_num++;
1257
1
            left_bytes += small_file->size();
1258
            // keep small_file_confirmed=false so the packed file remains uncorrected
1259
9
        } else {
1260
9
            bool rowset_exists = false;
1261
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1262
0
                return -1;
1263
0
            }
1264
1265
9
            if (!rowset_exists) {
1266
6
                if (!small_file->deleted()) {
1267
6
                    small_file->set_deleted(true);
1268
6
                    local_changed = true;
1269
6
                }
1270
6
                if (!small_file->corrected()) {
1271
6
                    small_file->set_corrected(true);
1272
6
                    local_changed = true;
1273
6
                }
1274
6
                small_file_confirmed = true;
1275
6
            } else {
1276
3
                left_num++;
1277
3
                left_bytes += small_file->size();
1278
3
                small_file_confirmed = true;
1279
3
            }
1280
9
        }
1281
1282
11
        if (!small_file_confirmed) {
1283
1
            all_small_files_confirmed = false;
1284
1
        }
1285
1286
11
        if (small_file->corrected() != small_file_confirmed) {
1287
4
            small_file->set_corrected(small_file_confirmed);
1288
4
            local_changed = true;
1289
4
        }
1290
1291
11
        log_small_file_status(*small_file, small_file_confirmed);
1292
11
    }
1293
1294
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1295
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1296
3
        local_changed = true;
1297
3
    }
1298
3
    if (packed_info->ref_cnt() != left_num) {
1299
3
        auto old_ref_cnt = packed_info->ref_cnt();
1300
3
        packed_info->set_ref_cnt(left_num);
1301
3
        LOG_INFO("corrected packed file ref count")
1302
3
                .tag("instance_id", instance_id_)
1303
3
                .tag("resource_id", packed_info->resource_id())
1304
3
                .tag("packed_file_path", packed_file_path)
1305
3
                .tag("old_ref_cnt", old_ref_cnt)
1306
3
                .tag("new_ref_cnt", left_num);
1307
3
        local_changed = true;
1308
3
    }
1309
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1310
2
        packed_info->set_corrected(all_small_files_confirmed);
1311
2
        local_changed = true;
1312
2
    }
1313
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1314
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1315
1
        local_changed = true;
1316
1
    }
1317
1318
3
    if (changed != nullptr) {
1319
3
        *changed = local_changed;
1320
3
    }
1321
3
    return 0;
1322
3
}
1323
1324
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1325
                                                 const std::string& packed_file_path,
1326
4
                                                 PackedFileRecycleStats* stats) {
1327
4
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1328
4
    bool correction_ok = false;
1329
4
    cloud::PackedFileInfoPB packed_info;
1330
1331
4
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1332
4
        if (stopped()) {
1333
0
            LOG_WARNING("recycler stopped before processing packed file")
1334
0
                    .tag("instance_id", instance_id_)
1335
0
                    .tag("packed_file_path", packed_file_path)
1336
0
                    .tag("attempt", attempt);
1337
0
            return -1;
1338
0
        }
1339
1340
4
        std::unique_ptr<Transaction> txn;
1341
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1342
4
        if (err != TxnErrorCode::TXN_OK) {
1343
0
            LOG_WARNING("failed to create txn when processing packed file")
1344
0
                    .tag("instance_id", instance_id_)
1345
0
                    .tag("packed_file_path", packed_file_path)
1346
0
                    .tag("attempt", attempt)
1347
0
                    .tag("err", err);
1348
0
            return -1;
1349
0
        }
1350
1351
4
        std::string packed_val;
1352
4
        err = txn->get(packed_key, &packed_val);
1353
4
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1354
0
            return 0;
1355
0
        }
1356
4
        if (err != TxnErrorCode::TXN_OK) {
1357
0
            LOG_WARNING("failed to get packed file kv")
1358
0
                    .tag("instance_id", instance_id_)
1359
0
                    .tag("packed_file_path", packed_file_path)
1360
0
                    .tag("attempt", attempt)
1361
0
                    .tag("err", err);
1362
0
            return -1;
1363
0
        }
1364
1365
4
        if (!packed_info.ParseFromString(packed_val)) {
1366
0
            LOG_WARNING("failed to parse packed file info")
1367
0
                    .tag("instance_id", instance_id_)
1368
0
                    .tag("packed_file_path", packed_file_path)
1369
0
                    .tag("attempt", attempt);
1370
0
            return -1;
1371
0
        }
1372
1373
4
        int64_t now_sec = ::time(nullptr);
1374
4
        bool corrected = packed_info.corrected();
1375
4
        bool due = config::force_immediate_recycle ||
1376
4
                   now_sec - packed_info.created_at_sec() >=
1377
4
                           config::packed_file_correction_delay_seconds;
1378
1379
4
        if (!corrected && due) {
1380
3
            bool changed = false;
1381
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1382
0
                LOG_WARNING("correct_packed_file_info failed")
1383
0
                        .tag("instance_id", instance_id_)
1384
0
                        .tag("packed_file_path", packed_file_path)
1385
0
                        .tag("attempt", attempt);
1386
0
                return -1;
1387
0
            }
1388
3
            if (changed) {
1389
3
                std::string updated;
1390
3
                if (!packed_info.SerializeToString(&updated)) {
1391
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1392
0
                            .tag("instance_id", instance_id_)
1393
0
                            .tag("packed_file_path", packed_file_path)
1394
0
                            .tag("attempt", attempt);
1395
0
                    return -1;
1396
0
                }
1397
3
                txn->put(packed_key, updated);
1398
3
                err = txn->commit();
1399
3
                if (err == TxnErrorCode::TXN_OK) {
1400
3
                    if (stats) {
1401
3
                        ++stats->num_corrected;
1402
3
                    }
1403
3
                } else {
1404
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1405
0
                        LOG_WARNING(
1406
0
                                "failed to commit correction for packed file due to conflict, "
1407
0
                                "retrying")
1408
0
                                .tag("instance_id", instance_id_)
1409
0
                                .tag("packed_file_path", packed_file_path)
1410
0
                                .tag("attempt", attempt);
1411
0
                        sleep_for_packed_file_retry();
1412
0
                        packed_info.Clear();
1413
0
                        continue;
1414
0
                    }
1415
0
                    LOG_WARNING("failed to commit correction for packed file")
1416
0
                            .tag("instance_id", instance_id_)
1417
0
                            .tag("packed_file_path", packed_file_path)
1418
0
                            .tag("attempt", attempt)
1419
0
                            .tag("err", err);
1420
0
                    return -1;
1421
0
                }
1422
3
            }
1423
3
        }
1424
1425
4
        correction_ok = true;
1426
4
        break;
1427
4
    }
1428
1429
4
    if (!correction_ok) {
1430
0
        return -1;
1431
0
    }
1432
1433
4
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1434
4
          packed_info.ref_cnt() == 0)) {
1435
3
        return 0;
1436
3
    }
1437
1438
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1439
0
        LOG_WARNING("packed file missing resource id when recycling")
1440
0
                .tag("instance_id", instance_id_)
1441
0
                .tag("packed_file_path", packed_file_path);
1442
0
        return -1;
1443
0
    }
1444
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1445
1
    if (!accessor) {
1446
0
        LOG_WARNING("no accessor available to delete packed file")
1447
0
                .tag("instance_id", instance_id_)
1448
0
                .tag("packed_file_path", packed_file_path)
1449
0
                .tag("resource_id", packed_info.resource_id());
1450
0
        return -1;
1451
0
    }
1452
1
    int del_ret = accessor->delete_file(packed_file_path);
1453
1
    if (del_ret != 0 && del_ret != 1) {
1454
0
        LOG_WARNING("failed to delete packed file")
1455
0
                .tag("instance_id", instance_id_)
1456
0
                .tag("packed_file_path", packed_file_path)
1457
0
                .tag("resource_id", resource_id)
1458
0
                .tag("ret", del_ret);
1459
0
        return -1;
1460
0
    }
1461
1
    if (del_ret == 1) {
1462
0
        LOG_INFO("packed file already removed")
1463
0
                .tag("instance_id", instance_id_)
1464
0
                .tag("packed_file_path", packed_file_path)
1465
0
                .tag("resource_id", resource_id);
1466
1
    } else {
1467
1
        LOG_INFO("deleted packed file")
1468
1
                .tag("instance_id", instance_id_)
1469
1
                .tag("packed_file_path", packed_file_path)
1470
1
                .tag("resource_id", resource_id);
1471
1
    }
1472
1473
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1474
1
        std::unique_ptr<Transaction> del_txn;
1475
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1476
1
        if (err != TxnErrorCode::TXN_OK) {
1477
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1478
0
                    .tag("instance_id", instance_id_)
1479
0
                    .tag("packed_file_path", packed_file_path)
1480
0
                    .tag("del_attempt", del_attempt)
1481
0
                    .tag("err", err);
1482
0
            return -1;
1483
0
        }
1484
1485
1
        std::string latest_val;
1486
1
        err = del_txn->get(packed_key, &latest_val);
1487
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1488
0
            return 0;
1489
0
        }
1490
1
        if (err != TxnErrorCode::TXN_OK) {
1491
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1492
0
                    .tag("instance_id", instance_id_)
1493
0
                    .tag("packed_file_path", packed_file_path)
1494
0
                    .tag("del_attempt", del_attempt)
1495
0
                    .tag("err", err);
1496
0
            return -1;
1497
0
        }
1498
1499
1
        cloud::PackedFileInfoPB latest_info;
1500
1
        if (!latest_info.ParseFromString(latest_val)) {
1501
0
            LOG_WARNING("failed to parse packed file info before removal")
1502
0
                    .tag("instance_id", instance_id_)
1503
0
                    .tag("packed_file_path", packed_file_path)
1504
0
                    .tag("del_attempt", del_attempt);
1505
0
            return -1;
1506
0
        }
1507
1508
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1509
1
              latest_info.ref_cnt() == 0)) {
1510
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1511
0
                    .tag("instance_id", instance_id_)
1512
0
                    .tag("packed_file_path", packed_file_path)
1513
0
                    .tag("del_attempt", del_attempt);
1514
0
            return 0;
1515
0
        }
1516
1517
1
        del_txn->remove(packed_key);
1518
1
        err = del_txn->commit();
1519
1
        if (err == TxnErrorCode::TXN_OK) {
1520
1
            if (stats) {
1521
1
                ++stats->num_deleted;
1522
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1523
1
                                        static_cast<int64_t>(latest_val.size());
1524
1
                if (del_ret == 0 || del_ret == 1) {
1525
1
                    ++stats->num_object_deleted;
1526
1
                    int64_t object_size = latest_info.total_slice_bytes();
1527
1
                    if (object_size <= 0) {
1528
0
                        object_size = packed_info.total_slice_bytes();
1529
0
                    }
1530
1
                    stats->bytes_object_deleted += object_size;
1531
1
                }
1532
1
            }
1533
1
            LOG_INFO("removed packed file metadata")
1534
1
                    .tag("instance_id", instance_id_)
1535
1
                    .tag("packed_file_path", packed_file_path);
1536
1
            return 0;
1537
1
        }
1538
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1539
0
            if (del_attempt >= max_retry_times) {
1540
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1541
0
                        .tag("instance_id", instance_id_)
1542
0
                        .tag("packed_file_path", packed_file_path)
1543
0
                        .tag("del_attempt", del_attempt);
1544
0
                return -1;
1545
0
            }
1546
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1547
0
                    .tag("instance_id", instance_id_)
1548
0
                    .tag("packed_file_path", packed_file_path)
1549
0
                    .tag("del_attempt", del_attempt);
1550
0
            sleep_for_packed_file_retry();
1551
0
            continue;
1552
0
        }
1553
0
        LOG_WARNING("failed to remove packed file kv")
1554
0
                .tag("instance_id", instance_id_)
1555
0
                .tag("packed_file_path", packed_file_path)
1556
0
                .tag("del_attempt", del_attempt)
1557
0
                .tag("err", err);
1558
0
        return -1;
1559
0
    }
1560
1561
0
    return -1;
1562
1
}
1563
1564
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view /*value*/,
1565
4
                                            PackedFileRecycleStats* stats, int* ret) {
1566
4
    if (stats) {
1567
4
        ++stats->num_scanned;
1568
4
    }
1569
4
    std::string packed_file_path;
1570
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1571
0
        LOG_WARNING("failed to decode packed file key")
1572
0
                .tag("instance_id", instance_id_)
1573
0
                .tag("key", hex(key));
1574
0
        if (stats) {
1575
0
            ++stats->num_failed;
1576
0
        }
1577
0
        if (ret) {
1578
0
            *ret = -1;
1579
0
        }
1580
0
        return 0;
1581
0
    }
1582
1583
4
    std::string packed_key(key);
1584
4
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1585
4
    if (process_ret != 0) {
1586
0
        if (stats) {
1587
0
            ++stats->num_failed;
1588
0
        }
1589
0
        if (ret) {
1590
0
            *ret = -1;
1591
0
        }
1592
0
    }
1593
4
    return 0;
1594
4
}
1595
1596
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1597
9.77k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1598
9.77k
    if (config::force_immediate_recycle) {
1599
15
        return 0L;
1600
15
    }
1601
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1602
9.75k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1603
9.75k
    int64_t retention_seconds = config::retention_seconds;
1604
9.75k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1605
7.80k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1606
7.80k
    }
1607
9.75k
    int64_t final_expiration = expiration + retention_seconds;
1608
9.75k
    if (*earlest_ts > final_expiration) {
1609
7
        *earlest_ts = final_expiration;
1610
7
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1611
7
    }
1612
9.75k
    return final_expiration;
1613
9.77k
}
1614
1615
int64_t calculate_partition_expired_time(
1616
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1617
9
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1618
9
    if (config::force_immediate_recycle) {
1619
3
        return 0L;
1620
3
    }
1621
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1622
6
                                                            : partition_meta_pb.creation_time();
1623
6
    int64_t retention_seconds = config::retention_seconds;
1624
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1625
6
        retention_seconds =
1626
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1627
6
    }
1628
6
    int64_t final_expiration = expiration + retention_seconds;
1629
6
    if (*earlest_ts > final_expiration) {
1630
2
        *earlest_ts = final_expiration;
1631
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1632
2
    }
1633
6
    return final_expiration;
1634
9
}
1635
1636
int64_t calculate_index_expired_time(const std::string& instance_id_,
1637
                                     const RecycleIndexPB& index_meta_pb,
1638
10
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1639
10
    if (config::force_immediate_recycle) {
1640
4
        return 0L;
1641
4
    }
1642
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1643
6
                                                        : index_meta_pb.creation_time();
1644
6
    int64_t retention_seconds = config::retention_seconds;
1645
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1646
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1647
6
    }
1648
6
    int64_t final_expiration = expiration + retention_seconds;
1649
6
    if (*earlest_ts > final_expiration) {
1650
2
        *earlest_ts = final_expiration;
1651
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1652
2
    }
1653
6
    return final_expiration;
1654
10
}
1655
1656
int64_t calculate_tmp_rowset_expired_time(
1657
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1658
106k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1659
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1660
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1661
    //  duration or timeout always < `retention_time` in practice.
1662
106k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1663
106k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1664
106k
                                 : tmp_rowset_meta_pb.creation_time();
1665
106k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1666
106k
    int64_t final_expiration = expiration + config::retention_seconds;
1667
106k
    if (*earlest_ts > final_expiration) {
1668
24
        *earlest_ts = final_expiration;
1669
24
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1670
24
    }
1671
106k
    return final_expiration;
1672
106k
}
1673
1674
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1675
30.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1676
30.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1677
30.0k
    if (*earlest_ts > final_expiration / 1000) {
1678
8
        *earlest_ts = final_expiration / 1000;
1679
8
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1680
8
    }
1681
30.0k
    return final_expiration;
1682
30.0k
}
1683
1684
int64_t calculate_restore_job_expired_time(
1685
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1686
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1687
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1688
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1689
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1690
        // final state, recycle immediately
1691
41
        return 0L;
1692
41
    }
1693
    // not final state, wait much longer than the FE's timeout(1 day)
1694
0
    int64_t last_modified_s =
1695
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1696
0
    int64_t expiration = restore_job.expired_at_s() > 0
1697
0
                                 ? last_modified_s + restore_job.expired_at_s()
1698
0
                                 : last_modified_s;
1699
0
    int64_t final_expiration = expiration + config::retention_seconds;
1700
0
    if (*earlest_ts > final_expiration) {
1701
0
        *earlest_ts = final_expiration;
1702
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1703
0
    }
1704
0
    return final_expiration;
1705
41
}
1706
1707
2
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1708
2
    AbortTxnRequest req;
1709
2
    TxnInfoPB txn_info;
1710
2
    MetaServiceCode code = MetaServiceCode::OK;
1711
2
    std::string msg;
1712
2
    std::stringstream ss;
1713
2
    std::unique_ptr<Transaction> txn;
1714
2
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1715
2
    if (err != TxnErrorCode::TXN_OK) {
1716
0
        LOG_WARNING("failed to create txn").tag("err", err);
1717
0
        return -1;
1718
0
    }
1719
1720
    // get txn index
1721
2
    TxnIndexPB txn_idx_pb;
1722
2
    auto index_key = txn_index_key({instance_id_, txn_id});
1723
2
    std::string index_val;
1724
2
    err = txn->get(index_key, &index_val);
1725
2
    if (err != TxnErrorCode::TXN_OK) {
1726
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1727
            // maybe recycled
1728
0
            LOG_INFO("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1729
0
                    .tag("key", hex(index_key))
1730
0
                    .tag("txn_id", txn_id);
1731
0
            return 0;
1732
0
        }
1733
0
        LOG_WARNING("failed to get txn index")
1734
0
                .tag("err", err)
1735
0
                .tag("key", hex(index_key))
1736
0
                .tag("txn_id", txn_id);
1737
0
        return -1;
1738
0
    }
1739
2
    if (!txn_idx_pb.ParseFromString(index_val)) {
1740
0
        LOG_WARNING("failed to parse txn index")
1741
0
                .tag("err", err)
1742
0
                .tag("key", hex(index_key))
1743
0
                .tag("txn_id", txn_id);
1744
0
        return -1;
1745
0
    }
1746
1747
2
    auto info_key = txn_info_key({instance_id_, txn_idx_pb.tablet_index().db_id(), txn_id});
1748
2
    std::string info_val;
1749
2
    err = txn->get(info_key, &info_val);
1750
2
    if (err != TxnErrorCode::TXN_OK) {
1751
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1752
            // maybe recycled
1753
0
            LOG_INFO("txn info not found, txn_id={} instance_id={}", txn_id, instance_id_)
1754
0
                    .tag("key", hex(info_key))
1755
0
                    .tag("txn_id", txn_id);
1756
0
            return 0;
1757
0
        }
1758
0
        LOG_WARNING("failed to get txn info")
1759
0
                .tag("err", err)
1760
0
                .tag("key", hex(info_key))
1761
0
                .tag("txn_id", txn_id);
1762
0
        return -1;
1763
0
    }
1764
2
    if (!txn_info.ParseFromString(info_val)) {
1765
0
        LOG_WARNING("failed to parse txn info")
1766
0
                .tag("err", err)
1767
0
                .tag("key", hex(info_key))
1768
0
                .tag("txn_id", txn_id);
1769
0
        return -1;
1770
0
    }
1771
1772
2
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
1773
0
        LOG_INFO("txn is not prepared status, txn_id={} status={}", txn_id, txn_info.status())
1774
0
                .tag("key", hex(info_key))
1775
0
                .tag("txn_id", txn_id);
1776
0
        return 0;
1777
0
    }
1778
1779
2
    req.set_txn_id(txn_id);
1780
1781
2
    LOG(INFO) << "begin abort txn for related rowset, txn_id=" << txn_id
1782
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString();
1783
1784
2
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
1785
2
    err = txn->commit();
1786
2
    if (err != TxnErrorCode::TXN_OK) {
1787
0
        code = cast_as<ErrCategory::COMMIT>(err);
1788
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
1789
0
        msg = ss.str();
1790
0
        return -1;
1791
0
    }
1792
1793
2
    LOG(INFO) << "finish abort txn for related rowset, txn_id=" << txn_id
1794
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString()
1795
2
              << " code=" << code << " msg=" << msg;
1796
1797
2
    return 0;
1798
2
}
1799
1800
4
int InstanceRecycler::abort_job_for_related_rowset(const RowsetMetaCloudPB& rowset_meta) {
1801
4
    FinishTabletJobRequest req;
1802
4
    FinishTabletJobResponse res;
1803
4
    req.set_action(FinishTabletJobRequest::ABORT);
1804
4
    MetaServiceCode code = MetaServiceCode::OK;
1805
4
    std::string msg;
1806
4
    std::stringstream ss;
1807
1808
4
    TabletIndexPB tablet_idx;
1809
4
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, rowset_meta.tablet_id(), tablet_idx);
1810
4
    if (ret == 1) {
1811
        // tablet maybe recycled, directly return 0
1812
1
        return 0;
1813
3
    } else if (ret != 0) {
1814
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << rowset_meta.tablet_id()
1815
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
1816
0
        return ret;
1817
0
    }
1818
1819
3
    std::unique_ptr<Transaction> txn;
1820
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1821
3
    if (err != TxnErrorCode::TXN_OK) {
1822
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
1823
0
        return -1;
1824
0
    }
1825
1826
3
    std::string job_key =
1827
3
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
1828
3
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
1829
3
    std::string job_val;
1830
3
    err = txn->get(job_key, &job_val);
1831
3
    if (err != TxnErrorCode::TXN_OK) {
1832
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1833
0
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
1834
0
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
1835
0
            return 0;
1836
0
        }
1837
0
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
1838
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
1839
0
                     << " key=" << hex(job_key);
1840
0
        return -1;
1841
0
    }
1842
1843
3
    TabletJobInfoPB job_pb;
1844
3
    if (!job_pb.ParseFromString(job_val)) {
1845
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
1846
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
1847
0
        return -1;
1848
0
    }
1849
1850
3
    std::string job_id {};
1851
3
    if (!job_pb.compaction().empty()) {
1852
2
        for (const auto& c : job_pb.compaction()) {
1853
2
            if (c.id() == rowset_meta.job_id()) {
1854
2
                job_id = c.id();
1855
2
                break;
1856
2
            }
1857
2
        }
1858
2
    } else if (job_pb.has_schema_change()) {
1859
1
        job_id = job_pb.schema_change().id();
1860
1
    }
1861
1862
3
    if (!job_id.empty() && rowset_meta.job_id() == job_id) {
1863
3
        LOG(INFO) << "begin to abort job for related rowset, job_id=" << rowset_meta.job_id()
1864
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
1865
3
        req.mutable_job()->CopyFrom(job_pb);
1866
3
        req.set_action(FinishTabletJobRequest::ABORT);
1867
3
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
1868
3
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
1869
3
                           ss);
1870
3
        if (code != MetaServiceCode::OK) {
1871
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
1872
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
1873
0
                         << " msg=" << msg;
1874
0
            return -1;
1875
0
        }
1876
3
        LOG(INFO) << "finish abort job for related rowset, job_id=" << rowset_meta.job_id()
1877
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
1878
3
                  << " code=" << code << " msg=" << msg;
1879
3
    } else {
1880
        // clang-format off
1881
0
        LOG(INFO) << "there is no job for related rowset, directly recycle rowset data"
1882
0
                  << ", instance_id=" << instance_id_ 
1883
0
                  << ", tablet_id=" << tablet_idx.tablet_id() 
1884
0
                  << ", job_id=" << job_id
1885
0
                  << ", rowset_id=" << rowset_meta.rowset_id_v2();
1886
        // clang-format on
1887
0
    }
1888
1889
3
    return 0;
1890
3
}
1891
1892
template <typename T>
1893
55.6k
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
1894
55.6k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1895
51.9k
        return rowset_meta_pb.mutable_rowset_meta();
1896
51.9k
    } else {
1897
51.9k
        return &rowset_meta_pb;
1898
51.9k
    }
1899
55.6k
}
_ZN5doris5cloud19mutable_rowset_metaINS0_15RecycleRowsetPBEEEPNS_17RowsetMetaCloudPBERT_
Line
Count
Source
1893
3.75k
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
1894
3.75k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1895
3.75k
        return rowset_meta_pb.mutable_rowset_meta();
1896
3.75k
    } else {
1897
3.75k
        return &rowset_meta_pb;
1898
3.75k
    }
1899
3.75k
}
_ZN5doris5cloud19mutable_rowset_metaINS_17RowsetMetaCloudPBEEEPS2_RT_
Line
Count
Source
1893
51.9k
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
1894
51.9k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1895
51.9k
        return rowset_meta_pb.mutable_rowset_meta();
1896
51.9k
    } else {
1897
51.9k
        return &rowset_meta_pb;
1898
51.9k
    }
1899
51.9k
}
1900
1901
template <typename T>
1902
223k
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
1903
223k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1904
212k
        return rowset_meta_pb.rowset_meta();
1905
212k
    } else {
1906
212k
        return rowset_meta_pb;
1907
212k
    }
1908
223k
}
_ZN5doris5cloud11rowset_metaINS0_15RecycleRowsetPBEEERKNS_17RowsetMetaCloudPBERKT_
Line
Count
Source
1902
11.9k
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
1903
11.9k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1904
11.9k
        return rowset_meta_pb.rowset_meta();
1905
11.9k
    } else {
1906
11.9k
        return rowset_meta_pb;
1907
11.9k
    }
1908
11.9k
}
_ZN5doris5cloud11rowset_metaINS_17RowsetMetaCloudPBEEERKS2_RKT_
Line
Count
Source
1902
212k
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
1903
212k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1904
212k
        return rowset_meta_pb.rowset_meta();
1905
212k
    } else {
1906
212k
        return rowset_meta_pb;
1907
212k
    }
1908
212k
}
1909
1910
struct DeferredRecycleAbortTask {
1911
    enum class Type : uint8_t {
1912
        TXN,
1913
        JOB,
1914
    };
1915
1916
    Type type = Type::TXN;
1917
    int64_t txn_id = 0;
1918
    int64_t tablet_id = 0;
1919
    int64_t start_version = 0;
1920
    int64_t end_version = 0;
1921
    std::string rowset_id;
1922
    std::string job_id;
1923
};
1924
1925
struct DeferredRecyclePrepareDeleteTask {
1926
    std::string key;
1927
    std::string resource_id;
1928
    std::string rowset_id;
1929
    int64_t tablet_id = 0;
1930
};
1931
1932
template <typename T>
1933
57.7k
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
1934
57.7k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1935
3.75k
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
1936
3.10k
            return std::nullopt;
1937
3.10k
        }
1938
3.75k
    }
1939
1940
654
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1941
654
    DeferredRecycleAbortTask task;
1942
654
    task.tablet_id = rs_meta.tablet_id();
1943
654
    task.start_version = rs_meta.start_version();
1944
654
    task.end_version = rs_meta.end_version();
1945
54.6k
    if (rs_meta.has_load_id()) {
1946
4
        task.type = DeferredRecycleAbortTask::Type::TXN;
1947
4
        task.txn_id = rs_meta.txn_id();
1948
4
        return task;
1949
4
    }
1950
54.6k
    if (rs_meta.has_job_id()) {
1951
6
        task.type = DeferredRecycleAbortTask::Type::JOB;
1952
6
        task.rowset_id = rs_meta.rowset_id_v2();
1953
6
        task.job_id = rs_meta.job_id();
1954
6
        return task;
1955
6
    }
1956
54.6k
    return std::nullopt;
1957
54.6k
}
_ZN5doris5cloud24make_deferred_abort_taskINS0_15RecycleRowsetPBEEESt8optionalINS0_24DeferredRecycleAbortTaskEERKT_
Line
Count
Source
1933
3.75k
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
1934
3.75k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1935
3.75k
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
1936
3.10k
            return std::nullopt;
1937
3.10k
        }
1938
3.75k
    }
1939
1940
654
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1941
654
    DeferredRecycleAbortTask task;
1942
654
    task.tablet_id = rs_meta.tablet_id();
1943
654
    task.start_version = rs_meta.start_version();
1944
654
    task.end_version = rs_meta.end_version();
1945
654
    if (rs_meta.has_load_id()) {
1946
2
        task.type = DeferredRecycleAbortTask::Type::TXN;
1947
2
        task.txn_id = rs_meta.txn_id();
1948
2
        return task;
1949
2
    }
1950
652
    if (rs_meta.has_job_id()) {
1951
2
        task.type = DeferredRecycleAbortTask::Type::JOB;
1952
2
        task.rowset_id = rs_meta.rowset_id_v2();
1953
2
        task.job_id = rs_meta.job_id();
1954
2
        return task;
1955
2
    }
1956
650
    return std::nullopt;
1957
652
}
_ZN5doris5cloud24make_deferred_abort_taskINS_17RowsetMetaCloudPBEEESt8optionalINS0_24DeferredRecycleAbortTaskEERKT_
Line
Count
Source
1933
54.0k
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
1934
54.0k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1935
54.0k
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
1936
54.0k
            return std::nullopt;
1937
54.0k
        }
1938
54.0k
    }
1939
1940
54.0k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1941
54.0k
    DeferredRecycleAbortTask task;
1942
54.0k
    task.tablet_id = rs_meta.tablet_id();
1943
54.0k
    task.start_version = rs_meta.start_version();
1944
54.0k
    task.end_version = rs_meta.end_version();
1945
54.0k
    if (rs_meta.has_load_id()) {
1946
2
        task.type = DeferredRecycleAbortTask::Type::TXN;
1947
2
        task.txn_id = rs_meta.txn_id();
1948
2
        return task;
1949
2
    }
1950
54.0k
    if (rs_meta.has_job_id()) {
1951
4
        task.type = DeferredRecycleAbortTask::Type::JOB;
1952
4
        task.rowset_id = rs_meta.rowset_id_v2();
1953
4
        task.job_id = rs_meta.job_id();
1954
4
        return task;
1955
4
    }
1956
54.0k
    return std::nullopt;
1957
54.0k
}
1958
1959
template <typename T>
1960
169k
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
1961
169k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1962
169k
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
1963
169k
}
_ZN5doris5cloud28need_mark_rowset_as_recycledINS0_15RecycleRowsetPBEEEbRKT_
Line
Count
Source
1960
11.2k
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
1961
11.2k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1962
11.2k
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
1963
11.2k
}
_ZN5doris5cloud28need_mark_rowset_as_recycledINS_17RowsetMetaCloudPBEEEbRKT_
Line
Count
Source
1960
157k
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
1961
157k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1962
157k
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
1963
157k
}
1964
1965
template <typename T>
1966
int batch_mark_rowsets_as_recycled(TxnKv* txn_kv, const std::string& instance_id,
1967
42
                                   const std::vector<std::string>& keys) {
1968
42
    std::unique_ptr<Transaction> txn;
1969
42
    TxnErrorCode err = txn_kv->create_txn(&txn);
1970
42
    if (err != TxnErrorCode::TXN_OK) {
1971
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1972
0
        return -1;
1973
0
    }
1974
42
    std::vector<std::optional<std::string>> values;
1975
42
    err = txn->batch_get(&values, keys);
1976
42
    if (err != TxnErrorCode::TXN_OK) {
1977
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
1978
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
1979
0
        return -1;
1980
0
    }
1981
42
    size_t total_keys = keys.size();
1982
55.8k
    for (size_t i = 0; i < total_keys; i++) {
1983
55.7k
        if (!values[i].has_value()) {
1984
            // has already been removed by commit_rowset
1985
0
            continue;
1986
0
        }
1987
55.7k
        auto key = keys[i];
1988
55.7k
        auto val = values[i].value();
1989
55.7k
        T rowset_meta_pb;
1990
55.7k
        if (!rowset_meta_pb.ParseFromString(val)) {
1991
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
1992
0
                         << " key=" << hex(key);
1993
0
            return -1;
1994
0
        }
1995
55.7k
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
1996
0
            continue;
1997
0
        }
1998
55.7k
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
1999
55.7k
        val.clear();
2000
55.7k
        rowset_meta_pb.SerializeToString(&val);
2001
55.7k
        txn->put(key, val);
2002
55.7k
    }
2003
42
    err = txn->commit();
2004
42
    if (err != TxnErrorCode::TXN_OK) {
2005
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2006
0
        return -1;
2007
0
    }
2008
2009
42
    return 0;
2010
42
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
1967
26
                                   const std::vector<std::string>& keys) {
1968
26
    std::unique_ptr<Transaction> txn;
1969
26
    TxnErrorCode err = txn_kv->create_txn(&txn);
1970
26
    if (err != TxnErrorCode::TXN_OK) {
1971
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1972
0
        return -1;
1973
0
    }
1974
26
    std::vector<std::optional<std::string>> values;
1975
26
    err = txn->batch_get(&values, keys);
1976
26
    if (err != TxnErrorCode::TXN_OK) {
1977
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
1978
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
1979
0
        return -1;
1980
0
    }
1981
26
    size_t total_keys = keys.size();
1982
3.78k
    for (size_t i = 0; i < total_keys; i++) {
1983
3.75k
        if (!values[i].has_value()) {
1984
            // has already been removed by commit_rowset
1985
0
            continue;
1986
0
        }
1987
3.75k
        auto key = keys[i];
1988
3.75k
        auto val = values[i].value();
1989
3.75k
        T rowset_meta_pb;
1990
3.75k
        if (!rowset_meta_pb.ParseFromString(val)) {
1991
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
1992
0
                         << " key=" << hex(key);
1993
0
            return -1;
1994
0
        }
1995
3.75k
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
1996
0
            continue;
1997
0
        }
1998
3.75k
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
1999
3.75k
        val.clear();
2000
3.75k
        rowset_meta_pb.SerializeToString(&val);
2001
3.75k
        txn->put(key, val);
2002
3.75k
    }
2003
26
    err = txn->commit();
2004
26
    if (err != TxnErrorCode::TXN_OK) {
2005
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2006
0
        return -1;
2007
0
    }
2008
2009
26
    return 0;
2010
26
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
1967
16
                                   const std::vector<std::string>& keys) {
1968
16
    std::unique_ptr<Transaction> txn;
1969
16
    TxnErrorCode err = txn_kv->create_txn(&txn);
1970
16
    if (err != TxnErrorCode::TXN_OK) {
1971
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1972
0
        return -1;
1973
0
    }
1974
16
    std::vector<std::optional<std::string>> values;
1975
16
    err = txn->batch_get(&values, keys);
1976
16
    if (err != TxnErrorCode::TXN_OK) {
1977
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
1978
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
1979
0
        return -1;
1980
0
    }
1981
16
    size_t total_keys = keys.size();
1982
52.0k
    for (size_t i = 0; i < total_keys; i++) {
1983
52.0k
        if (!values[i].has_value()) {
1984
            // has already been removed by commit_rowset
1985
0
            continue;
1986
0
        }
1987
52.0k
        auto key = keys[i];
1988
52.0k
        auto val = values[i].value();
1989
52.0k
        T rowset_meta_pb;
1990
52.0k
        if (!rowset_meta_pb.ParseFromString(val)) {
1991
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
1992
0
                         << " key=" << hex(key);
1993
0
            return -1;
1994
0
        }
1995
52.0k
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
1996
0
            continue;
1997
0
        }
1998
52.0k
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
1999
52.0k
        val.clear();
2000
52.0k
        rowset_meta_pb.SerializeToString(&val);
2001
52.0k
        txn->put(key, val);
2002
52.0k
    }
2003
16
    err = txn->commit();
2004
16
    if (err != TxnErrorCode::TXN_OK) {
2005
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2006
0
        return -1;
2007
0
    }
2008
2009
16
    return 0;
2010
16
}
2011
2012
template <typename T>
2013
int collect_deferred_abort_tasks(TxnKv* txn_kv, const std::string& instance_id,
2014
                                 const std::vector<std::string>& keys,
2015
                                 std::vector<DeferredRecycleAbortTask>* abort_tasks,
2016
5
                                 bool skip_base_version) {
2017
5
    constexpr size_t kAbortCheckBatchSize = 256;
2018
10
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2019
5
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2020
5
        std::unique_ptr<Transaction> txn;
2021
5
        TxnErrorCode err = txn_kv->create_txn(&txn);
2022
5
        if (err != TxnErrorCode::TXN_OK) {
2023
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2024
0
            return -1;
2025
0
        }
2026
10
        for (size_t idx = offset; idx < limit; ++idx) {
2027
5
            const std::string& key = keys[idx];
2028
5
            std::string val;
2029
5
            err = txn->get(key, &val);
2030
5
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2031
                // has already been removed
2032
0
                continue;
2033
0
            }
2034
5
            if (err != TxnErrorCode::TXN_OK) {
2035
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2036
0
                             << " key=" << hex(key);
2037
0
                return -1;
2038
0
            }
2039
5
            T rowset_meta_pb;
2040
5
            if (!rowset_meta_pb.ParseFromString(val)) {
2041
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2042
0
                             << " key=" << hex(key);
2043
0
                return -1;
2044
0
            }
2045
5
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2046
0
                continue;
2047
0
            }
2048
5
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2049
5
                abort_task.has_value()) {
2050
5
                abort_tasks->emplace_back(std::move(*abort_task));
2051
5
            }
2052
5
        }
2053
5
    }
2054
5
    return 0;
2055
5
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24DeferredRecycleAbortTaskESaISI_EEb
Line
Count
Source
2016
2
                                 bool skip_base_version) {
2017
2
    constexpr size_t kAbortCheckBatchSize = 256;
2018
4
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2019
2
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2020
2
        std::unique_ptr<Transaction> txn;
2021
2
        TxnErrorCode err = txn_kv->create_txn(&txn);
2022
2
        if (err != TxnErrorCode::TXN_OK) {
2023
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2024
0
            return -1;
2025
0
        }
2026
4
        for (size_t idx = offset; idx < limit; ++idx) {
2027
2
            const std::string& key = keys[idx];
2028
2
            std::string val;
2029
2
            err = txn->get(key, &val);
2030
2
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2031
                // has already been removed
2032
0
                continue;
2033
0
            }
2034
2
            if (err != TxnErrorCode::TXN_OK) {
2035
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2036
0
                             << " key=" << hex(key);
2037
0
                return -1;
2038
0
            }
2039
2
            T rowset_meta_pb;
2040
2
            if (!rowset_meta_pb.ParseFromString(val)) {
2041
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2042
0
                             << " key=" << hex(key);
2043
0
                return -1;
2044
0
            }
2045
2
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2046
0
                continue;
2047
0
            }
2048
2
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2049
2
                abort_task.has_value()) {
2050
2
                abort_tasks->emplace_back(std::move(*abort_task));
2051
2
            }
2052
2
        }
2053
2
    }
2054
2
    return 0;
2055
2
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24DeferredRecycleAbortTaskESaISI_EEb
Line
Count
Source
2016
3
                                 bool skip_base_version) {
2017
3
    constexpr size_t kAbortCheckBatchSize = 256;
2018
6
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2019
3
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2020
3
        std::unique_ptr<Transaction> txn;
2021
3
        TxnErrorCode err = txn_kv->create_txn(&txn);
2022
3
        if (err != TxnErrorCode::TXN_OK) {
2023
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2024
0
            return -1;
2025
0
        }
2026
6
        for (size_t idx = offset; idx < limit; ++idx) {
2027
3
            const std::string& key = keys[idx];
2028
3
            std::string val;
2029
3
            err = txn->get(key, &val);
2030
3
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2031
                // has already been removed
2032
0
                continue;
2033
0
            }
2034
3
            if (err != TxnErrorCode::TXN_OK) {
2035
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2036
0
                             << " key=" << hex(key);
2037
0
                return -1;
2038
0
            }
2039
3
            T rowset_meta_pb;
2040
3
            if (!rowset_meta_pb.ParseFromString(val)) {
2041
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2042
0
                             << " key=" << hex(key);
2043
0
                return -1;
2044
0
            }
2045
3
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2046
0
                continue;
2047
0
            }
2048
3
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2049
3
                abort_task.has_value()) {
2050
3
                abort_tasks->emplace_back(std::move(*abort_task));
2051
3
            }
2052
3
        }
2053
3
    }
2054
3
    return 0;
2055
3
}
2056
2057
template <typename T>
2058
int InstanceRecycler::batch_abort_txn_or_job_for_recycle(const std::vector<std::string>& keys,
2059
5
                                                         bool skip_base_version) {
2060
5
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2061
5
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2062
5
                                        skip_base_version) != 0) {
2063
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2064
0
        return -1;
2065
0
    }
2066
5
    for (const auto& abort_task : abort_tasks) {
2067
5
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2068
5
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2069
5
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2070
5
        int abort_ret = 0;
2071
5
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2072
2
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2073
3
        } else {
2074
3
            RowsetMetaCloudPB rowset_meta;
2075
3
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2076
3
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2077
3
            rowset_meta.set_job_id(abort_task.job_id);
2078
3
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2079
3
        }
2080
5
        if (abort_ret != 0) {
2081
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2082
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2083
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2084
0
            return abort_ret;
2085
0
        }
2086
5
    }
2087
5
    return 0;
2088
5
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEb
Line
Count
Source
2059
2
                                                         bool skip_base_version) {
2060
2
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2061
2
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2062
2
                                        skip_base_version) != 0) {
2063
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2064
0
        return -1;
2065
0
    }
2066
2
    for (const auto& abort_task : abort_tasks) {
2067
2
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2068
2
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2069
2
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2070
2
        int abort_ret = 0;
2071
2
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2072
1
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2073
1
        } else {
2074
1
            RowsetMetaCloudPB rowset_meta;
2075
1
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2076
1
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2077
1
            rowset_meta.set_job_id(abort_task.job_id);
2078
1
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2079
1
        }
2080
2
        if (abort_ret != 0) {
2081
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2082
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2083
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2084
0
            return abort_ret;
2085
0
        }
2086
2
    }
2087
2
    return 0;
2088
2
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEb
Line
Count
Source
2059
3
                                                         bool skip_base_version) {
2060
3
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2061
3
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2062
3
                                        skip_base_version) != 0) {
2063
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2064
0
        return -1;
2065
0
    }
2066
3
    for (const auto& abort_task : abort_tasks) {
2067
3
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2068
3
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2069
3
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2070
3
        int abort_ret = 0;
2071
3
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2072
1
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2073
2
        } else {
2074
2
            RowsetMetaCloudPB rowset_meta;
2075
2
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2076
2
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2077
2
            rowset_meta.set_job_id(abort_task.job_id);
2078
2
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2079
2
        }
2080
3
        if (abort_ret != 0) {
2081
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2082
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2083
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2084
0
            return abort_ret;
2085
0
        }
2086
3
    }
2087
3
    return 0;
2088
3
}
2089
2090
int collect_prepare_delete_tasks(TxnKv* txn_kv, const std::string& instance_id,
2091
                                 const std::vector<std::string>& keys,
2092
23
                                 std::vector<DeferredRecyclePrepareDeleteTask>* delete_tasks) {
2093
23
    constexpr size_t kPrepareCheckBatchSize = 256;
2094
46
    for (size_t offset = 0; offset < keys.size(); offset += kPrepareCheckBatchSize) {
2095
23
        size_t limit = std::min(keys.size(), offset + kPrepareCheckBatchSize);
2096
23
        std::unique_ptr<Transaction> txn;
2097
23
        TxnErrorCode err = txn_kv->create_txn(&txn);
2098
23
        if (err != TxnErrorCode::TXN_OK) {
2099
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2100
0
            return -1;
2101
0
        }
2102
675
        for (size_t idx = offset; idx < limit; ++idx) {
2103
652
            const std::string& key = keys[idx];
2104
652
            std::string val;
2105
652
            err = txn->get(key, &val);
2106
652
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2107
                // has already been removed
2108
0
                continue;
2109
0
            }
2110
652
            if (err != TxnErrorCode::TXN_OK) {
2111
0
                LOG(WARNING) << "failed to get recycle rowset, instance_id=" << instance_id
2112
0
                             << " key=" << hex(key);
2113
0
                return -1;
2114
0
            }
2115
652
            RecycleRowsetPB rowset;
2116
652
            if (!rowset.ParseFromString(val)) {
2117
0
                LOG(WARNING) << "failed to parse recycle rowset, instance_id=" << instance_id
2118
0
                             << " key=" << hex(key);
2119
0
                return -1;
2120
0
            }
2121
652
            if (rowset.type() != RecycleRowsetPB::PREPARE) {
2122
0
                continue;
2123
0
            }
2124
652
            const auto& rs_meta = rowset.rowset_meta();
2125
652
            delete_tasks->push_back(
2126
652
                    {key, rs_meta.resource_id(), rs_meta.rowset_id_v2(), rs_meta.tablet_id()});
2127
652
        }
2128
23
    }
2129
23
    return 0;
2130
23
}
2131
2132
1
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
2133
1
    const std::string task_name = "recycle_ref_rowsets";
2134
1
    *has_unrecycled_rowsets = false;
2135
2136
1
    std::string data_rowset_ref_count_key_start =
2137
1
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
2138
1
    std::string data_rowset_ref_count_key_end =
2139
1
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
2140
2141
1
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
2142
2143
1
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2144
1
    register_recycle_task(task_name, start_time);
2145
2146
1
    DORIS_CLOUD_DEFER {
2147
1
        unregister_recycle_task(task_name);
2148
1
        int64_t cost =
2149
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2150
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2151
1
                .tag("instance_id", instance_id_);
2152
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Line
Count
Source
2146
1
    DORIS_CLOUD_DEFER {
2147
1
        unregister_recycle_task(task_name);
2148
1
        int64_t cost =
2149
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2150
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2151
1
                .tag("instance_id", instance_id_);
2152
1
    };
2153
2154
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
2155
1
    std::set<int64_t> tablets_with_refs;
2156
1
    int64_t num_scanned = 0;
2157
2158
1
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
2159
0
        ++num_scanned;
2160
0
        int64_t tablet_id;
2161
0
        std::string rowset_id;
2162
0
        std::string_view key(k);
2163
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
2164
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
2165
0
            return 0; // Continue scanning
2166
0
        }
2167
2168
0
        tablets_with_refs.insert(tablet_id);
2169
0
        return 0;
2170
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
2171
2172
1
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
2173
1
                         std::move(scan_func)) != 0) {
2174
0
        LOG_WARNING("failed to scan data rowset ref count keys");
2175
0
        return -1;
2176
0
    }
2177
2178
1
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
2179
1
             tablets_with_refs.size(), num_scanned)
2180
1
            .tag("instance_id", instance_id_);
2181
2182
    // Phase 2: Recycle each tablet
2183
1
    int64_t num_recycled_tablets = 0;
2184
1
    for (int64_t tablet_id : tablets_with_refs) {
2185
0
        if (stopped()) {
2186
0
            LOG_INFO("recycler stopped, skip remaining tablets")
2187
0
                    .tag("instance_id", instance_id_)
2188
0
                    .tag("tablets_processed", num_recycled_tablets)
2189
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
2190
0
            break;
2191
0
        }
2192
2193
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
2194
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
2195
0
            LOG_WARNING("failed to recycle tablet")
2196
0
                    .tag("instance_id", instance_id_)
2197
0
                    .tag("tablet_id", tablet_id);
2198
0
            return -1;
2199
0
        }
2200
0
        ++num_recycled_tablets;
2201
0
    }
2202
2203
1
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
2204
1
            .tag("instance_id", instance_id_)
2205
1
            .tag("total_tablets", tablets_with_refs.size());
2206
2207
    // Phase 3: Scan again to check if any ref count keys still exist
2208
1
    std::unique_ptr<Transaction> txn;
2209
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2210
1
    if (err != TxnErrorCode::TXN_OK) {
2211
0
        LOG_WARNING("failed to create txn for final check")
2212
0
                .tag("instance_id", instance_id_)
2213
0
                .tag("err", err);
2214
0
        return -1;
2215
0
    }
2216
2217
1
    std::unique_ptr<RangeGetIterator> iter;
2218
1
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2219
1
    if (err != TxnErrorCode::TXN_OK) {
2220
0
        LOG_WARNING("failed to create range iterator for final check")
2221
0
                .tag("instance_id", instance_id_)
2222
0
                .tag("err", err);
2223
0
        return -1;
2224
0
    }
2225
2226
1
    *has_unrecycled_rowsets = iter->has_next();
2227
1
    if (*has_unrecycled_rowsets) {
2228
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2229
0
                .tag("instance_id", instance_id_);
2230
0
    }
2231
2232
1
    return 0;
2233
1
}
2234
2235
17
int InstanceRecycler::recycle_indexes() {
2236
17
    const std::string task_name = "recycle_indexes";
2237
17
    int64_t num_scanned = 0;
2238
17
    int64_t num_expired = 0;
2239
17
    int64_t num_recycled = 0;
2240
17
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2241
2242
17
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2243
17
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2244
17
    std::string index_key0;
2245
17
    std::string index_key1;
2246
17
    recycle_index_key(index_key_info0, &index_key0);
2247
17
    recycle_index_key(index_key_info1, &index_key1);
2248
2249
17
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2250
2251
17
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2252
17
    register_recycle_task(task_name, start_time);
2253
2254
17
    DORIS_CLOUD_DEFER {
2255
17
        unregister_recycle_task(task_name);
2256
17
        int64_t cost =
2257
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2258
17
        metrics_context.finish_report();
2259
17
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2260
17
                .tag("instance_id", instance_id_)
2261
17
                .tag("num_scanned", num_scanned)
2262
17
                .tag("num_expired", num_expired)
2263
17
                .tag("num_recycled", num_recycled);
2264
17
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2254
2
    DORIS_CLOUD_DEFER {
2255
2
        unregister_recycle_task(task_name);
2256
2
        int64_t cost =
2257
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2258
2
        metrics_context.finish_report();
2259
2
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2260
2
                .tag("instance_id", instance_id_)
2261
2
                .tag("num_scanned", num_scanned)
2262
2
                .tag("num_expired", num_expired)
2263
2
                .tag("num_recycled", num_recycled);
2264
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2254
15
    DORIS_CLOUD_DEFER {
2255
15
        unregister_recycle_task(task_name);
2256
15
        int64_t cost =
2257
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2258
15
        metrics_context.finish_report();
2259
15
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2260
15
                .tag("instance_id", instance_id_)
2261
15
                .tag("num_scanned", num_scanned)
2262
15
                .tag("num_expired", num_expired)
2263
15
                .tag("num_recycled", num_recycled);
2264
15
    };
2265
2266
17
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2267
2268
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2269
17
    std::vector<std::string_view> index_keys;
2270
17
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2271
10
        ++num_scanned;
2272
10
        RecycleIndexPB index_pb;
2273
10
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2274
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2275
0
            return -1;
2276
0
        }
2277
10
        int64_t current_time = ::time(nullptr);
2278
10
        if (current_time <
2279
10
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2280
0
            return 0;
2281
0
        }
2282
10
        ++num_expired;
2283
        // decode index_id
2284
10
        auto k1 = k;
2285
10
        k1.remove_prefix(1);
2286
10
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2287
10
        decode_key(&k1, &out);
2288
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2289
10
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2290
10
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2291
10
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2292
10
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2293
        // Change state to RECYCLING
2294
10
        std::unique_ptr<Transaction> txn;
2295
10
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2296
10
        if (err != TxnErrorCode::TXN_OK) {
2297
0
            LOG_WARNING("failed to create txn").tag("err", err);
2298
0
            return -1;
2299
0
        }
2300
10
        std::string val;
2301
10
        err = txn->get(k, &val);
2302
10
        if (err ==
2303
10
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2304
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2305
0
            return 0;
2306
0
        }
2307
10
        if (err != TxnErrorCode::TXN_OK) {
2308
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2309
0
            return -1;
2310
0
        }
2311
10
        index_pb.Clear();
2312
10
        if (!index_pb.ParseFromString(val)) {
2313
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2314
0
            return -1;
2315
0
        }
2316
10
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2317
9
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2318
9
            txn->put(k, index_pb.SerializeAsString());
2319
9
            err = txn->commit();
2320
9
            if (err != TxnErrorCode::TXN_OK) {
2321
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2322
0
                return -1;
2323
0
            }
2324
9
        }
2325
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2326
1
            LOG_WARNING("failed to recycle tablets under index")
2327
1
                    .tag("table_id", index_pb.table_id())
2328
1
                    .tag("instance_id", instance_id_)
2329
1
                    .tag("index_id", index_id);
2330
1
            return -1;
2331
1
        }
2332
2333
9
        if (index_pb.has_db_id()) {
2334
            // Recycle the versioned keys
2335
3
            std::unique_ptr<Transaction> txn;
2336
3
            err = txn_kv_->create_txn(&txn);
2337
3
            if (err != TxnErrorCode::TXN_OK) {
2338
0
                LOG_WARNING("failed to create txn").tag("err", err);
2339
0
                return -1;
2340
0
            }
2341
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2342
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2343
3
            std::string index_inverted_key = versioned::index_inverted_key(
2344
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2345
3
            versioned_remove_all(txn.get(), meta_key);
2346
3
            txn->remove(index_key);
2347
3
            txn->remove(index_inverted_key);
2348
3
            err = txn->commit();
2349
3
            if (err != TxnErrorCode::TXN_OK) {
2350
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2351
0
                return -1;
2352
0
            }
2353
3
        }
2354
2355
9
        metrics_context.total_recycled_num = ++num_recycled;
2356
9
        metrics_context.report();
2357
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2358
9
        index_keys.push_back(k);
2359
9
        return 0;
2360
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2270
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2271
2
        ++num_scanned;
2272
2
        RecycleIndexPB index_pb;
2273
2
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2274
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2275
0
            return -1;
2276
0
        }
2277
2
        int64_t current_time = ::time(nullptr);
2278
2
        if (current_time <
2279
2
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2280
0
            return 0;
2281
0
        }
2282
2
        ++num_expired;
2283
        // decode index_id
2284
2
        auto k1 = k;
2285
2
        k1.remove_prefix(1);
2286
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2287
2
        decode_key(&k1, &out);
2288
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2289
2
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2290
2
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2291
2
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2292
2
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2293
        // Change state to RECYCLING
2294
2
        std::unique_ptr<Transaction> txn;
2295
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2296
2
        if (err != TxnErrorCode::TXN_OK) {
2297
0
            LOG_WARNING("failed to create txn").tag("err", err);
2298
0
            return -1;
2299
0
        }
2300
2
        std::string val;
2301
2
        err = txn->get(k, &val);
2302
2
        if (err ==
2303
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2304
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2305
0
            return 0;
2306
0
        }
2307
2
        if (err != TxnErrorCode::TXN_OK) {
2308
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2309
0
            return -1;
2310
0
        }
2311
2
        index_pb.Clear();
2312
2
        if (!index_pb.ParseFromString(val)) {
2313
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2314
0
            return -1;
2315
0
        }
2316
2
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2317
1
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2318
1
            txn->put(k, index_pb.SerializeAsString());
2319
1
            err = txn->commit();
2320
1
            if (err != TxnErrorCode::TXN_OK) {
2321
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2322
0
                return -1;
2323
0
            }
2324
1
        }
2325
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2326
1
            LOG_WARNING("failed to recycle tablets under index")
2327
1
                    .tag("table_id", index_pb.table_id())
2328
1
                    .tag("instance_id", instance_id_)
2329
1
                    .tag("index_id", index_id);
2330
1
            return -1;
2331
1
        }
2332
2333
1
        if (index_pb.has_db_id()) {
2334
            // Recycle the versioned keys
2335
1
            std::unique_ptr<Transaction> txn;
2336
1
            err = txn_kv_->create_txn(&txn);
2337
1
            if (err != TxnErrorCode::TXN_OK) {
2338
0
                LOG_WARNING("failed to create txn").tag("err", err);
2339
0
                return -1;
2340
0
            }
2341
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2342
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2343
1
            std::string index_inverted_key = versioned::index_inverted_key(
2344
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2345
1
            versioned_remove_all(txn.get(), meta_key);
2346
1
            txn->remove(index_key);
2347
1
            txn->remove(index_inverted_key);
2348
1
            err = txn->commit();
2349
1
            if (err != TxnErrorCode::TXN_OK) {
2350
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2351
0
                return -1;
2352
0
            }
2353
1
        }
2354
2355
1
        metrics_context.total_recycled_num = ++num_recycled;
2356
1
        metrics_context.report();
2357
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2358
1
        index_keys.push_back(k);
2359
1
        return 0;
2360
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2270
8
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2271
8
        ++num_scanned;
2272
8
        RecycleIndexPB index_pb;
2273
8
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2274
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2275
0
            return -1;
2276
0
        }
2277
8
        int64_t current_time = ::time(nullptr);
2278
8
        if (current_time <
2279
8
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2280
0
            return 0;
2281
0
        }
2282
8
        ++num_expired;
2283
        // decode index_id
2284
8
        auto k1 = k;
2285
8
        k1.remove_prefix(1);
2286
8
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2287
8
        decode_key(&k1, &out);
2288
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2289
8
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2290
8
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2291
8
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2292
8
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2293
        // Change state to RECYCLING
2294
8
        std::unique_ptr<Transaction> txn;
2295
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2296
8
        if (err != TxnErrorCode::TXN_OK) {
2297
0
            LOG_WARNING("failed to create txn").tag("err", err);
2298
0
            return -1;
2299
0
        }
2300
8
        std::string val;
2301
8
        err = txn->get(k, &val);
2302
8
        if (err ==
2303
8
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2304
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2305
0
            return 0;
2306
0
        }
2307
8
        if (err != TxnErrorCode::TXN_OK) {
2308
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2309
0
            return -1;
2310
0
        }
2311
8
        index_pb.Clear();
2312
8
        if (!index_pb.ParseFromString(val)) {
2313
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2314
0
            return -1;
2315
0
        }
2316
8
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2317
8
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2318
8
            txn->put(k, index_pb.SerializeAsString());
2319
8
            err = txn->commit();
2320
8
            if (err != TxnErrorCode::TXN_OK) {
2321
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2322
0
                return -1;
2323
0
            }
2324
8
        }
2325
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2326
0
            LOG_WARNING("failed to recycle tablets under index")
2327
0
                    .tag("table_id", index_pb.table_id())
2328
0
                    .tag("instance_id", instance_id_)
2329
0
                    .tag("index_id", index_id);
2330
0
            return -1;
2331
0
        }
2332
2333
8
        if (index_pb.has_db_id()) {
2334
            // Recycle the versioned keys
2335
2
            std::unique_ptr<Transaction> txn;
2336
2
            err = txn_kv_->create_txn(&txn);
2337
2
            if (err != TxnErrorCode::TXN_OK) {
2338
0
                LOG_WARNING("failed to create txn").tag("err", err);
2339
0
                return -1;
2340
0
            }
2341
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2342
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2343
2
            std::string index_inverted_key = versioned::index_inverted_key(
2344
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2345
2
            versioned_remove_all(txn.get(), meta_key);
2346
2
            txn->remove(index_key);
2347
2
            txn->remove(index_inverted_key);
2348
2
            err = txn->commit();
2349
2
            if (err != TxnErrorCode::TXN_OK) {
2350
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2351
0
                return -1;
2352
0
            }
2353
2
        }
2354
2355
8
        metrics_context.total_recycled_num = ++num_recycled;
2356
8
        metrics_context.report();
2357
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2358
8
        index_keys.push_back(k);
2359
8
        return 0;
2360
8
    };
2361
2362
17
    auto loop_done = [&index_keys, this]() -> int {
2363
6
        if (index_keys.empty()) return 0;
2364
5
        DORIS_CLOUD_DEFER {
2365
5
            index_keys.clear();
2366
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2364
1
        DORIS_CLOUD_DEFER {
2365
1
            index_keys.clear();
2366
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2364
4
        DORIS_CLOUD_DEFER {
2365
4
            index_keys.clear();
2366
4
        };
2367
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2368
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2369
0
            return -1;
2370
0
        }
2371
5
        return 0;
2372
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2362
2
    auto loop_done = [&index_keys, this]() -> int {
2363
2
        if (index_keys.empty()) return 0;
2364
1
        DORIS_CLOUD_DEFER {
2365
1
            index_keys.clear();
2366
1
        };
2367
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2368
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2369
0
            return -1;
2370
0
        }
2371
1
        return 0;
2372
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2362
4
    auto loop_done = [&index_keys, this]() -> int {
2363
4
        if (index_keys.empty()) return 0;
2364
4
        DORIS_CLOUD_DEFER {
2365
4
            index_keys.clear();
2366
4
        };
2367
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2368
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2369
0
            return -1;
2370
0
        }
2371
4
        return 0;
2372
4
    };
2373
2374
17
    if (config::enable_recycler_stats_metrics) {
2375
0
        scan_and_statistics_indexes();
2376
0
    }
2377
    // recycle_func and loop_done for scan and recycle
2378
17
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
2379
17
}
2380
2381
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
2382
8.25k
                             int64_t tablet_id) {
2383
8.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
2384
2385
8.25k
    std::unique_ptr<Transaction> txn;
2386
8.25k
    TxnErrorCode err = txn_kv->create_txn(&txn);
2387
8.25k
    if (err != TxnErrorCode::TXN_OK) {
2388
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
2389
0
                     << " tablet_id=" << tablet_id << " err=" << err;
2390
0
        return false;
2391
0
    }
2392
2393
8.25k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
2394
8.25k
    std::string tablet_idx_val;
2395
8.25k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
2396
8.25k
    if (TxnErrorCode::TXN_OK != err) {
2397
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
2398
0
                     << " tablet_id=" << tablet_id << " err=" << err
2399
0
                     << " key=" << hex(tablet_idx_key);
2400
0
        return false;
2401
0
    }
2402
2403
8.25k
    TabletIndexPB tablet_idx_pb;
2404
8.25k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
2405
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
2406
0
                     << " tablet_id=" << tablet_id;
2407
0
        return false;
2408
0
    }
2409
2410
8.25k
    if (!tablet_idx_pb.has_db_id()) {
2411
        // In the previous version, the db_id was not set in the index_pb.
2412
        // If updating to the version which enable txn lazy commit, the db_id will be set.
2413
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
2414
0
                  << " instance_id=" << instance_id
2415
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
2416
0
        return true;
2417
0
    }
2418
2419
8.25k
    std::string ver_val;
2420
8.25k
    std::string ver_key =
2421
8.25k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
2422
8.25k
                                   tablet_idx_pb.partition_id()});
2423
8.25k
    err = txn->get(ver_key, &ver_val);
2424
2425
8.25k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
2426
214
        LOG(INFO) << ""
2427
214
                     "partition version not found, instance_id="
2428
214
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
2429
214
                  << " table_id=" << tablet_idx_pb.table_id()
2430
214
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
2431
214
                  << " key=" << hex(ver_key);
2432
214
        return true;
2433
214
    }
2434
2435
8.03k
    if (TxnErrorCode::TXN_OK != err) {
2436
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
2437
0
                     << " db_id=" << tablet_idx_pb.db_id()
2438
0
                     << " table_id=" << tablet_idx_pb.table_id()
2439
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2440
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
2441
0
        return false;
2442
0
    }
2443
2444
8.03k
    VersionPB version_pb;
2445
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
2446
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
2447
0
                     << " db_id=" << tablet_idx_pb.db_id()
2448
0
                     << " table_id=" << tablet_idx_pb.table_id()
2449
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2450
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
2451
0
        return false;
2452
0
    }
2453
2454
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
2455
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
2456
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
2457
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
2458
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
2459
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
2460
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
2461
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
2462
4.00k
                     << " key=" << hex(ver_key);
2463
4.00k
        return false;
2464
4.00k
    }
2465
4.03k
    return true;
2466
8.03k
}
2467
2468
15
int InstanceRecycler::recycle_partitions() {
2469
15
    const std::string task_name = "recycle_partitions";
2470
15
    int64_t num_scanned = 0;
2471
15
    int64_t num_expired = 0;
2472
15
    int64_t num_recycled = 0;
2473
15
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2474
2475
15
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
2476
15
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
2477
15
    std::string part_key0;
2478
15
    std::string part_key1;
2479
15
    recycle_partition_key(part_key_info0, &part_key0);
2480
15
    recycle_partition_key(part_key_info1, &part_key1);
2481
2482
15
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
2483
2484
15
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2485
15
    register_recycle_task(task_name, start_time);
2486
2487
15
    DORIS_CLOUD_DEFER {
2488
15
        unregister_recycle_task(task_name);
2489
15
        int64_t cost =
2490
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2491
15
        metrics_context.finish_report();
2492
15
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2493
15
                .tag("instance_id", instance_id_)
2494
15
                .tag("num_scanned", num_scanned)
2495
15
                .tag("num_expired", num_expired)
2496
15
                .tag("num_recycled", num_recycled);
2497
15
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2487
2
    DORIS_CLOUD_DEFER {
2488
2
        unregister_recycle_task(task_name);
2489
2
        int64_t cost =
2490
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2491
2
        metrics_context.finish_report();
2492
2
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2493
2
                .tag("instance_id", instance_id_)
2494
2
                .tag("num_scanned", num_scanned)
2495
2
                .tag("num_expired", num_expired)
2496
2
                .tag("num_recycled", num_recycled);
2497
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2487
13
    DORIS_CLOUD_DEFER {
2488
13
        unregister_recycle_task(task_name);
2489
13
        int64_t cost =
2490
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2491
13
        metrics_context.finish_report();
2492
13
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2493
13
                .tag("instance_id", instance_id_)
2494
13
                .tag("num_scanned", num_scanned)
2495
13
                .tag("num_expired", num_expired)
2496
13
                .tag("num_recycled", num_recycled);
2497
13
    };
2498
2499
15
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2500
2501
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
2502
15
    std::vector<std::string_view> partition_keys;
2503
15
    std::vector<std::string> partition_version_keys;
2504
15
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2505
9
        ++num_scanned;
2506
9
        RecyclePartitionPB part_pb;
2507
9
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2508
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2509
0
            return -1;
2510
0
        }
2511
9
        int64_t current_time = ::time(nullptr);
2512
9
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2513
9
                                                            &earlest_ts)) { // not expired
2514
0
            return 0;
2515
0
        }
2516
9
        ++num_expired;
2517
        // decode partition_id
2518
9
        auto k1 = k;
2519
9
        k1.remove_prefix(1);
2520
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2521
9
        decode_key(&k1, &out);
2522
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2523
9
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2524
9
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2525
9
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2526
9
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2527
        // Change state to RECYCLING
2528
9
        std::unique_ptr<Transaction> txn;
2529
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2530
9
        if (err != TxnErrorCode::TXN_OK) {
2531
0
            LOG_WARNING("failed to create txn").tag("err", err);
2532
0
            return -1;
2533
0
        }
2534
9
        std::string val;
2535
9
        err = txn->get(k, &val);
2536
9
        if (err ==
2537
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2538
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2539
0
            return 0;
2540
0
        }
2541
9
        if (err != TxnErrorCode::TXN_OK) {
2542
0
            LOG_WARNING("failed to get kv");
2543
0
            return -1;
2544
0
        }
2545
9
        part_pb.Clear();
2546
9
        if (!part_pb.ParseFromString(val)) {
2547
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2548
0
            return -1;
2549
0
        }
2550
        // Partitions with PREPARED state MUST have no data
2551
9
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2552
8
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2553
8
            txn->put(k, part_pb.SerializeAsString());
2554
8
            err = txn->commit();
2555
8
            if (err != TxnErrorCode::TXN_OK) {
2556
0
                LOG_WARNING("failed to commit txn: {}", err);
2557
0
                return -1;
2558
0
            }
2559
8
        }
2560
2561
9
        int ret = 0;
2562
33
        for (int64_t index_id : part_pb.index_id()) {
2563
33
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2564
1
                LOG_WARNING("failed to recycle tablets under partition")
2565
1
                        .tag("table_id", part_pb.table_id())
2566
1
                        .tag("instance_id", instance_id_)
2567
1
                        .tag("index_id", index_id)
2568
1
                        .tag("partition_id", partition_id);
2569
1
                ret = -1;
2570
1
            }
2571
33
        }
2572
9
        if (ret == 0 && part_pb.has_db_id()) {
2573
            // Recycle the versioned keys
2574
8
            std::unique_ptr<Transaction> txn;
2575
8
            err = txn_kv_->create_txn(&txn);
2576
8
            if (err != TxnErrorCode::TXN_OK) {
2577
0
                LOG_WARNING("failed to create txn").tag("err", err);
2578
0
                return -1;
2579
0
            }
2580
8
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2581
8
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2582
8
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2583
8
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2584
8
            std::string partition_version_key =
2585
8
                    versioned::partition_version_key({instance_id_, partition_id});
2586
8
            versioned_remove_all(txn.get(), meta_key);
2587
8
            txn->remove(index_key);
2588
8
            txn->remove(inverted_index_key);
2589
8
            versioned_remove_all(txn.get(), partition_version_key);
2590
8
            err = txn->commit();
2591
8
            if (err != TxnErrorCode::TXN_OK) {
2592
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2593
0
                return -1;
2594
0
            }
2595
8
        }
2596
2597
9
        if (ret == 0) {
2598
8
            ++num_recycled;
2599
8
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2600
8
            partition_keys.push_back(k);
2601
8
            if (part_pb.db_id() > 0) {
2602
8
                partition_version_keys.push_back(partition_version_key(
2603
8
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2604
8
            }
2605
8
            metrics_context.total_recycled_num = num_recycled;
2606
8
            metrics_context.report();
2607
8
        }
2608
9
        return ret;
2609
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2504
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2505
2
        ++num_scanned;
2506
2
        RecyclePartitionPB part_pb;
2507
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2508
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2509
0
            return -1;
2510
0
        }
2511
2
        int64_t current_time = ::time(nullptr);
2512
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2513
2
                                                            &earlest_ts)) { // not expired
2514
0
            return 0;
2515
0
        }
2516
2
        ++num_expired;
2517
        // decode partition_id
2518
2
        auto k1 = k;
2519
2
        k1.remove_prefix(1);
2520
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2521
2
        decode_key(&k1, &out);
2522
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2523
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2524
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2525
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2526
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2527
        // Change state to RECYCLING
2528
2
        std::unique_ptr<Transaction> txn;
2529
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2530
2
        if (err != TxnErrorCode::TXN_OK) {
2531
0
            LOG_WARNING("failed to create txn").tag("err", err);
2532
0
            return -1;
2533
0
        }
2534
2
        std::string val;
2535
2
        err = txn->get(k, &val);
2536
2
        if (err ==
2537
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2538
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2539
0
            return 0;
2540
0
        }
2541
2
        if (err != TxnErrorCode::TXN_OK) {
2542
0
            LOG_WARNING("failed to get kv");
2543
0
            return -1;
2544
0
        }
2545
2
        part_pb.Clear();
2546
2
        if (!part_pb.ParseFromString(val)) {
2547
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2548
0
            return -1;
2549
0
        }
2550
        // Partitions with PREPARED state MUST have no data
2551
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2552
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2553
1
            txn->put(k, part_pb.SerializeAsString());
2554
1
            err = txn->commit();
2555
1
            if (err != TxnErrorCode::TXN_OK) {
2556
0
                LOG_WARNING("failed to commit txn: {}", err);
2557
0
                return -1;
2558
0
            }
2559
1
        }
2560
2561
2
        int ret = 0;
2562
2
        for (int64_t index_id : part_pb.index_id()) {
2563
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2564
1
                LOG_WARNING("failed to recycle tablets under partition")
2565
1
                        .tag("table_id", part_pb.table_id())
2566
1
                        .tag("instance_id", instance_id_)
2567
1
                        .tag("index_id", index_id)
2568
1
                        .tag("partition_id", partition_id);
2569
1
                ret = -1;
2570
1
            }
2571
2
        }
2572
2
        if (ret == 0 && part_pb.has_db_id()) {
2573
            // Recycle the versioned keys
2574
1
            std::unique_ptr<Transaction> txn;
2575
1
            err = txn_kv_->create_txn(&txn);
2576
1
            if (err != TxnErrorCode::TXN_OK) {
2577
0
                LOG_WARNING("failed to create txn").tag("err", err);
2578
0
                return -1;
2579
0
            }
2580
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2581
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2582
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2583
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2584
1
            std::string partition_version_key =
2585
1
                    versioned::partition_version_key({instance_id_, partition_id});
2586
1
            versioned_remove_all(txn.get(), meta_key);
2587
1
            txn->remove(index_key);
2588
1
            txn->remove(inverted_index_key);
2589
1
            versioned_remove_all(txn.get(), partition_version_key);
2590
1
            err = txn->commit();
2591
1
            if (err != TxnErrorCode::TXN_OK) {
2592
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2593
0
                return -1;
2594
0
            }
2595
1
        }
2596
2597
2
        if (ret == 0) {
2598
1
            ++num_recycled;
2599
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2600
1
            partition_keys.push_back(k);
2601
1
            if (part_pb.db_id() > 0) {
2602
1
                partition_version_keys.push_back(partition_version_key(
2603
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2604
1
            }
2605
1
            metrics_context.total_recycled_num = num_recycled;
2606
1
            metrics_context.report();
2607
1
        }
2608
2
        return ret;
2609
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2504
7
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2505
7
        ++num_scanned;
2506
7
        RecyclePartitionPB part_pb;
2507
7
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2508
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2509
0
            return -1;
2510
0
        }
2511
7
        int64_t current_time = ::time(nullptr);
2512
7
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2513
7
                                                            &earlest_ts)) { // not expired
2514
0
            return 0;
2515
0
        }
2516
7
        ++num_expired;
2517
        // decode partition_id
2518
7
        auto k1 = k;
2519
7
        k1.remove_prefix(1);
2520
7
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2521
7
        decode_key(&k1, &out);
2522
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2523
7
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2524
7
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2525
7
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2526
7
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2527
        // Change state to RECYCLING
2528
7
        std::unique_ptr<Transaction> txn;
2529
7
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2530
7
        if (err != TxnErrorCode::TXN_OK) {
2531
0
            LOG_WARNING("failed to create txn").tag("err", err);
2532
0
            return -1;
2533
0
        }
2534
7
        std::string val;
2535
7
        err = txn->get(k, &val);
2536
7
        if (err ==
2537
7
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2538
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2539
0
            return 0;
2540
0
        }
2541
7
        if (err != TxnErrorCode::TXN_OK) {
2542
0
            LOG_WARNING("failed to get kv");
2543
0
            return -1;
2544
0
        }
2545
7
        part_pb.Clear();
2546
7
        if (!part_pb.ParseFromString(val)) {
2547
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2548
0
            return -1;
2549
0
        }
2550
        // Partitions with PREPARED state MUST have no data
2551
7
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2552
7
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2553
7
            txn->put(k, part_pb.SerializeAsString());
2554
7
            err = txn->commit();
2555
7
            if (err != TxnErrorCode::TXN_OK) {
2556
0
                LOG_WARNING("failed to commit txn: {}", err);
2557
0
                return -1;
2558
0
            }
2559
7
        }
2560
2561
7
        int ret = 0;
2562
31
        for (int64_t index_id : part_pb.index_id()) {
2563
31
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2564
0
                LOG_WARNING("failed to recycle tablets under partition")
2565
0
                        .tag("table_id", part_pb.table_id())
2566
0
                        .tag("instance_id", instance_id_)
2567
0
                        .tag("index_id", index_id)
2568
0
                        .tag("partition_id", partition_id);
2569
0
                ret = -1;
2570
0
            }
2571
31
        }
2572
7
        if (ret == 0 && part_pb.has_db_id()) {
2573
            // Recycle the versioned keys
2574
7
            std::unique_ptr<Transaction> txn;
2575
7
            err = txn_kv_->create_txn(&txn);
2576
7
            if (err != TxnErrorCode::TXN_OK) {
2577
0
                LOG_WARNING("failed to create txn").tag("err", err);
2578
0
                return -1;
2579
0
            }
2580
7
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2581
7
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2582
7
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2583
7
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2584
7
            std::string partition_version_key =
2585
7
                    versioned::partition_version_key({instance_id_, partition_id});
2586
7
            versioned_remove_all(txn.get(), meta_key);
2587
7
            txn->remove(index_key);
2588
7
            txn->remove(inverted_index_key);
2589
7
            versioned_remove_all(txn.get(), partition_version_key);
2590
7
            err = txn->commit();
2591
7
            if (err != TxnErrorCode::TXN_OK) {
2592
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2593
0
                return -1;
2594
0
            }
2595
7
        }
2596
2597
7
        if (ret == 0) {
2598
7
            ++num_recycled;
2599
7
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2600
7
            partition_keys.push_back(k);
2601
7
            if (part_pb.db_id() > 0) {
2602
7
                partition_version_keys.push_back(partition_version_key(
2603
7
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2604
7
            }
2605
7
            metrics_context.total_recycled_num = num_recycled;
2606
7
            metrics_context.report();
2607
7
        }
2608
7
        return ret;
2609
7
    };
2610
2611
15
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2612
5
        if (partition_keys.empty()) return 0;
2613
4
        DORIS_CLOUD_DEFER {
2614
4
            partition_keys.clear();
2615
4
            partition_version_keys.clear();
2616
4
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2613
1
        DORIS_CLOUD_DEFER {
2614
1
            partition_keys.clear();
2615
1
            partition_version_keys.clear();
2616
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2613
3
        DORIS_CLOUD_DEFER {
2614
3
            partition_keys.clear();
2615
3
            partition_version_keys.clear();
2616
3
        };
2617
4
        std::unique_ptr<Transaction> txn;
2618
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2619
4
        if (err != TxnErrorCode::TXN_OK) {
2620
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2621
0
            return -1;
2622
0
        }
2623
8
        for (auto& k : partition_keys) {
2624
8
            txn->remove(k);
2625
8
        }
2626
8
        for (auto& k : partition_version_keys) {
2627
8
            txn->remove(k);
2628
8
        }
2629
4
        err = txn->commit();
2630
4
        if (err != TxnErrorCode::TXN_OK) {
2631
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2632
0
                         << " err=" << err;
2633
0
            return -1;
2634
0
        }
2635
4
        return 0;
2636
4
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2611
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2612
2
        if (partition_keys.empty()) return 0;
2613
1
        DORIS_CLOUD_DEFER {
2614
1
            partition_keys.clear();
2615
1
            partition_version_keys.clear();
2616
1
        };
2617
1
        std::unique_ptr<Transaction> txn;
2618
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2619
1
        if (err != TxnErrorCode::TXN_OK) {
2620
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2621
0
            return -1;
2622
0
        }
2623
1
        for (auto& k : partition_keys) {
2624
1
            txn->remove(k);
2625
1
        }
2626
1
        for (auto& k : partition_version_keys) {
2627
1
            txn->remove(k);
2628
1
        }
2629
1
        err = txn->commit();
2630
1
        if (err != TxnErrorCode::TXN_OK) {
2631
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2632
0
                         << " err=" << err;
2633
0
            return -1;
2634
0
        }
2635
1
        return 0;
2636
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2611
3
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2612
3
        if (partition_keys.empty()) return 0;
2613
3
        DORIS_CLOUD_DEFER {
2614
3
            partition_keys.clear();
2615
3
            partition_version_keys.clear();
2616
3
        };
2617
3
        std::unique_ptr<Transaction> txn;
2618
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2619
3
        if (err != TxnErrorCode::TXN_OK) {
2620
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2621
0
            return -1;
2622
0
        }
2623
7
        for (auto& k : partition_keys) {
2624
7
            txn->remove(k);
2625
7
        }
2626
7
        for (auto& k : partition_version_keys) {
2627
7
            txn->remove(k);
2628
7
        }
2629
3
        err = txn->commit();
2630
3
        if (err != TxnErrorCode::TXN_OK) {
2631
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2632
0
                         << " err=" << err;
2633
0
            return -1;
2634
0
        }
2635
3
        return 0;
2636
3
    };
2637
2638
15
    if (config::enable_recycler_stats_metrics) {
2639
0
        scan_and_statistics_partitions();
2640
0
    }
2641
    // recycle_func and loop_done for scan and recycle
2642
15
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
2643
15
}
2644
2645
14
int InstanceRecycler::recycle_versions() {
2646
14
    if (should_recycle_versioned_keys()) {
2647
2
        return recycle_orphan_partitions();
2648
2
    }
2649
2650
12
    int64_t num_scanned = 0;
2651
12
    int64_t num_recycled = 0;
2652
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
2653
2654
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
2655
2656
12
    auto start_time = steady_clock::now();
2657
2658
12
    DORIS_CLOUD_DEFER {
2659
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2660
12
        metrics_context.finish_report();
2661
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
2662
12
                .tag("instance_id", instance_id_)
2663
12
                .tag("num_scanned", num_scanned)
2664
12
                .tag("num_recycled", num_recycled);
2665
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
2658
12
    DORIS_CLOUD_DEFER {
2659
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2660
12
        metrics_context.finish_report();
2661
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
2662
12
                .tag("instance_id", instance_id_)
2663
12
                .tag("num_scanned", num_scanned)
2664
12
                .tag("num_recycled", num_recycled);
2665
12
    };
2666
2667
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
2668
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
2669
12
    int64_t last_scanned_table_id = 0;
2670
12
    bool is_recycled = false; // Is last scanned kv recycled
2671
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
2672
12
                         &metrics_context, this](std::string_view k, std::string_view) {
2673
2
        ++num_scanned;
2674
2
        auto k1 = k;
2675
2
        k1.remove_prefix(1);
2676
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
2677
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2678
2
        decode_key(&k1, &out);
2679
2
        DCHECK_EQ(out.size(), 6) << k;
2680
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
2681
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
2682
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
2683
0
            return 0;
2684
0
        }
2685
2
        last_scanned_table_id = table_id;
2686
2
        is_recycled = false;
2687
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
2688
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
2689
2
        std::unique_ptr<Transaction> txn;
2690
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2691
2
        if (err != TxnErrorCode::TXN_OK) {
2692
0
            return -1;
2693
0
        }
2694
2
        std::unique_ptr<RangeGetIterator> iter;
2695
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
2696
2
        if (err != TxnErrorCode::TXN_OK) {
2697
0
            return -1;
2698
0
        }
2699
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
2700
1
            return 0;
2701
1
        }
2702
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2703
        // 1. Remove all partition version kvs of this table
2704
1
        auto partition_version_key_begin =
2705
1
                partition_version_key({instance_id_, db_id, table_id, 0});
2706
1
        auto partition_version_key_end =
2707
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
2708
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
2709
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
2710
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
2711
1
                     << " table_id=" << table_id;
2712
        // 2. Remove the table version kv of this table
2713
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
2714
1
        txn->remove(tbl_version_key);
2715
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
2716
        // 3. Remove mow delete bitmap update lock and tablet job lock
2717
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2718
1
        txn->remove(lock_key);
2719
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2720
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2721
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2722
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
2723
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2724
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2725
1
                     << " table_id=" << table_id;
2726
1
        err = txn->commit();
2727
1
        if (err != TxnErrorCode::TXN_OK) {
2728
0
            return -1;
2729
0
        }
2730
1
        metrics_context.total_recycled_num = ++num_recycled;
2731
1
        metrics_context.report();
2732
1
        is_recycled = true;
2733
1
        return 0;
2734
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2672
2
                         &metrics_context, this](std::string_view k, std::string_view) {
2673
2
        ++num_scanned;
2674
2
        auto k1 = k;
2675
2
        k1.remove_prefix(1);
2676
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
2677
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2678
2
        decode_key(&k1, &out);
2679
2
        DCHECK_EQ(out.size(), 6) << k;
2680
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
2681
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
2682
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
2683
0
            return 0;
2684
0
        }
2685
2
        last_scanned_table_id = table_id;
2686
2
        is_recycled = false;
2687
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
2688
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
2689
2
        std::unique_ptr<Transaction> txn;
2690
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2691
2
        if (err != TxnErrorCode::TXN_OK) {
2692
0
            return -1;
2693
0
        }
2694
2
        std::unique_ptr<RangeGetIterator> iter;
2695
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
2696
2
        if (err != TxnErrorCode::TXN_OK) {
2697
0
            return -1;
2698
0
        }
2699
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
2700
1
            return 0;
2701
1
        }
2702
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2703
        // 1. Remove all partition version kvs of this table
2704
1
        auto partition_version_key_begin =
2705
1
                partition_version_key({instance_id_, db_id, table_id, 0});
2706
1
        auto partition_version_key_end =
2707
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
2708
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
2709
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
2710
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
2711
1
                     << " table_id=" << table_id;
2712
        // 2. Remove the table version kv of this table
2713
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
2714
1
        txn->remove(tbl_version_key);
2715
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
2716
        // 3. Remove mow delete bitmap update lock and tablet job lock
2717
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2718
1
        txn->remove(lock_key);
2719
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2720
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2721
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2722
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
2723
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2724
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2725
1
                     << " table_id=" << table_id;
2726
1
        err = txn->commit();
2727
1
        if (err != TxnErrorCode::TXN_OK) {
2728
0
            return -1;
2729
0
        }
2730
1
        metrics_context.total_recycled_num = ++num_recycled;
2731
1
        metrics_context.report();
2732
1
        is_recycled = true;
2733
1
        return 0;
2734
1
    };
2735
2736
12
    if (config::enable_recycler_stats_metrics) {
2737
0
        scan_and_statistics_versions();
2738
0
    }
2739
    // recycle_func and loop_done for scan and recycle
2740
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
2741
14
}
2742
2743
3
int InstanceRecycler::recycle_orphan_partitions() {
2744
3
    int64_t num_scanned = 0;
2745
3
    int64_t num_recycled = 0;
2746
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
2747
2748
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
2749
3
            .tag("instance_id", instance_id_);
2750
2751
3
    auto start_time = steady_clock::now();
2752
2753
3
    DORIS_CLOUD_DEFER {
2754
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2755
3
        metrics_context.finish_report();
2756
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
2757
3
                .tag("instance_id", instance_id_)
2758
3
                .tag("num_scanned", num_scanned)
2759
3
                .tag("num_recycled", num_recycled);
2760
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
2753
3
    DORIS_CLOUD_DEFER {
2754
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2755
3
        metrics_context.finish_report();
2756
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
2757
3
                .tag("instance_id", instance_id_)
2758
3
                .tag("num_scanned", num_scanned)
2759
3
                .tag("num_recycled", num_recycled);
2760
3
    };
2761
2762
3
    bool is_empty_table = false;        // whether the table has no indexes
2763
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
2764
3
    int64_t current_table_id = 0;       // current scanning table id
2765
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
2766
3
                         &current_table_id, &is_table_kvs_recycled,
2767
3
                         this](std::string_view k, std::string_view) {
2768
2
        ++num_scanned;
2769
2770
2
        std::string_view k1(k);
2771
2
        int64_t db_id, table_id, partition_id;
2772
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
2773
2
                                                            &partition_id)) {
2774
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
2775
0
            return -1;
2776
2
        } else if (table_id != current_table_id) {
2777
2
            current_table_id = table_id;
2778
2
            is_table_kvs_recycled = false;
2779
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
2780
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
2781
2
            if (err != TxnErrorCode::TXN_OK) {
2782
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
2783
0
                             << " table_id=" << table_id << " err=" << err;
2784
0
                return -1;
2785
0
            }
2786
2
        }
2787
2788
2
        if (!is_empty_table) {
2789
            // table is not empty, skip recycle
2790
1
            return 0;
2791
1
        }
2792
2793
1
        std::unique_ptr<Transaction> txn;
2794
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2795
1
        if (err != TxnErrorCode::TXN_OK) {
2796
0
            return -1;
2797
0
        }
2798
2799
        // 1. Remove all partition related kvs
2800
1
        std::string partition_meta_key =
2801
1
                versioned::meta_partition_key({instance_id_, partition_id});
2802
1
        std::string partition_index_key =
2803
1
                versioned::partition_index_key({instance_id_, partition_id});
2804
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
2805
1
                {instance_id_, db_id, table_id, partition_id});
2806
1
        std::string partition_version_key =
2807
1
                versioned::partition_version_key({instance_id_, partition_id});
2808
1
        txn->remove(partition_index_key);
2809
1
        txn->remove(partition_inverted_key);
2810
1
        versioned_remove_all(txn.get(), partition_meta_key);
2811
1
        versioned_remove_all(txn.get(), partition_version_key);
2812
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
2813
1
                     << " table_id=" << table_id << " db_id=" << db_id
2814
1
                     << " partition_meta_key=" << hex(partition_meta_key)
2815
1
                     << " partition_version_key=" << hex(partition_version_key);
2816
2817
1
        if (!is_table_kvs_recycled) {
2818
1
            is_table_kvs_recycled = true;
2819
2820
            // 2. Remove the table version kv of this table
2821
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
2822
1
            versioned_remove_all(txn.get(), table_version_key);
2823
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
2824
            // 3. Remove mow delete bitmap update lock and tablet job lock
2825
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2826
1
            txn->remove(lock_key);
2827
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2828
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2829
1
            std::string tablet_job_key_end =
2830
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2831
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
2832
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2833
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2834
1
                         << " table_id=" << table_id;
2835
1
        }
2836
2837
1
        err = txn->commit();
2838
1
        if (err != TxnErrorCode::TXN_OK) {
2839
0
            return -1;
2840
0
        }
2841
1
        metrics_context.total_recycled_num = ++num_recycled;
2842
1
        metrics_context.report();
2843
1
        return 0;
2844
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
2767
2
                         this](std::string_view k, std::string_view) {
2768
2
        ++num_scanned;
2769
2770
2
        std::string_view k1(k);
2771
2
        int64_t db_id, table_id, partition_id;
2772
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
2773
2
                                                            &partition_id)) {
2774
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
2775
0
            return -1;
2776
2
        } else if (table_id != current_table_id) {
2777
2
            current_table_id = table_id;
2778
2
            is_table_kvs_recycled = false;
2779
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
2780
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
2781
2
            if (err != TxnErrorCode::TXN_OK) {
2782
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
2783
0
                             << " table_id=" << table_id << " err=" << err;
2784
0
                return -1;
2785
0
            }
2786
2
        }
2787
2788
2
        if (!is_empty_table) {
2789
            // table is not empty, skip recycle
2790
1
            return 0;
2791
1
        }
2792
2793
1
        std::unique_ptr<Transaction> txn;
2794
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2795
1
        if (err != TxnErrorCode::TXN_OK) {
2796
0
            return -1;
2797
0
        }
2798
2799
        // 1. Remove all partition related kvs
2800
1
        std::string partition_meta_key =
2801
1
                versioned::meta_partition_key({instance_id_, partition_id});
2802
1
        std::string partition_index_key =
2803
1
                versioned::partition_index_key({instance_id_, partition_id});
2804
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
2805
1
                {instance_id_, db_id, table_id, partition_id});
2806
1
        std::string partition_version_key =
2807
1
                versioned::partition_version_key({instance_id_, partition_id});
2808
1
        txn->remove(partition_index_key);
2809
1
        txn->remove(partition_inverted_key);
2810
1
        versioned_remove_all(txn.get(), partition_meta_key);
2811
1
        versioned_remove_all(txn.get(), partition_version_key);
2812
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
2813
1
                     << " table_id=" << table_id << " db_id=" << db_id
2814
1
                     << " partition_meta_key=" << hex(partition_meta_key)
2815
1
                     << " partition_version_key=" << hex(partition_version_key);
2816
2817
1
        if (!is_table_kvs_recycled) {
2818
1
            is_table_kvs_recycled = true;
2819
2820
            // 2. Remove the table version kv of this table
2821
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
2822
1
            versioned_remove_all(txn.get(), table_version_key);
2823
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
2824
            // 3. Remove mow delete bitmap update lock and tablet job lock
2825
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2826
1
            txn->remove(lock_key);
2827
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2828
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2829
1
            std::string tablet_job_key_end =
2830
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2831
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
2832
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2833
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2834
1
                         << " table_id=" << table_id;
2835
1
        }
2836
2837
1
        err = txn->commit();
2838
1
        if (err != TxnErrorCode::TXN_OK) {
2839
0
            return -1;
2840
0
        }
2841
1
        metrics_context.total_recycled_num = ++num_recycled;
2842
1
        metrics_context.report();
2843
1
        return 0;
2844
1
    };
2845
2846
    // recycle_func and loop_done for scan and recycle
2847
3
    return scan_and_recycle(
2848
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
2849
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
2850
3
            std::move(recycle_func));
2851
3
}
2852
2853
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
2854
                                      RecyclerMetricsContext& metrics_context,
2855
52
                                      int64_t partition_id) {
2856
52
    bool is_multi_version =
2857
52
            instance_info_.has_multi_version_status() &&
2858
52
            instance_info_.multi_version_status() != MultiVersionStatus::MULTI_VERSION_DISABLED;
2859
52
    int64_t num_scanned = 0;
2860
52
    std::atomic_long num_recycled = 0;
2861
2862
52
    std::string tablet_key_begin, tablet_key_end;
2863
52
    std::string stats_key_begin, stats_key_end;
2864
52
    std::string job_key_begin, job_key_end;
2865
2866
52
    std::string tablet_belongs;
2867
52
    if (partition_id > 0) {
2868
        // recycle tablets in a partition belonging to the index
2869
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
2870
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
2871
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
2872
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
2873
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
2874
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
2875
33
        tablet_belongs = "partition";
2876
33
    } else {
2877
        // recycle tablets in the index
2878
19
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
2879
19
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
2880
19
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
2881
19
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
2882
19
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
2883
19
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
2884
19
        tablet_belongs = "index";
2885
19
    }
2886
2887
52
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
2888
52
            .tag("table_id", table_id)
2889
52
            .tag("index_id", index_id)
2890
52
            .tag("partition_id", partition_id);
2891
2892
52
    auto start_time = steady_clock::now();
2893
2894
52
    DORIS_CLOUD_DEFER {
2895
52
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2896
52
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
2897
52
                .tag("instance_id", instance_id_)
2898
52
                .tag("table_id", table_id)
2899
52
                .tag("index_id", index_id)
2900
52
                .tag("partition_id", partition_id)
2901
52
                .tag("num_scanned", num_scanned)
2902
52
                .tag("num_recycled", num_recycled);
2903
52
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
2894
4
    DORIS_CLOUD_DEFER {
2895
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2896
4
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
2897
4
                .tag("instance_id", instance_id_)
2898
4
                .tag("table_id", table_id)
2899
4
                .tag("index_id", index_id)
2900
4
                .tag("partition_id", partition_id)
2901
4
                .tag("num_scanned", num_scanned)
2902
4
                .tag("num_recycled", num_recycled);
2903
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
2894
48
    DORIS_CLOUD_DEFER {
2895
48
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2896
48
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
2897
48
                .tag("instance_id", instance_id_)
2898
48
                .tag("table_id", table_id)
2899
48
                .tag("index_id", index_id)
2900
48
                .tag("partition_id", partition_id)
2901
48
                .tag("num_scanned", num_scanned)
2902
48
                .tag("num_recycled", num_recycled);
2903
48
    };
2904
2905
    // The tablet key and id which have been recycled.
2906
52
    struct TabletInfo {
2907
52
        std::string_view tablet_meta_key;
2908
52
        int64_t tablet_id;
2909
52
    };
2910
52
    SyncExecutor<TabletInfo> sync_executor(
2911
52
            _thread_pool_group.recycle_tablet_pool,
2912
52
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
2913
52
                        index_id, partition_id),
2914
4.24k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
2914
4.00k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
2914
241
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
2915
2916
    // Elements in `tablets_info` has the same lifetime as `it` in `scan_and_recycle`
2917
52
    std::vector<std::string> init_rs_keys;
2918
52
    bool has_failure = false;
2919
8.25k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2920
8.25k
        ++num_scanned;
2921
8.25k
        doris::TabletMetaCloudPB tablet_meta_pb;
2922
8.25k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
2923
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
2924
0
            has_failure = true;
2925
0
            return -1;
2926
0
        }
2927
8.25k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
2928
2929
8.25k
        if (config::enable_recycler_check_lazy_txn_finished &&
2930
8.25k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
2931
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
2932
4.00k
            has_failure = true;
2933
4.00k
            return -1;
2934
4.00k
        }
2935
2936
4.25k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
2937
4.25k
        sync_executor.add(
2938
4.25k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
2939
4.25k
                    if (recycle_tablet(tid, metrics_context) != 0) {
2940
2
                        LOG_WARNING("failed to recycle tablet")
2941
2
                                .tag("instance_id", instance_id_)
2942
2
                                .tag("tablet_id", tid);
2943
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
2944
2
                    }
2945
4.25k
                    ++num_recycled;
2946
4.25k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2947
4.25k
                    return {.tablet_meta_key = k, .tablet_id = tid};
2948
4.25k
                });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
2938
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
2939
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
2940
0
                        LOG_WARNING("failed to recycle tablet")
2941
0
                                .tag("instance_id", instance_id_)
2942
0
                                .tag("tablet_id", tid);
2943
0
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
2944
0
                    }
2945
4.00k
                    ++num_recycled;
2946
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2947
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
2948
4.00k
                });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
2938
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
2939
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
2940
2
                        LOG_WARNING("failed to recycle tablet")
2941
2
                                .tag("instance_id", instance_id_)
2942
2
                                .tag("tablet_id", tid);
2943
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
2944
2
                    }
2945
248
                    ++num_recycled;
2946
248
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2947
248
                    return {.tablet_meta_key = k, .tablet_id = tid};
2948
250
                });
2949
4.25k
        return 0;
2950
4.25k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
2919
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2920
8.00k
        ++num_scanned;
2921
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
2922
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
2923
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
2924
0
            has_failure = true;
2925
0
            return -1;
2926
0
        }
2927
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
2928
2929
8.00k
        if (config::enable_recycler_check_lazy_txn_finished &&
2930
8.00k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
2931
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
2932
4.00k
            has_failure = true;
2933
4.00k
            return -1;
2934
4.00k
        }
2935
2936
4.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
2937
4.00k
        sync_executor.add(
2938
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
2939
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
2940
4.00k
                        LOG_WARNING("failed to recycle tablet")
2941
4.00k
                                .tag("instance_id", instance_id_)
2942
4.00k
                                .tag("tablet_id", tid);
2943
4.00k
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
2944
4.00k
                    }
2945
4.00k
                    ++num_recycled;
2946
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2947
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
2948
4.00k
                });
2949
4.00k
        return 0;
2950
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
2919
251
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2920
251
        ++num_scanned;
2921
251
        doris::TabletMetaCloudPB tablet_meta_pb;
2922
251
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
2923
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
2924
0
            has_failure = true;
2925
0
            return -1;
2926
0
        }
2927
251
        int64_t tablet_id = tablet_meta_pb.tablet_id();
2928
2929
251
        if (config::enable_recycler_check_lazy_txn_finished &&
2930
251
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
2931
1
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
2932
1
            has_failure = true;
2933
1
            return -1;
2934
1
        }
2935
2936
250
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
2937
250
        sync_executor.add(
2938
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
2939
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
2940
250
                        LOG_WARNING("failed to recycle tablet")
2941
250
                                .tag("instance_id", instance_id_)
2942
250
                                .tag("tablet_id", tid);
2943
250
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
2944
250
                    }
2945
250
                    ++num_recycled;
2946
250
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2947
250
                    return {.tablet_meta_key = k, .tablet_id = tid};
2948
250
                });
2949
250
        return 0;
2950
250
    };
2951
2952
52
    auto loop_done = [&, this]() -> int {
2953
52
        int ret = 0;
2954
52
        bool finished = true;
2955
52
        bool has_empty_key = false;
2956
52
        DORIS_CLOUD_DEFER {
2957
52
            init_rs_keys.clear();
2958
52
            has_failure = false;
2959
52
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2956
4
        DORIS_CLOUD_DEFER {
2957
4
            init_rs_keys.clear();
2958
4
            has_failure = false;
2959
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2956
48
        DORIS_CLOUD_DEFER {
2957
48
            init_rs_keys.clear();
2958
48
            has_failure = false;
2959
48
        };
2960
52
        auto tablets_info = sync_executor.when_all(&finished);
2961
52
        if (!finished) {
2962
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
2963
1
            return -1;
2964
1
        }
2965
2966
51
        size_t size_before_erase = tablets_info.size();
2967
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
2967
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
2967
249
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
2968
51
        if (tablets_info.empty()) {
2969
2
            return size_before_erase == 0 ? 0 : -1;
2970
49
        } else if (size_before_erase != tablets_info.size()) {
2971
1
            has_empty_key = true;
2972
1
        }
2973
2974
49
        ret = has_empty_key ? -1 : 0;
2975
        // sort the vector using key's order
2976
49.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
2977
49.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
2978
49.4k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
2976
48.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
2977
48.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
2978
48.4k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
2976
958
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
2977
958
            return prev.tablet_meta_key < last.tablet_meta_key;
2978
958
        });
2979
49
        std::unique_ptr<Transaction> txn;
2980
49
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2981
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
2982
0
            return -1;
2983
0
        }
2984
49
        std::string tablet_key_end;
2985
49
        if (!tablets_info.empty()) {
2986
49
            if (!has_empty_key && !has_failure) {
2987
47
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
2988
47
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
2989
47
            } else {
2990
8
                for (auto& tablet_info : tablets_info) {
2991
8
                    txn->remove(tablet_info.tablet_meta_key);
2992
8
                }
2993
2
            }
2994
49
        }
2995
49
        if (is_multi_version) {
2996
6
            for (auto& tablet_info : tablets_info) {
2997
                // Remove all versions of tablet compact stats for recycled tablet
2998
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
2999
6
                LOG_INFO("remove versioned tablet compact stats key")
3000
6
                        .tag("compact_stats_key", hex(k));
3001
6
                versioned_remove_all(txn.get(), k);
3002
6
            }
3003
6
            for (auto& tablet_info : tablets_info) {
3004
                // Remove all versions of tablet load stats for recycled tablet
3005
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3006
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3007
6
                versioned_remove_all(txn.get(), k);
3008
6
            }
3009
6
            for (auto& tablet_info : tablets_info) {
3010
                // Remove all versions of meta tablet for recycled tablet
3011
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3012
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3013
6
                versioned_remove_all(txn.get(), k);
3014
6
            }
3015
5
        }
3016
4.25k
        for (auto& tablet_info : tablets_info) {
3017
4.25k
            std::string k;
3018
4.25k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3019
4.25k
            txn->remove(k);
3020
4.25k
        }
3021
4.25k
        for (auto& tablet_info : tablets_info) {
3022
4.25k
            std::string k;
3023
4.25k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3024
4.25k
            txn->remove(k);
3025
4.25k
        }
3026
49
        for (auto& k : init_rs_keys) {
3027
0
            txn->remove(k);
3028
0
        }
3029
49
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3030
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3031
0
                         << ", err=" << err;
3032
0
            return -1;
3033
0
        }
3034
49
        return ret;
3035
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
2952
4
    auto loop_done = [&, this]() -> int {
2953
4
        int ret = 0;
2954
4
        bool finished = true;
2955
4
        bool has_empty_key = false;
2956
4
        DORIS_CLOUD_DEFER {
2957
4
            init_rs_keys.clear();
2958
4
            has_failure = false;
2959
4
        };
2960
4
        auto tablets_info = sync_executor.when_all(&finished);
2961
4
        if (!finished) {
2962
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
2963
0
            return -1;
2964
0
        }
2965
2966
4
        size_t size_before_erase = tablets_info.size();
2967
4
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
2968
4
        if (tablets_info.empty()) {
2969
2
            return size_before_erase == 0 ? 0 : -1;
2970
2
        } else if (size_before_erase != tablets_info.size()) {
2971
0
            has_empty_key = true;
2972
0
        }
2973
2974
2
        ret = has_empty_key ? -1 : 0;
2975
        // sort the vector using key's order
2976
2
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
2977
2
            return prev.tablet_meta_key < last.tablet_meta_key;
2978
2
        });
2979
2
        std::unique_ptr<Transaction> txn;
2980
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2981
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
2982
0
            return -1;
2983
0
        }
2984
2
        std::string tablet_key_end;
2985
2
        if (!tablets_info.empty()) {
2986
2
            if (!has_empty_key && !has_failure) {
2987
2
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
2988
2
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
2989
2
            } else {
2990
0
                for (auto& tablet_info : tablets_info) {
2991
0
                    txn->remove(tablet_info.tablet_meta_key);
2992
0
                }
2993
0
            }
2994
2
        }
2995
2
        if (is_multi_version) {
2996
0
            for (auto& tablet_info : tablets_info) {
2997
                // Remove all versions of tablet compact stats for recycled tablet
2998
0
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
2999
0
                LOG_INFO("remove versioned tablet compact stats key")
3000
0
                        .tag("compact_stats_key", hex(k));
3001
0
                versioned_remove_all(txn.get(), k);
3002
0
            }
3003
0
            for (auto& tablet_info : tablets_info) {
3004
                // Remove all versions of tablet load stats for recycled tablet
3005
0
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3006
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3007
0
                versioned_remove_all(txn.get(), k);
3008
0
            }
3009
0
            for (auto& tablet_info : tablets_info) {
3010
                // Remove all versions of meta tablet for recycled tablet
3011
0
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3012
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3013
0
                versioned_remove_all(txn.get(), k);
3014
0
            }
3015
0
        }
3016
4.00k
        for (auto& tablet_info : tablets_info) {
3017
4.00k
            std::string k;
3018
4.00k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3019
4.00k
            txn->remove(k);
3020
4.00k
        }
3021
4.00k
        for (auto& tablet_info : tablets_info) {
3022
4.00k
            std::string k;
3023
4.00k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3024
4.00k
            txn->remove(k);
3025
4.00k
        }
3026
2
        for (auto& k : init_rs_keys) {
3027
0
            txn->remove(k);
3028
0
        }
3029
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3030
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3031
0
                         << ", err=" << err;
3032
0
            return -1;
3033
0
        }
3034
2
        return ret;
3035
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
2952
48
    auto loop_done = [&, this]() -> int {
2953
48
        int ret = 0;
2954
48
        bool finished = true;
2955
48
        bool has_empty_key = false;
2956
48
        DORIS_CLOUD_DEFER {
2957
48
            init_rs_keys.clear();
2958
48
            has_failure = false;
2959
48
        };
2960
48
        auto tablets_info = sync_executor.when_all(&finished);
2961
48
        if (!finished) {
2962
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
2963
1
            return -1;
2964
1
        }
2965
2966
47
        size_t size_before_erase = tablets_info.size();
2967
47
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
2968
47
        if (tablets_info.empty()) {
2969
0
            return size_before_erase == 0 ? 0 : -1;
2970
47
        } else if (size_before_erase != tablets_info.size()) {
2971
1
            has_empty_key = true;
2972
1
        }
2973
2974
47
        ret = has_empty_key ? -1 : 0;
2975
        // sort the vector using key's order
2976
47
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
2977
47
            return prev.tablet_meta_key < last.tablet_meta_key;
2978
47
        });
2979
47
        std::unique_ptr<Transaction> txn;
2980
47
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2981
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
2982
0
            return -1;
2983
0
        }
2984
47
        std::string tablet_key_end;
2985
47
        if (!tablets_info.empty()) {
2986
47
            if (!has_empty_key && !has_failure) {
2987
45
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
2988
45
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
2989
45
            } else {
2990
8
                for (auto& tablet_info : tablets_info) {
2991
8
                    txn->remove(tablet_info.tablet_meta_key);
2992
8
                }
2993
2
            }
2994
47
        }
2995
47
        if (is_multi_version) {
2996
6
            for (auto& tablet_info : tablets_info) {
2997
                // Remove all versions of tablet compact stats for recycled tablet
2998
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
2999
6
                LOG_INFO("remove versioned tablet compact stats key")
3000
6
                        .tag("compact_stats_key", hex(k));
3001
6
                versioned_remove_all(txn.get(), k);
3002
6
            }
3003
6
            for (auto& tablet_info : tablets_info) {
3004
                // Remove all versions of tablet load stats for recycled tablet
3005
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3006
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3007
6
                versioned_remove_all(txn.get(), k);
3008
6
            }
3009
6
            for (auto& tablet_info : tablets_info) {
3010
                // Remove all versions of meta tablet for recycled tablet
3011
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3012
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3013
6
                versioned_remove_all(txn.get(), k);
3014
6
            }
3015
5
        }
3016
248
        for (auto& tablet_info : tablets_info) {
3017
248
            std::string k;
3018
248
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3019
248
            txn->remove(k);
3020
248
        }
3021
248
        for (auto& tablet_info : tablets_info) {
3022
248
            std::string k;
3023
248
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3024
248
            txn->remove(k);
3025
248
        }
3026
47
        for (auto& k : init_rs_keys) {
3027
0
            txn->remove(k);
3028
0
        }
3029
47
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3030
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3031
0
                         << ", err=" << err;
3032
0
            return -1;
3033
0
        }
3034
47
        return ret;
3035
47
    };
3036
3037
52
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
3038
52
                               std::move(loop_done));
3039
52
    if (ret != 0) {
3040
5
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
3041
5
        return ret;
3042
5
    }
3043
3044
    // directly remove tablet stats and tablet jobs of these dropped index or partition
3045
47
    std::unique_ptr<Transaction> txn;
3046
47
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3047
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
3048
0
        return -1;
3049
0
    }
3050
47
    txn->remove(stats_key_begin, stats_key_end);
3051
47
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
3052
47
                 << " end=" << hex(stats_key_end);
3053
47
    txn->remove(job_key_begin, job_key_end);
3054
47
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
3055
47
    std::string schema_key_begin, schema_key_end;
3056
47
    std::string schema_dict_key;
3057
47
    std::string versioned_schema_key_begin, versioned_schema_key_end;
3058
47
    if (partition_id <= 0) {
3059
        // Delete schema kv of this index
3060
15
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
3061
15
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
3062
15
        txn->remove(schema_key_begin, schema_key_end);
3063
15
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
3064
15
                     << " end=" << hex(schema_key_end);
3065
15
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
3066
15
        txn->remove(schema_dict_key);
3067
15
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
3068
15
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
3069
15
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
3070
15
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
3071
15
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
3072
15
                     << " end=" << hex(versioned_schema_key_end);
3073
15
    }
3074
3075
47
    TxnErrorCode err = txn->commit();
3076
47
    if (err != TxnErrorCode::TXN_OK) {
3077
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
3078
0
                     << " err=" << err;
3079
0
        return -1;
3080
0
    }
3081
3082
47
    return ret;
3083
47
}
3084
3085
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
3086
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
3087
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
3088
5.61k
    if (num_segments <= 0) return 0;
3089
3090
5.61k
    std::vector<std::string> file_paths;
3091
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
3092
0
        return -1;
3093
0
    }
3094
3095
    // Process inverted indexes
3096
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
3097
    // default format as v1.
3098
5.61k
    InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
3099
5.61k
    bool delete_rowset_data_by_prefix = false;
3100
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3101
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3102
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3103
0
        delete_rowset_data_by_prefix = true;
3104
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
3105
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
3106
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3107
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3108
10.0k
            }
3109
10.0k
        }
3110
4.80k
        if (rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
3111
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
3112
2.00k
        }
3113
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
3114
        // schema version and index id are not found, delete rowset data by prefix directly.
3115
0
        delete_rowset_data_by_prefix = true;
3116
809
    } else {
3117
        // otherwise, try to get schema kv
3118
809
        InvertedIndexInfo index_info;
3119
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
3120
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
3121
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3122
809
                                 &inverted_index_get_ret);
3123
809
        if (inverted_index_get_ret == 0) {
3124
809
            index_format = index_info.first;
3125
809
            index_ids = index_info.second;
3126
809
        } else if (inverted_index_get_ret == 1) {
3127
            // 1. Schema kv not found means tablet has been recycled
3128
            // Maybe some tablet recycle failed by some bugs
3129
            // We need to delete again to double check
3130
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3131
            // because we are uncertain about the inverted index information.
3132
            // If there are inverted indexes, some data might not be deleted,
3133
            // but this is acceptable as we have made our best effort to delete the data.
3134
0
            LOG_INFO(
3135
0
                    "delete rowset data schema kv not found, need to delete again to double "
3136
0
                    "check")
3137
0
                    .tag("instance_id", instance_id_)
3138
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3139
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
3140
            // Currently index_ids is guaranteed to be empty,
3141
            // but we clear it again here as a safeguard against future code changes
3142
            // that might cause index_ids to no longer be empty
3143
0
            index_format = InvertedIndexStorageFormatPB::V2;
3144
0
            index_ids.clear();
3145
0
        } else {
3146
            // failed to get schema kv, delete rowset data by prefix directly.
3147
0
            delete_rowset_data_by_prefix = true;
3148
0
        }
3149
809
    }
3150
3151
5.61k
    if (delete_rowset_data_by_prefix) {
3152
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
3153
0
                                  rs_meta_pb.rowset_id_v2());
3154
0
    }
3155
3156
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
3157
5.61k
    if (it == accessor_map_.end()) {
3158
1.59k
        LOG_WARNING("instance has no such resource id")
3159
1.59k
                .tag("instance_id", instance_id_)
3160
1.59k
                .tag("resource_id", rs_meta_pb.resource_id());
3161
1.59k
        return -1;
3162
1.59k
    }
3163
4.01k
    auto& accessor = it->second;
3164
3165
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
3166
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
3167
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
3168
20.0k
        add_file_to_delete_if_not_packed(rs_meta_pb, segment_path(tablet_id, rowset_id, i),
3169
20.0k
                                         &file_paths);
3170
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
3171
40.0k
            for (const auto& index_id : index_ids) {
3172
40.0k
                add_file_to_delete_if_not_packed(
3173
40.0k
                        rs_meta_pb,
3174
40.0k
                        inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
3175
40.0k
                                               index_id.second),
3176
40.0k
                        &file_paths);
3177
40.0k
            }
3178
20.0k
        } else if (!index_ids.empty()) {
3179
0
            add_file_to_delete_if_not_packed(
3180
0
                    rs_meta_pb, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
3181
0
        }
3182
20.0k
    }
3183
3184
    // Process delete bitmap - check where it's stored.
3185
4.01k
    DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3186
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3187
4.01k
                                                       &delete_bitmap_storage_type) != 0) {
3188
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3189
0
                .tag("instance_id", instance_id_)
3190
0
                .tag("tablet_id", tablet_id)
3191
0
                .tag("rowset_id", rowset_id);
3192
0
        return -1;
3193
0
    }
3194
4.01k
    if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3195
2.00k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3196
2.00k
    }
3197
    // TODO(AlexYue): seems could do do batch
3198
4.01k
    return accessor->delete_files(file_paths);
3199
4.01k
}
3200
3201
62.3k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3202
62.3k
    LOG_INFO("begin process_packed_file_location_index")
3203
62.3k
            .tag("instance_id", instance_id_)
3204
62.3k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3205
62.3k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3206
62.3k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3207
62.3k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3208
62.3k
    if (index_map.empty()) {
3209
62.3k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3210
62.3k
                .tag("instance_id", instance_id_)
3211
62.3k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3212
62.3k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3213
62.3k
        return 0;
3214
62.3k
    }
3215
3216
13
    struct PackedSmallFileInfo {
3217
13
        std::string small_file_path;
3218
13
    };
3219
13
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3220
13
    packed_file_updates.reserve(index_map.size());
3221
27
    for (const auto& [small_path, index_pb] : index_map) {
3222
27
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3223
0
            continue;
3224
0
        }
3225
27
        packed_file_updates[index_pb.packed_file_path()].push_back(
3226
27
                PackedSmallFileInfo {small_path});
3227
27
    }
3228
13
    if (packed_file_updates.empty()) {
3229
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3230
0
                .tag("instance_id", instance_id_)
3231
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3232
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3233
0
                .tag("index_map_size", index_map.size());
3234
0
        return 0;
3235
0
    }
3236
3237
13
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3238
13
    int ret = 0;
3239
24
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3240
24
        if (small_files.empty()) {
3241
0
            continue;
3242
0
        }
3243
3244
24
        bool success = false;
3245
24
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3246
24
            std::unique_ptr<Transaction> txn;
3247
24
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3248
24
            if (err != TxnErrorCode::TXN_OK) {
3249
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3250
0
                        .tag("instance_id", instance_id_)
3251
0
                        .tag("packed_file_path", packed_file_path)
3252
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3253
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3254
0
                        .tag("err", err);
3255
0
                ret = -1;
3256
0
                break;
3257
0
            }
3258
3259
24
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3260
24
            std::string packed_val;
3261
24
            err = txn->get(packed_key, &packed_val);
3262
24
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3263
0
                LOG_WARNING("packed file info not found when recycling rowset")
3264
0
                        .tag("instance_id", instance_id_)
3265
0
                        .tag("packed_file_path", packed_file_path)
3266
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3267
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3268
0
                        .tag("key", hex(packed_key))
3269
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3270
                // Skip this packed file entry and continue with others
3271
0
                success = true;
3272
0
                break;
3273
0
            }
3274
24
            if (err != TxnErrorCode::TXN_OK) {
3275
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
3276
0
                        .tag("instance_id", instance_id_)
3277
0
                        .tag("packed_file_path", packed_file_path)
3278
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3279
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3280
0
                        .tag("err", err);
3281
0
                ret = -1;
3282
0
                break;
3283
0
            }
3284
3285
24
            cloud::PackedFileInfoPB packed_info;
3286
24
            if (!packed_info.ParseFromString(packed_val)) {
3287
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
3288
0
                        .tag("instance_id", instance_id_)
3289
0
                        .tag("packed_file_path", packed_file_path)
3290
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3291
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3292
0
                ret = -1;
3293
0
                break;
3294
0
            }
3295
3296
24
            LOG_INFO("packed file update check")
3297
24
                    .tag("instance_id", instance_id_)
3298
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3299
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3300
24
                    .tag("merged_file_path", packed_file_path)
3301
24
                    .tag("requested_small_files", small_files.size())
3302
24
                    .tag("merge_entries", packed_info.slices_size());
3303
3304
24
            auto* small_file_entries = packed_info.mutable_slices();
3305
24
            int64_t changed_files = 0;
3306
24
            int64_t missing_entries = 0;
3307
24
            int64_t already_deleted = 0;
3308
27
            for (const auto& small_file_info : small_files) {
3309
27
                bool found = false;
3310
87
                for (auto& small_file_entry : *small_file_entries) {
3311
87
                    if (small_file_entry.path() == small_file_info.small_file_path) {
3312
27
                        if (!small_file_entry.deleted()) {
3313
27
                            small_file_entry.set_deleted(true);
3314
27
                            if (!small_file_entry.corrected()) {
3315
27
                                small_file_entry.set_corrected(true);
3316
27
                            }
3317
27
                            ++changed_files;
3318
27
                        } else {
3319
0
                            ++already_deleted;
3320
0
                        }
3321
27
                        found = true;
3322
27
                        break;
3323
27
                    }
3324
87
                }
3325
27
                if (!found) {
3326
0
                    ++missing_entries;
3327
0
                    LOG_WARNING("packed file info missing small file entry")
3328
0
                            .tag("instance_id", instance_id_)
3329
0
                            .tag("packed_file_path", packed_file_path)
3330
0
                            .tag("small_file_path", small_file_info.small_file_path)
3331
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3332
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
3333
0
                }
3334
27
            }
3335
3336
24
            if (changed_files == 0) {
3337
0
                LOG_INFO("skip merge file update: no merge entries changed")
3338
0
                        .tag("instance_id", instance_id_)
3339
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3340
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3341
0
                        .tag("merged_file_path", packed_file_path)
3342
0
                        .tag("missing_entries", missing_entries)
3343
0
                        .tag("already_deleted", already_deleted)
3344
0
                        .tag("requested_small_files", small_files.size())
3345
0
                        .tag("merge_entries", packed_info.slices_size());
3346
0
                success = true;
3347
0
                break;
3348
0
            }
3349
3350
            // Calculate remaining files
3351
24
            int64_t left_file_count = 0;
3352
24
            int64_t left_file_bytes = 0;
3353
141
            for (const auto& small_file_entry : packed_info.slices()) {
3354
141
                if (!small_file_entry.deleted()) {
3355
57
                    ++left_file_count;
3356
57
                    left_file_bytes += small_file_entry.size();
3357
57
                }
3358
141
            }
3359
24
            packed_info.set_remaining_slice_bytes(left_file_bytes);
3360
24
            packed_info.set_ref_cnt(left_file_count);
3361
24
            LOG_INFO("updated packed file reference info")
3362
24
                    .tag("instance_id", instance_id_)
3363
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3364
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3365
24
                    .tag("packed_file_path", packed_file_path)
3366
24
                    .tag("ref_cnt", left_file_count)
3367
24
                    .tag("left_file_bytes", left_file_bytes);
3368
3369
24
            if (left_file_count == 0) {
3370
7
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3371
7
            }
3372
3373
24
            std::string updated_val;
3374
24
            if (!packed_info.SerializeToString(&updated_val)) {
3375
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
3376
0
                        .tag("instance_id", instance_id_)
3377
0
                        .tag("packed_file_path", packed_file_path)
3378
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3379
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3380
0
                ret = -1;
3381
0
                break;
3382
0
            }
3383
3384
24
            txn->put(packed_key, updated_val);
3385
24
            err = txn->commit();
3386
24
            if (err == TxnErrorCode::TXN_OK) {
3387
24
                success = true;
3388
24
                if (left_file_count == 0) {
3389
7
                    LOG_INFO("packed file ready to delete, deleting immediately")
3390
7
                            .tag("instance_id", instance_id_)
3391
7
                            .tag("packed_file_path", packed_file_path);
3392
7
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3393
0
                        ret = -1;
3394
0
                    }
3395
7
                }
3396
24
                break;
3397
24
            }
3398
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
3399
0
                if (attempt >= max_retry_times) {
3400
0
                    LOG_WARNING("packed file info update conflict after max retry")
3401
0
                            .tag("instance_id", instance_id_)
3402
0
                            .tag("packed_file_path", packed_file_path)
3403
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3404
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
3405
0
                            .tag("changed_files", changed_files)
3406
0
                            .tag("attempt", attempt);
3407
0
                    ret = -1;
3408
0
                    break;
3409
0
                }
3410
0
                LOG_WARNING("packed file info update conflict, retrying")
3411
0
                        .tag("instance_id", instance_id_)
3412
0
                        .tag("packed_file_path", packed_file_path)
3413
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3414
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3415
0
                        .tag("changed_files", changed_files)
3416
0
                        .tag("attempt", attempt);
3417
0
                sleep_for_packed_file_retry();
3418
0
                continue;
3419
0
            }
3420
3421
0
            LOG_WARNING("failed to commit packed file info update")
3422
0
                    .tag("instance_id", instance_id_)
3423
0
                    .tag("packed_file_path", packed_file_path)
3424
0
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3425
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3426
0
                    .tag("err", err)
3427
0
                    .tag("changed_files", changed_files);
3428
0
            ret = -1;
3429
0
            break;
3430
0
        }
3431
3432
24
        if (!success) {
3433
0
            ret = -1;
3434
0
        }
3435
24
    }
3436
3437
13
    return ret;
3438
13
}
3439
3440
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(
3441
        int64_t tablet_id, const std::string& rowset_id,
3442
58.2k
        DeleteBitmapStorageType* out_storage_type) {
3443
58.2k
    if (out_storage_type) {
3444
58.2k
        *out_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3445
58.2k
    }
3446
3447
    // Get delete bitmap storage info from FDB
3448
58.2k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
3449
58.2k
    std::unique_ptr<Transaction> txn;
3450
58.2k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
3451
58.2k
    if (err != TxnErrorCode::TXN_OK) {
3452
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
3453
0
                .tag("instance_id", instance_id_)
3454
0
                .tag("tablet_id", tablet_id)
3455
0
                .tag("rowset_id", rowset_id)
3456
0
                .tag("err", err);
3457
0
        return -1;
3458
0
    }
3459
3460
58.2k
    std::string dbm_val;
3461
58.2k
    err = txn->get(dbm_key, &dbm_val);
3462
58.2k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3463
        // No delete bitmap for this rowset, nothing to do
3464
4.63k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
3465
4.63k
                .tag("instance_id", instance_id_)
3466
4.63k
                .tag("tablet_id", tablet_id)
3467
4.63k
                .tag("rowset_id", rowset_id);
3468
4.63k
        return 0;
3469
4.63k
    }
3470
53.5k
    if (err != TxnErrorCode::TXN_OK) {
3471
0
        LOG_WARNING("failed to get delete bitmap storage")
3472
0
                .tag("instance_id", instance_id_)
3473
0
                .tag("tablet_id", tablet_id)
3474
0
                .tag("rowset_id", rowset_id)
3475
0
                .tag("err", err);
3476
0
        return -1;
3477
0
    }
3478
3479
53.5k
    DeleteBitmapStoragePB storage;
3480
53.5k
    if (!storage.ParseFromString(dbm_val)) {
3481
0
        LOG_WARNING("failed to parse delete bitmap storage")
3482
0
                .tag("instance_id", instance_id_)
3483
0
                .tag("tablet_id", tablet_id)
3484
0
                .tag("rowset_id", rowset_id);
3485
0
        return -1;
3486
0
    }
3487
3488
53.5k
    if (storage.store_in_fdb()) {
3489
0
        if (out_storage_type) {
3490
0
            *out_storage_type = DeleteBitmapStorageType::IN_FDB;
3491
0
        }
3492
0
        return 0;
3493
0
    }
3494
3495
    // Check if delete bitmap is stored in standalone file.
3496
53.5k
    if (!storage.has_packed_slice_location() ||
3497
53.5k
        storage.packed_slice_location().packed_file_path().empty()) {
3498
53.5k
        if (out_storage_type) {
3499
53.5k
            *out_storage_type = DeleteBitmapStorageType::STANDALONE_FILE;
3500
53.5k
        }
3501
53.5k
        return 0;
3502
53.5k
    }
3503
3504
18.4E
    if (out_storage_type) {
3505
0
        *out_storage_type = DeleteBitmapStorageType::PACKED_FILE;
3506
0
    }
3507
3508
18.4E
    const auto& packed_loc = storage.packed_slice_location();
3509
18.4E
    const std::string& packed_file_path = packed_loc.packed_file_path();
3510
3511
18.4E
    LOG_INFO("decrementing delete bitmap packed file ref count")
3512
18.4E
            .tag("instance_id", instance_id_)
3513
18.4E
            .tag("tablet_id", tablet_id)
3514
18.4E
            .tag("rowset_id", rowset_id)
3515
18.4E
            .tag("packed_file_path", packed_file_path);
3516
3517
18.4E
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3518
18.4E
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3519
0
        std::unique_ptr<Transaction> update_txn;
3520
0
        err = txn_kv_->create_txn(&update_txn);
3521
0
        if (err != TxnErrorCode::TXN_OK) {
3522
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
3523
0
                    .tag("instance_id", instance_id_)
3524
0
                    .tag("tablet_id", tablet_id)
3525
0
                    .tag("rowset_id", rowset_id)
3526
0
                    .tag("err", err);
3527
0
            return -1;
3528
0
        }
3529
3530
0
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3531
0
        std::string packed_val;
3532
0
        err = update_txn->get(packed_key, &packed_val);
3533
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3534
0
            LOG_WARNING("packed file info not found for delete bitmap")
3535
0
                    .tag("instance_id", instance_id_)
3536
0
                    .tag("tablet_id", tablet_id)
3537
0
                    .tag("rowset_id", rowset_id)
3538
0
                    .tag("packed_file_path", packed_file_path);
3539
0
            return 0;
3540
0
        }
3541
0
        if (err != TxnErrorCode::TXN_OK) {
3542
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
3543
0
                    .tag("instance_id", instance_id_)
3544
0
                    .tag("tablet_id", tablet_id)
3545
0
                    .tag("rowset_id", rowset_id)
3546
0
                    .tag("packed_file_path", packed_file_path)
3547
0
                    .tag("err", err);
3548
0
            return -1;
3549
0
        }
3550
3551
0
        cloud::PackedFileInfoPB packed_info;
3552
0
        if (!packed_info.ParseFromString(packed_val)) {
3553
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
3554
0
                    .tag("instance_id", instance_id_)
3555
0
                    .tag("tablet_id", tablet_id)
3556
0
                    .tag("rowset_id", rowset_id)
3557
0
                    .tag("packed_file_path", packed_file_path);
3558
0
            return -1;
3559
0
        }
3560
3561
        // Find and mark the small file entry as deleted
3562
        // Use tablet_id and rowset_id to match entry instead of path,
3563
        // because path format may vary with path_version (with or without shard prefix)
3564
0
        auto* entries = packed_info.mutable_slices();
3565
0
        bool found = false;
3566
0
        bool already_deleted = false;
3567
0
        for (auto& entry : *entries) {
3568
0
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
3569
0
                if (!entry.deleted()) {
3570
0
                    entry.set_deleted(true);
3571
0
                    if (!entry.corrected()) {
3572
0
                        entry.set_corrected(true);
3573
0
                    }
3574
0
                } else {
3575
0
                    already_deleted = true;
3576
0
                }
3577
0
                found = true;
3578
0
                break;
3579
0
            }
3580
0
        }
3581
3582
0
        if (!found) {
3583
0
            LOG_WARNING("delete bitmap entry not found in packed file")
3584
0
                    .tag("instance_id", instance_id_)
3585
0
                    .tag("tablet_id", tablet_id)
3586
0
                    .tag("rowset_id", rowset_id)
3587
0
                    .tag("packed_file_path", packed_file_path);
3588
0
            return 0;
3589
0
        }
3590
3591
0
        if (already_deleted) {
3592
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
3593
0
                    .tag("instance_id", instance_id_)
3594
0
                    .tag("tablet_id", tablet_id)
3595
0
                    .tag("rowset_id", rowset_id)
3596
0
                    .tag("packed_file_path", packed_file_path);
3597
0
            return 0;
3598
0
        }
3599
3600
        // Calculate remaining files
3601
0
        int64_t left_file_count = 0;
3602
0
        int64_t left_file_bytes = 0;
3603
0
        for (const auto& entry : packed_info.slices()) {
3604
0
            if (!entry.deleted()) {
3605
0
                ++left_file_count;
3606
0
                left_file_bytes += entry.size();
3607
0
            }
3608
0
        }
3609
0
        packed_info.set_remaining_slice_bytes(left_file_bytes);
3610
0
        packed_info.set_ref_cnt(left_file_count);
3611
3612
0
        if (left_file_count == 0) {
3613
0
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3614
0
        }
3615
3616
0
        std::string updated_val;
3617
0
        if (!packed_info.SerializeToString(&updated_val)) {
3618
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
3619
0
                    .tag("instance_id", instance_id_)
3620
0
                    .tag("tablet_id", tablet_id)
3621
0
                    .tag("rowset_id", rowset_id)
3622
0
                    .tag("packed_file_path", packed_file_path);
3623
0
            return -1;
3624
0
        }
3625
3626
0
        update_txn->put(packed_key, updated_val);
3627
0
        err = update_txn->commit();
3628
0
        if (err == TxnErrorCode::TXN_OK) {
3629
0
            LOG_INFO("delete bitmap packed file ref count decremented")
3630
0
                    .tag("instance_id", instance_id_)
3631
0
                    .tag("tablet_id", tablet_id)
3632
0
                    .tag("rowset_id", rowset_id)
3633
0
                    .tag("packed_file_path", packed_file_path)
3634
0
                    .tag("left_file_count", left_file_count);
3635
0
            if (left_file_count == 0) {
3636
0
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3637
0
                    return -1;
3638
0
                }
3639
0
            }
3640
0
            return 0;
3641
0
        }
3642
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
3643
0
            if (attempt >= max_retry_times) {
3644
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
3645
0
                        .tag("instance_id", instance_id_)
3646
0
                        .tag("tablet_id", tablet_id)
3647
0
                        .tag("rowset_id", rowset_id)
3648
0
                        .tag("packed_file_path", packed_file_path)
3649
0
                        .tag("attempt", attempt);
3650
0
                return -1;
3651
0
            }
3652
0
            sleep_for_packed_file_retry();
3653
0
            continue;
3654
0
        }
3655
3656
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
3657
0
                .tag("instance_id", instance_id_)
3658
0
                .tag("tablet_id", tablet_id)
3659
0
                .tag("rowset_id", rowset_id)
3660
0
                .tag("packed_file_path", packed_file_path)
3661
0
                .tag("err", err);
3662
0
        return -1;
3663
0
    }
3664
3665
18.4E
    return -1;
3666
18.4E
}
3667
3668
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
3669
                                                const std::string& packed_key,
3670
7
                                                const cloud::PackedFileInfoPB& packed_info) {
3671
7
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
3672
0
        LOG_WARNING("packed file missing resource id when recycling")
3673
0
                .tag("instance_id", instance_id_)
3674
0
                .tag("packed_file_path", packed_file_path);
3675
0
        return -1;
3676
0
    }
3677
3678
7
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
3679
7
    if (!accessor) {
3680
0
        LOG_WARNING("no accessor available to delete packed file")
3681
0
                .tag("instance_id", instance_id_)
3682
0
                .tag("packed_file_path", packed_file_path)
3683
0
                .tag("resource_id", packed_info.resource_id());
3684
0
        return -1;
3685
0
    }
3686
3687
7
    int del_ret = accessor->delete_file(packed_file_path);
3688
7
    if (del_ret != 0 && del_ret != 1) {
3689
0
        LOG_WARNING("failed to delete packed file")
3690
0
                .tag("instance_id", instance_id_)
3691
0
                .tag("packed_file_path", packed_file_path)
3692
0
                .tag("resource_id", resource_id)
3693
0
                .tag("ret", del_ret);
3694
0
        return -1;
3695
0
    }
3696
7
    if (del_ret == 1) {
3697
0
        LOG_INFO("packed file already removed")
3698
0
                .tag("instance_id", instance_id_)
3699
0
                .tag("packed_file_path", packed_file_path)
3700
0
                .tag("resource_id", resource_id);
3701
7
    } else {
3702
7
        LOG_INFO("deleted packed file")
3703
7
                .tag("instance_id", instance_id_)
3704
7
                .tag("packed_file_path", packed_file_path)
3705
7
                .tag("resource_id", resource_id);
3706
7
    }
3707
3708
7
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
3709
7
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3710
7
        std::unique_ptr<Transaction> del_txn;
3711
7
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
3712
7
        if (err != TxnErrorCode::TXN_OK) {
3713
0
            LOG_WARNING("failed to create txn when removing packed file kv")
3714
0
                    .tag("instance_id", instance_id_)
3715
0
                    .tag("packed_file_path", packed_file_path)
3716
0
                    .tag("attempt", attempt)
3717
0
                    .tag("err", err);
3718
0
            return -1;
3719
0
        }
3720
3721
7
        std::string latest_val;
3722
7
        err = del_txn->get(packed_key, &latest_val);
3723
7
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3724
0
            return 0;
3725
0
        }
3726
7
        if (err != TxnErrorCode::TXN_OK) {
3727
0
            LOG_WARNING("failed to re-read packed file kv before removal")
3728
0
                    .tag("instance_id", instance_id_)
3729
0
                    .tag("packed_file_path", packed_file_path)
3730
0
                    .tag("attempt", attempt)
3731
0
                    .tag("err", err);
3732
0
            return -1;
3733
0
        }
3734
3735
7
        cloud::PackedFileInfoPB latest_info;
3736
7
        if (!latest_info.ParseFromString(latest_val)) {
3737
0
            LOG_WARNING("failed to parse packed file info before removal")
3738
0
                    .tag("instance_id", instance_id_)
3739
0
                    .tag("packed_file_path", packed_file_path)
3740
0
                    .tag("attempt", attempt);
3741
0
            return -1;
3742
0
        }
3743
3744
7
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
3745
7
              latest_info.ref_cnt() == 0)) {
3746
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
3747
0
                    .tag("instance_id", instance_id_)
3748
0
                    .tag("packed_file_path", packed_file_path)
3749
0
                    .tag("attempt", attempt);
3750
0
            return 0;
3751
0
        }
3752
3753
7
        del_txn->remove(packed_key);
3754
7
        err = del_txn->commit();
3755
7
        if (err == TxnErrorCode::TXN_OK) {
3756
7
            LOG_INFO("removed packed file metadata")
3757
7
                    .tag("instance_id", instance_id_)
3758
7
                    .tag("packed_file_path", packed_file_path);
3759
7
            return 0;
3760
7
        }
3761
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
3762
0
            if (attempt >= max_retry_times) {
3763
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
3764
0
                        .tag("instance_id", instance_id_)
3765
0
                        .tag("packed_file_path", packed_file_path)
3766
0
                        .tag("attempt", attempt);
3767
0
                return -1;
3768
0
            }
3769
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
3770
0
                    .tag("instance_id", instance_id_)
3771
0
                    .tag("packed_file_path", packed_file_path)
3772
0
                    .tag("attempt", attempt);
3773
0
            sleep_for_packed_file_retry();
3774
0
            continue;
3775
0
        }
3776
0
        LOG_WARNING("failed to remove packed file kv")
3777
0
                .tag("instance_id", instance_id_)
3778
0
                .tag("packed_file_path", packed_file_path)
3779
0
                .tag("attempt", attempt)
3780
0
                .tag("err", err);
3781
0
        return -1;
3782
0
    }
3783
0
    return -1;
3784
7
}
3785
3786
int InstanceRecycler::delete_rowset_data(
3787
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
3788
98
        RecyclerMetricsContext& metrics_context) {
3789
98
    int ret = 0;
3790
    // resource_id -> file_paths
3791
98
    std::map<std::string, std::vector<std::string>> resource_file_paths;
3792
    // (resource_id, tablet_id, rowset_id)
3793
98
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
3794
98
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
3795
3796
57.1k
    for (const auto& [_, rs] : rowsets) {
3797
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
3798
        // due to aborted schema change.
3799
57.1k
        if (is_formal_rowset) {
3800
3.15k
            std::lock_guard lock(recycled_tablets_mtx_);
3801
3.15k
            if (recycled_tablets_.count(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
3802
                // Tablet has been recycled and this rowset has no packed slices, so file data
3803
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
3804
                // slice info must still run to decrement packed file ref counts.
3805
0
                continue;
3806
0
            }
3807
3.15k
        }
3808
3809
57.1k
        int64_t num_segments = rs.num_segments();
3810
        // Check num_segments before accessor lookup, because empty rowsets
3811
        // (e.g. base compaction output of empty rowsets) may have no resource_id
3812
        // set. Skipping them early avoids a spurious "no such resource id" error
3813
        // that marks the entire batch as failed and prevents txn_remove from
3814
        // cleaning up recycle KV keys.
3815
57.1k
        if (num_segments <= 0) {
3816
0
            metrics_context.total_recycled_num++;
3817
0
            metrics_context.total_recycled_data_size += rs.total_disk_size();
3818
0
            continue;
3819
0
        }
3820
3821
57.1k
        auto it = accessor_map_.find(rs.resource_id());
3822
        // possible if the accessor is not initilized correctly
3823
57.1k
        if (it == accessor_map_.end()) [[unlikely]] {
3824
3.00k
            LOG_WARNING("instance has no such resource id")
3825
3.00k
                    .tag("instance_id", instance_id_)
3826
3.00k
                    .tag("resource_id", rs.resource_id());
3827
3.00k
            ret = -1;
3828
3.00k
            continue;
3829
3.00k
        }
3830
3831
54.1k
        auto& file_paths = resource_file_paths[rs.resource_id()];
3832
54.1k
        const auto& rowset_id = rs.rowset_id_v2();
3833
54.1k
        int64_t tablet_id = rs.tablet_id();
3834
54.1k
        LOG_INFO("recycle rowset merge index size")
3835
54.1k
                .tag("instance_id", instance_id_)
3836
54.1k
                .tag("tablet_id", tablet_id)
3837
54.1k
                .tag("rowset_id", rowset_id)
3838
54.1k
                .tag("merge_index_size", rs.packed_slice_locations_size());
3839
54.1k
        if (decrement_packed_file_ref_counts(rs) != 0) {
3840
0
            ret = -1;
3841
0
            continue;
3842
0
        }
3843
3844
        // Process delete bitmap - check where it's stored.
3845
54.1k
        DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3846
54.1k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3847
54.1k
                                                           &delete_bitmap_storage_type) != 0) {
3848
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3849
0
                    .tag("instance_id", instance_id_)
3850
0
                    .tag("tablet_id", tablet_id)
3851
0
                    .tag("rowset_id", rowset_id);
3852
0
            ret = -1;
3853
0
            continue;
3854
0
        }
3855
54.1k
        if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3856
51.5k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3857
51.5k
        }
3858
3859
        // Process inverted indexes
3860
54.1k
        std::vector<std::pair<int64_t, std::string>> index_ids;
3861
        // default format as v1.
3862
54.1k
        InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
3863
54.1k
        int inverted_index_get_ret = 0;
3864
54.1k
        if (rs.has_tablet_schema()) {
3865
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
3866
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3867
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3868
53.5k
                }
3869
53.5k
            }
3870
26.6k
            if (rs.tablet_schema().has_inverted_index_storage_format()) {
3871
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
3872
26.5k
            }
3873
27.5k
        } else {
3874
27.5k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
3875
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
3876
0
                                "instance_id="
3877
0
                             << instance_id_ << " tablet_id=" << tablet_id
3878
0
                             << " rowset_id=" << rowset_id;
3879
0
                ret = -1;
3880
0
                continue;
3881
0
            }
3882
27.5k
            InvertedIndexInfo index_info;
3883
27.5k
            inverted_index_get_ret =
3884
27.5k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
3885
27.5k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3886
27.5k
                                     &inverted_index_get_ret);
3887
27.5k
            if (inverted_index_get_ret == 0) {
3888
27.0k
                index_format = index_info.first;
3889
27.0k
                index_ids = index_info.second;
3890
27.0k
            } else if (inverted_index_get_ret == 1) {
3891
                // 1. Schema kv not found means tablet has been recycled
3892
                // Maybe some tablet recycle failed by some bugs
3893
                // We need to delete again to double check
3894
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3895
                // because we are uncertain about the inverted index information.
3896
                // If there are inverted indexes, some data might not be deleted,
3897
                // but this is acceptable as we have made our best effort to delete the data.
3898
503
                LOG_INFO(
3899
503
                        "delete rowset data schema kv not found, need to delete again to "
3900
503
                        "double "
3901
503
                        "check")
3902
503
                        .tag("instance_id", instance_id_)
3903
503
                        .tag("tablet_id", tablet_id)
3904
503
                        .tag("rowset", rs.ShortDebugString());
3905
                // Currently index_ids is guaranteed to be empty,
3906
                // but we clear it again here as a safeguard against future code changes
3907
                // that might cause index_ids to no longer be empty
3908
503
                index_format = InvertedIndexStorageFormatPB::V2;
3909
503
                index_ids.clear();
3910
18.4E
            } else {
3911
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
3912
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
3913
18.4E
                ret = -1;
3914
18.4E
                continue;
3915
18.4E
            }
3916
27.5k
        }
3917
54.2k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3918
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3919
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3920
5
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
3921
5
            continue;
3922
5
        }
3923
323k
        for (int64_t i = 0; i < num_segments; ++i) {
3924
269k
            add_file_to_delete_if_not_packed(rs, segment_path(tablet_id, rowset_id, i),
3925
269k
                                             &file_paths);
3926
269k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
3927
536k
                for (const auto& index_id : index_ids) {
3928
536k
                    add_file_to_delete_if_not_packed(
3929
536k
                            rs,
3930
536k
                            inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
3931
536k
                                                   index_id.second),
3932
536k
                            &file_paths);
3933
536k
                }
3934
267k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
3935
                // try to recycle inverted index v2 when get_ret == 1
3936
                // we treat schema not found as if it has a v2 format inverted index
3937
                // to reduce chance of data leakage
3938
2.50k
                if (inverted_index_get_ret == 1) {
3939
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
3940
2.50k
                            .tag("instance_id", instance_id_)
3941
2.50k
                            .tag("inverted index v2 path",
3942
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, i));
3943
2.50k
                }
3944
2.50k
                add_file_to_delete_if_not_packed(
3945
2.50k
                        rs, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
3946
2.50k
            }
3947
269k
        }
3948
54.1k
    }
3949
3950
98
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
3951
98
                                                 "delete_rowset_data",
3952
98
                                                 [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clERKi
Line
Count
Source
3952
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
3952
51
                                                 [](const int& ret) { return ret != 0; });
3953
98
    for (auto& [resource_id, file_paths] : resource_file_paths) {
3954
51
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
3955
51
            DCHECK(accessor_map_.count(*rid))
3956
0
                    << "uninitilized accessor, instance_id=" << instance_id_
3957
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
3958
51
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
3959
51
                                     &accessor_map_);
3960
51
            if (!accessor_map_.contains(*rid)) {
3961
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
3962
0
                        .tag("resource_id", resource_id)
3963
0
                        .tag("instance_id", instance_id_);
3964
0
                return -1;
3965
0
            }
3966
51
            auto& accessor = accessor_map_[*rid];
3967
51
            int ret = accessor->delete_files(*paths);
3968
51
            if (!ret) {
3969
                // deduplication of different files with the same rowset id
3970
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
3971
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
3972
51
                std::set<std::string> deleted_rowset_id;
3973
3974
51
                std::for_each(paths->begin(), paths->end(),
3975
51
                              [&metrics_context, &rowsets, &deleted_rowset_id,
3976
856k
                               this](const std::string& path) {
3977
856k
                                  std::vector<std::string> str;
3978
856k
                                  butil::SplitString(path, '/', &str);
3979
856k
                                  std::string rowset_id;
3980
856k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3981
852k
                                      rowset_id = str.back().substr(0, pos);
3982
852k
                                  } else {
3983
3.10k
                                      if (path.find("packed_file/") != std::string::npos) {
3984
0
                                          return; // packed files do not have rowset_id encoded
3985
0
                                      }
3986
3.10k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3987
3.10k
                                      return;
3988
3.10k
                                  }
3989
852k
                                  auto rs_meta = rowsets.find(rowset_id);
3990
852k
                                  if (rs_meta != rowsets.end() &&
3991
857k
                                      !deleted_rowset_id.contains(rowset_id)) {
3992
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
3993
54.1k
                                      metrics_context.total_recycled_data_size +=
3994
54.1k
                                              rs_meta->second.total_disk_size();
3995
54.1k
                                      segment_metrics_context_.total_recycled_num +=
3996
54.1k
                                              rs_meta->second.num_segments();
3997
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
3998
54.1k
                                              rs_meta->second.total_disk_size();
3999
54.1k
                                      metrics_context.total_recycled_num++;
4000
54.1k
                                  }
4001
852k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
3976
7
                               this](const std::string& path) {
3977
7
                                  std::vector<std::string> str;
3978
7
                                  butil::SplitString(path, '/', &str);
3979
7
                                  std::string rowset_id;
3980
7
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3981
7
                                      rowset_id = str.back().substr(0, pos);
3982
7
                                  } else {
3983
0
                                      if (path.find("packed_file/") != std::string::npos) {
3984
0
                                          return; // packed files do not have rowset_id encoded
3985
0
                                      }
3986
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3987
0
                                      return;
3988
0
                                  }
3989
7
                                  auto rs_meta = rowsets.find(rowset_id);
3990
7
                                  if (rs_meta != rowsets.end() &&
3991
7
                                      !deleted_rowset_id.contains(rowset_id)) {
3992
7
                                      deleted_rowset_id.emplace(rowset_id);
3993
7
                                      metrics_context.total_recycled_data_size +=
3994
7
                                              rs_meta->second.total_disk_size();
3995
7
                                      segment_metrics_context_.total_recycled_num +=
3996
7
                                              rs_meta->second.num_segments();
3997
7
                                      segment_metrics_context_.total_recycled_data_size +=
3998
7
                                              rs_meta->second.total_disk_size();
3999
7
                                      metrics_context.total_recycled_num++;
4000
7
                                  }
4001
7
                              });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
3976
856k
                               this](const std::string& path) {
3977
856k
                                  std::vector<std::string> str;
3978
856k
                                  butil::SplitString(path, '/', &str);
3979
856k
                                  std::string rowset_id;
3980
856k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3981
852k
                                      rowset_id = str.back().substr(0, pos);
3982
852k
                                  } else {
3983
3.10k
                                      if (path.find("packed_file/") != std::string::npos) {
3984
0
                                          return; // packed files do not have rowset_id encoded
3985
0
                                      }
3986
3.10k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3987
3.10k
                                      return;
3988
3.10k
                                  }
3989
852k
                                  auto rs_meta = rowsets.find(rowset_id);
3990
852k
                                  if (rs_meta != rowsets.end() &&
3991
857k
                                      !deleted_rowset_id.contains(rowset_id)) {
3992
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
3993
54.1k
                                      metrics_context.total_recycled_data_size +=
3994
54.1k
                                              rs_meta->second.total_disk_size();
3995
54.1k
                                      segment_metrics_context_.total_recycled_num +=
3996
54.1k
                                              rs_meta->second.num_segments();
3997
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
3998
54.1k
                                              rs_meta->second.total_disk_size();
3999
54.1k
                                      metrics_context.total_recycled_num++;
4000
54.1k
                                  }
4001
852k
                              });
4002
51
            }
4003
51
            return ret;
4004
51
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
3954
5
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
3955
5
            DCHECK(accessor_map_.count(*rid))
3956
0
                    << "uninitilized accessor, instance_id=" << instance_id_
3957
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
3958
5
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
3959
5
                                     &accessor_map_);
3960
5
            if (!accessor_map_.contains(*rid)) {
3961
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
3962
0
                        .tag("resource_id", resource_id)
3963
0
                        .tag("instance_id", instance_id_);
3964
0
                return -1;
3965
0
            }
3966
5
            auto& accessor = accessor_map_[*rid];
3967
5
            int ret = accessor->delete_files(*paths);
3968
5
            if (!ret) {
3969
                // deduplication of different files with the same rowset id
3970
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
3971
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
3972
5
                std::set<std::string> deleted_rowset_id;
3973
3974
5
                std::for_each(paths->begin(), paths->end(),
3975
5
                              [&metrics_context, &rowsets, &deleted_rowset_id,
3976
5
                               this](const std::string& path) {
3977
5
                                  std::vector<std::string> str;
3978
5
                                  butil::SplitString(path, '/', &str);
3979
5
                                  std::string rowset_id;
3980
5
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3981
5
                                      rowset_id = str.back().substr(0, pos);
3982
5
                                  } else {
3983
5
                                      if (path.find("packed_file/") != std::string::npos) {
3984
5
                                          return; // packed files do not have rowset_id encoded
3985
5
                                      }
3986
5
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3987
5
                                      return;
3988
5
                                  }
3989
5
                                  auto rs_meta = rowsets.find(rowset_id);
3990
5
                                  if (rs_meta != rowsets.end() &&
3991
5
                                      !deleted_rowset_id.contains(rowset_id)) {
3992
5
                                      deleted_rowset_id.emplace(rowset_id);
3993
5
                                      metrics_context.total_recycled_data_size +=
3994
5
                                              rs_meta->second.total_disk_size();
3995
5
                                      segment_metrics_context_.total_recycled_num +=
3996
5
                                              rs_meta->second.num_segments();
3997
5
                                      segment_metrics_context_.total_recycled_data_size +=
3998
5
                                              rs_meta->second.total_disk_size();
3999
5
                                      metrics_context.total_recycled_num++;
4000
5
                                  }
4001
5
                              });
4002
5
            }
4003
5
            return ret;
4004
5
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
3954
46
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
3955
46
            DCHECK(accessor_map_.count(*rid))
3956
0
                    << "uninitilized accessor, instance_id=" << instance_id_
3957
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
3958
46
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
3959
46
                                     &accessor_map_);
3960
46
            if (!accessor_map_.contains(*rid)) {
3961
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
3962
0
                        .tag("resource_id", resource_id)
3963
0
                        .tag("instance_id", instance_id_);
3964
0
                return -1;
3965
0
            }
3966
46
            auto& accessor = accessor_map_[*rid];
3967
46
            int ret = accessor->delete_files(*paths);
3968
46
            if (!ret) {
3969
                // deduplication of different files with the same rowset id
3970
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
3971
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
3972
46
                std::set<std::string> deleted_rowset_id;
3973
3974
46
                std::for_each(paths->begin(), paths->end(),
3975
46
                              [&metrics_context, &rowsets, &deleted_rowset_id,
3976
46
                               this](const std::string& path) {
3977
46
                                  std::vector<std::string> str;
3978
46
                                  butil::SplitString(path, '/', &str);
3979
46
                                  std::string rowset_id;
3980
46
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3981
46
                                      rowset_id = str.back().substr(0, pos);
3982
46
                                  } else {
3983
46
                                      if (path.find("packed_file/") != std::string::npos) {
3984
46
                                          return; // packed files do not have rowset_id encoded
3985
46
                                      }
3986
46
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3987
46
                                      return;
3988
46
                                  }
3989
46
                                  auto rs_meta = rowsets.find(rowset_id);
3990
46
                                  if (rs_meta != rowsets.end() &&
3991
46
                                      !deleted_rowset_id.contains(rowset_id)) {
3992
46
                                      deleted_rowset_id.emplace(rowset_id);
3993
46
                                      metrics_context.total_recycled_data_size +=
3994
46
                                              rs_meta->second.total_disk_size();
3995
46
                                      segment_metrics_context_.total_recycled_num +=
3996
46
                                              rs_meta->second.num_segments();
3997
46
                                      segment_metrics_context_.total_recycled_data_size +=
3998
46
                                              rs_meta->second.total_disk_size();
3999
46
                                      metrics_context.total_recycled_num++;
4000
46
                                  }
4001
46
                              });
4002
46
            }
4003
46
            return ret;
4004
46
        });
4005
51
    }
4006
98
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
4007
5
        LOG_INFO(
4008
5
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
4009
5
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
4010
5
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
4011
5
        concurrent_delete_executor.add([&]() -> int {
4012
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4013
5
            if (!ret) {
4014
5
                auto rs = rowsets.at(rowset_id);
4015
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4016
5
                metrics_context.total_recycled_num++;
4017
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4018
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4019
5
            }
4020
5
            return ret;
4021
5
        });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_2clEv
Line
Count
Source
4011
5
        concurrent_delete_executor.add([&]() -> int {
4012
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4013
5
            if (!ret) {
4014
5
                auto rs = rowsets.at(rowset_id);
4015
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4016
5
                metrics_context.total_recycled_num++;
4017
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4018
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4019
5
            }
4020
5
            return ret;
4021
5
        });
4022
5
    }
4023
4024
98
    bool finished = true;
4025
98
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4026
98
    for (int r : rets) {
4027
56
        if (r != 0) {
4028
0
            ret = -1;
4029
0
            break;
4030
0
        }
4031
56
    }
4032
98
    ret = finished ? ret : -1;
4033
98
    return ret;
4034
98
}
4035
4036
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
4037
3.30k
                                         const std::string& rowset_id) {
4038
3.30k
    auto it = accessor_map_.find(resource_id);
4039
3.30k
    if (it == accessor_map_.end()) {
4040
400
        LOG_WARNING("instance has no such resource id")
4041
400
                .tag("instance_id", instance_id_)
4042
400
                .tag("resource_id", resource_id)
4043
400
                .tag("tablet_id", tablet_id)
4044
400
                .tag("rowset_id", rowset_id);
4045
400
        return -1;
4046
400
    }
4047
2.90k
    auto& accessor = it->second;
4048
2.90k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
4049
3.30k
}
4050
4051
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
4052
4
    if (key.empty()) {
4053
0
        return false;
4054
0
    }
4055
4
    std::string_view key_view = key;
4056
4
    key_view.remove_prefix(1); // remove keyspace prefix
4057
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
4058
4
    if (decode_key(&key_view, &decoded) != 0) {
4059
0
        return false;
4060
0
    }
4061
4
    if (decoded.size() < 4) {
4062
0
        return false;
4063
0
    }
4064
4
    try {
4065
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
4066
4
    } catch (const std::bad_variant_access&) {
4067
0
        return false;
4068
0
    }
4069
4
    return true;
4070
4
}
4071
4072
14
int InstanceRecycler::recycle_packed_files() {
4073
14
    const std::string task_name = "recycle_packed_files";
4074
14
    auto start_tp = steady_clock::now();
4075
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
4076
14
    int ret = 0;
4077
14
    PackedFileRecycleStats stats;
4078
4079
14
    register_recycle_task(task_name, start_time);
4080
14
    DORIS_CLOUD_DEFER {
4081
14
        unregister_recycle_task(task_name);
4082
14
        int64_t cost =
4083
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4084
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4085
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4086
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4087
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4088
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4089
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4090
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4091
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4092
14
                                                             stats.bytes_object_deleted);
4093
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4094
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4095
14
                .tag("instance_id", instance_id_)
4096
14
                .tag("num_scanned", stats.num_scanned)
4097
14
                .tag("num_corrected", stats.num_corrected)
4098
14
                .tag("num_deleted", stats.num_deleted)
4099
14
                .tag("num_failed", stats.num_failed)
4100
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4101
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4102
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4103
14
                .tag("bytes_deleted", stats.bytes_deleted)
4104
14
                .tag("ret", ret);
4105
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
4080
14
    DORIS_CLOUD_DEFER {
4081
14
        unregister_recycle_task(task_name);
4082
14
        int64_t cost =
4083
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4084
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4085
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4086
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4087
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4088
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4089
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4090
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4091
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4092
14
                                                             stats.bytes_object_deleted);
4093
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4094
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4095
14
                .tag("instance_id", instance_id_)
4096
14
                .tag("num_scanned", stats.num_scanned)
4097
14
                .tag("num_corrected", stats.num_corrected)
4098
14
                .tag("num_deleted", stats.num_deleted)
4099
14
                .tag("num_failed", stats.num_failed)
4100
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4101
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4102
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4103
14
                .tag("bytes_deleted", stats.bytes_deleted)
4104
14
                .tag("ret", ret);
4105
14
    };
4106
4107
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4108
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4109
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4110
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
4107
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4108
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4109
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4110
4
    };
4111
4112
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
4113
4114
14
    std::string begin = packed_file_key({instance_id_, ""});
4115
14
    std::string end = packed_file_key({instance_id_, "\xff"});
4116
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
4117
0
        ret = -1;
4118
0
    }
4119
4120
14
    return ret;
4121
14
}
4122
4123
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
4124
                                                  RecyclerMetricsContext& metrics_context,
4125
0
                                                  int64_t partition_id, bool is_empty_tablet) {
4126
0
    std::string tablet_key_begin, tablet_key_end;
4127
4128
0
    if (partition_id > 0) {
4129
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
4130
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
4131
0
    } else {
4132
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
4133
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
4134
0
    }
4135
    // for calculate the total num or bytes of recyled objects
4136
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
4137
0
                                                          std::string_view v) -> int {
4138
0
        doris::TabletMetaCloudPB tablet_meta_pb;
4139
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
4140
0
            return 0;
4141
0
        }
4142
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
4143
4144
0
        if (config::enable_recycler_check_lazy_txn_finished &&
4145
0
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
4146
0
            return 0;
4147
0
        }
4148
4149
0
        if (!is_empty_tablet) {
4150
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
4151
0
                return 0;
4152
0
            }
4153
0
            tablet_metrics_context_.total_need_recycle_num++;
4154
0
        }
4155
0
        return 0;
4156
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_
4157
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
4158
0
    metrics_context.report(true);
4159
0
    tablet_metrics_context_.report(true);
4160
0
    segment_metrics_context_.report(true);
4161
0
    return ret;
4162
0
}
4163
4164
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
4165
0
                                                 RecyclerMetricsContext& metrics_context) {
4166
0
    int ret = 0;
4167
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
4168
0
    std::unique_ptr<Transaction> txn;
4169
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4170
0
        LOG_WARNING("failed to recycle tablet ")
4171
0
                .tag("tablet id", tablet_id)
4172
0
                .tag("instance_id", instance_id_)
4173
0
                .tag("reason", "failed to create txn");
4174
0
        ret = -1;
4175
0
    }
4176
0
    GetRowsetResponse resp;
4177
0
    std::string msg;
4178
0
    MetaServiceCode code = MetaServiceCode::OK;
4179
    // get rowsets in tablet
4180
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4181
0
                        tablet_id, code, msg, &resp);
4182
0
    if (code != MetaServiceCode::OK) {
4183
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4184
0
                .tag("tablet id", tablet_id)
4185
0
                .tag("msg", msg)
4186
0
                .tag("code", code)
4187
0
                .tag("instance id", instance_id_);
4188
0
        ret = -1;
4189
0
    }
4190
0
    for (const auto& rs_meta : resp.rowset_meta()) {
4191
        /*
4192
        * For compatibility, we skip the loop for [0-1] here.
4193
        * The purpose of this loop is to delete object files,
4194
        * and since [0-1] only has meta and doesn't have object files,
4195
        * skipping it doesn't affect system correctness.
4196
        *
4197
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
4198
        * would return error -1 directly, causing the recycle operation to fail.
4199
        *
4200
        * [0-1] doesn't have resource id is a bug.
4201
        * In the future, we will fix this problem, after that,
4202
        * we can remove this if statement.
4203
        *
4204
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
4205
        */
4206
4207
0
        if (rs_meta.end_version() == 1) {
4208
            // Assert that [0-1] has no resource_id to make sure
4209
            // this if statement will not be forgetted to remove
4210
            // when the resource id bug is fixed
4211
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4212
0
            continue;
4213
0
        }
4214
0
        if (!rs_meta.has_resource_id()) {
4215
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4216
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4217
0
                    .tag("instance_id", instance_id_)
4218
0
                    .tag("tablet_id", tablet_id);
4219
0
            continue;
4220
0
        }
4221
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4222
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4223
        // possible if the accessor is not initilized correctly
4224
0
        if (it == accessor_map_.end()) [[unlikely]] {
4225
0
            LOG_WARNING(
4226
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4227
0
                    "recycle process")
4228
0
                    .tag("tablet id", tablet_id)
4229
0
                    .tag("instance_id", instance_id_)
4230
0
                    .tag("resource_id", rs_meta.resource_id())
4231
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4232
0
            continue;
4233
0
        }
4234
4235
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
4236
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4237
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4238
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
4239
0
    }
4240
0
    return ret;
4241
0
}
4242
4243
4.26k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
4244
4.26k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
4245
4.26k
            .tag("instance_id", instance_id_)
4246
4.26k
            .tag("tablet_id", tablet_id);
4247
4248
4.26k
    if (should_recycle_versioned_keys()) {
4249
14
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
4250
14
        if (ret != 0) {
4251
0
            return ret;
4252
0
        }
4253
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
4254
        // during the recycle_versioned_tablet process.
4255
        //
4256
        // .. And remove restore job rowsets of this tablet too
4257
14
    }
4258
4259
4.26k
    int ret = 0;
4260
4.26k
    auto start_time = steady_clock::now();
4261
4262
4.26k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4263
4264
    // collect resource ids
4265
259
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4266
259
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4267
259
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4268
259
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4269
259
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
4270
259
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
4271
4272
259
    std::set<std::string> resource_ids;
4273
259
    int64_t recycle_rowsets_number = 0;
4274
259
    int64_t recycle_segments_number = 0;
4275
259
    int64_t recycle_rowsets_data_size = 0;
4276
259
    int64_t recycle_rowsets_index_size = 0;
4277
259
    int64_t recycle_restore_job_rowsets_number = 0;
4278
259
    int64_t recycle_restore_job_segments_number = 0;
4279
259
    int64_t recycle_restore_job_rowsets_data_size = 0;
4280
259
    int64_t recycle_restore_job_rowsets_index_size = 0;
4281
259
    int64_t max_rowset_version = 0;
4282
259
    int64_t min_rowset_creation_time = INT64_MAX;
4283
259
    int64_t max_rowset_creation_time = 0;
4284
259
    int64_t min_rowset_expiration_time = INT64_MAX;
4285
259
    int64_t max_rowset_expiration_time = 0;
4286
4287
259
    DORIS_CLOUD_DEFER {
4288
259
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4289
259
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4290
259
                .tag("instance_id", instance_id_)
4291
259
                .tag("tablet_id", tablet_id)
4292
259
                .tag("recycle rowsets number", recycle_rowsets_number)
4293
259
                .tag("recycle segments number", recycle_segments_number)
4294
259
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4295
259
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4296
259
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4297
259
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4298
259
                .tag("all restore job rowsets recycle data size",
4299
259
                     recycle_restore_job_rowsets_data_size)
4300
259
                .tag("all restore job rowsets recycle index size",
4301
259
                     recycle_restore_job_rowsets_index_size)
4302
259
                .tag("max rowset version", max_rowset_version)
4303
259
                .tag("min rowset creation time", min_rowset_creation_time)
4304
259
                .tag("max rowset creation time", max_rowset_creation_time)
4305
259
                .tag("min rowset expiration time", min_rowset_expiration_time)
4306
259
                .tag("max rowset expiration time", max_rowset_expiration_time)
4307
259
                .tag("task type", metrics_context.operation_type)
4308
259
                .tag("ret", ret);
4309
259
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4287
259
    DORIS_CLOUD_DEFER {
4288
259
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4289
259
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4290
259
                .tag("instance_id", instance_id_)
4291
259
                .tag("tablet_id", tablet_id)
4292
259
                .tag("recycle rowsets number", recycle_rowsets_number)
4293
259
                .tag("recycle segments number", recycle_segments_number)
4294
259
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4295
259
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4296
259
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4297
259
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4298
259
                .tag("all restore job rowsets recycle data size",
4299
259
                     recycle_restore_job_rowsets_data_size)
4300
259
                .tag("all restore job rowsets recycle index size",
4301
259
                     recycle_restore_job_rowsets_index_size)
4302
259
                .tag("max rowset version", max_rowset_version)
4303
259
                .tag("min rowset creation time", min_rowset_creation_time)
4304
259
                .tag("max rowset creation time", max_rowset_creation_time)
4305
259
                .tag("min rowset expiration time", min_rowset_expiration_time)
4306
259
                .tag("max rowset expiration time", max_rowset_expiration_time)
4307
259
                .tag("task type", metrics_context.operation_type)
4308
259
                .tag("ret", ret);
4309
259
    };
4310
4311
259
    std::unique_ptr<Transaction> txn;
4312
259
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4313
0
        LOG_WARNING("failed to recycle tablet ")
4314
0
                .tag("tablet id", tablet_id)
4315
0
                .tag("instance_id", instance_id_)
4316
0
                .tag("reason", "failed to create txn");
4317
0
        ret = -1;
4318
0
    }
4319
259
    GetRowsetResponse resp;
4320
259
    std::string msg;
4321
259
    MetaServiceCode code = MetaServiceCode::OK;
4322
    // get rowsets in tablet
4323
259
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4324
259
                        tablet_id, code, msg, &resp);
4325
259
    if (code != MetaServiceCode::OK) {
4326
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4327
0
                .tag("tablet id", tablet_id)
4328
0
                .tag("msg", msg)
4329
0
                .tag("code", code)
4330
0
                .tag("instance id", instance_id_);
4331
0
        ret = -1;
4332
0
    }
4333
259
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
4334
4335
2.55k
    for (const auto& rs_meta : resp.rowset_meta()) {
4336
        // Empty rowsets have no segment objects to delete, so they do not need a resource id.
4337
2.55k
        if (rs_meta.num_segments() <= 0) {
4338
1
            LOG_INFO("rowset meta has no segments, skip this rowset")
4339
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
4340
1
                    .tag("instance_id", instance_id_)
4341
1
                    .tag("tablet_id", tablet_id);
4342
1
            recycle_rowsets_number += 1;
4343
1
            continue;
4344
1
        }
4345
2.54k
        if (!rs_meta.has_resource_id() || rs_meta.resource_id().empty()) {
4346
1
            LOG_WARNING("rowset meta has a missing or empty resource id, impossible!")
4347
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
4348
1
                    .tag("instance_id", instance_id_)
4349
1
                    .tag("tablet_id", tablet_id);
4350
1
            return -1;
4351
1
        }
4352
2.54k
        DCHECK(rs_meta.has_resource_id() && !rs_meta.resource_id().empty())
4353
2
                << "rs_meta" << rs_meta.ShortDebugString();
4354
2.54k
        auto it = accessor_map_.find(rs_meta.resource_id());
4355
        // possible if the accessor is not initilized correctly
4356
2.54k
        if (it == accessor_map_.end()) [[unlikely]] {
4357
1
            LOG_WARNING(
4358
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4359
1
                    "recycle process")
4360
1
                    .tag("tablet id", tablet_id)
4361
1
                    .tag("instance_id", instance_id_)
4362
1
                    .tag("resource_id", rs_meta.resource_id())
4363
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4364
1
            return -1;
4365
1
        }
4366
2.54k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4367
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
4368
0
                    .tag("instance_id", instance_id_)
4369
0
                    .tag("tablet_id", tablet_id)
4370
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4371
0
            return -1;
4372
0
        }
4373
2.54k
        recycle_rowsets_number += 1;
4374
2.54k
        recycle_segments_number += rs_meta.num_segments();
4375
2.54k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4376
2.54k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4377
2.54k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4378
2.54k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4379
2.54k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4380
2.54k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4381
2.54k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4382
2.54k
        resource_ids.emplace(rs_meta.resource_id());
4383
2.54k
    }
4384
4385
    // get restore job rowset in tablet
4386
257
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
4387
257
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
4388
257
    if (code != MetaServiceCode::OK) {
4389
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
4390
0
                .tag("tablet id", tablet_id)
4391
0
                .tag("msg", msg)
4392
0
                .tag("code", code)
4393
0
                .tag("instance id", instance_id_);
4394
0
        return -1;
4395
0
    }
4396
4397
257
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
4398
0
        if (!rs_meta.has_resource_id()) {
4399
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4400
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4401
0
                    .tag("instance_id", instance_id_)
4402
0
                    .tag("tablet_id", tablet_id);
4403
0
            return -1;
4404
0
        }
4405
4406
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4407
        // possible if the accessor is not initilized correctly
4408
0
        if (it == accessor_map_.end()) [[unlikely]] {
4409
0
            LOG_WARNING(
4410
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4411
0
                    "recycle process")
4412
0
                    .tag("tablet id", tablet_id)
4413
0
                    .tag("instance_id", instance_id_)
4414
0
                    .tag("resource_id", rs_meta.resource_id())
4415
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4416
0
            return -1;
4417
0
        }
4418
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4419
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
4420
0
                    .tag("instance_id", instance_id_)
4421
0
                    .tag("tablet_id", tablet_id)
4422
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4423
0
            return -1;
4424
0
        }
4425
0
        recycle_restore_job_rowsets_number += 1;
4426
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
4427
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
4428
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
4429
0
        resource_ids.emplace(rs_meta.resource_id());
4430
0
    }
4431
4432
257
    LOG_INFO("recycle tablet start to delete object")
4433
257
            .tag("instance id", instance_id_)
4434
257
            .tag("tablet id", tablet_id)
4435
257
            .tag("recycle tablet resource ids are",
4436
257
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
4437
257
                                 [](std::string rs_id, const auto& it) {
4438
216
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4439
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
4437
216
                                 [](std::string rs_id, const auto& it) {
4438
216
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4439
216
                                 }));
4440
4441
257
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
4442
257
            _thread_pool_group.s3_producer_pool,
4443
257
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4444
257
            [](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
4444
207
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
4445
4446
    // delete all rowset data in this tablet
4447
    // ATTN: there may be data leak if not all accessor initilized successfully
4448
    //       partial data deleted if the tablet is stored cross-storage vault
4449
    //       vault id is not attached to TabletMeta...
4450
257
    for (const auto& resource_id : resource_ids) {
4451
216
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
4452
216
        concurrent_delete_executor.add(
4453
216
                [&, rs_id = resource_id,
4454
216
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4455
216
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4456
216
                    if (res != 0) {
4457
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4458
3
                                     << " path=" << accessor_ptr->uri()
4459
3
                                     << " task type=" << metrics_context.operation_type;
4460
3
                        return std::make_pair(-1, rs_id);
4461
3
                    }
4462
213
                    return std::make_pair(0, rs_id);
4463
216
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
4454
216
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4455
216
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4456
216
                    if (res != 0) {
4457
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4458
3
                                     << " path=" << accessor_ptr->uri()
4459
3
                                     << " task type=" << metrics_context.operation_type;
4460
3
                        return std::make_pair(-1, rs_id);
4461
3
                    }
4462
213
                    return std::make_pair(0, rs_id);
4463
216
                });
4464
216
    }
4465
4466
257
    bool finished = true;
4467
257
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
4468
257
    for (auto& r : rets) {
4469
216
        if (r.first != 0) {
4470
3
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
4471
3
            ret = -1;
4472
3
        }
4473
216
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
4474
216
    }
4475
257
    ret = finished ? ret : -1;
4476
4477
257
    if (ret != 0) { // failed recycle tablet data
4478
3
        LOG_WARNING("ret!=0")
4479
3
                .tag("finished", finished)
4480
3
                .tag("ret", ret)
4481
3
                .tag("instance_id", instance_id_)
4482
3
                .tag("tablet_id", tablet_id);
4483
3
        return ret;
4484
3
    }
4485
4486
254
    tablet_metrics_context_.total_recycled_data_size +=
4487
254
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4488
254
    tablet_metrics_context_.total_recycled_num += 1;
4489
254
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
4490
254
    segment_metrics_context_.total_recycled_data_size +=
4491
254
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4492
254
    metrics_context.total_recycled_data_size +=
4493
254
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4494
254
    tablet_metrics_context_.report();
4495
254
    segment_metrics_context_.report();
4496
254
    metrics_context.report();
4497
4498
254
    txn.reset();
4499
254
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4500
0
        LOG_WARNING("failed to recycle tablet ")
4501
0
                .tag("tablet id", tablet_id)
4502
0
                .tag("instance_id", instance_id_)
4503
0
                .tag("reason", "failed to create txn");
4504
0
        ret = -1;
4505
0
    }
4506
    // delete all rowset kv in this tablet
4507
254
    txn->remove(rs_key0, rs_key1);
4508
254
    txn->remove(recyc_rs_key0, recyc_rs_key1);
4509
254
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
4510
4511
    // remove delete bitmap for MoW table
4512
254
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
4513
254
    txn->remove(pending_key);
4514
254
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
4515
254
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
4516
254
    txn->remove(delete_bitmap_start, delete_bitmap_end);
4517
4518
254
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
4519
254
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
4520
254
    txn->remove(dbm_start_key, dbm_end_key);
4521
254
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
4522
254
              << " end=" << hex(dbm_end_key);
4523
4524
254
    TxnErrorCode err = txn->commit();
4525
254
    if (err != TxnErrorCode::TXN_OK) {
4526
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
4527
0
        ret = -1;
4528
0
    }
4529
4530
254
    if (ret == 0) {
4531
        // All object files under tablet have been deleted
4532
254
        std::lock_guard lock(recycled_tablets_mtx_);
4533
254
        recycled_tablets_.insert(tablet_id);
4534
254
    }
4535
4536
254
    return ret;
4537
257
}
4538
4539
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
4540
14
                                               RecyclerMetricsContext& metrics_context) {
4541
14
    int ret = 0;
4542
14
    auto start_time = steady_clock::now();
4543
4544
14
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4545
4546
    // collect resource ids
4547
11
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4548
11
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4549
11
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4550
11
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4551
4552
11
    int64_t recycle_rowsets_number = 0;
4553
11
    int64_t recycle_segments_number = 0;
4554
11
    int64_t recycle_rowsets_data_size = 0;
4555
11
    int64_t recycle_rowsets_index_size = 0;
4556
11
    int64_t max_rowset_version = 0;
4557
11
    int64_t min_rowset_creation_time = INT64_MAX;
4558
11
    int64_t max_rowset_creation_time = 0;
4559
11
    int64_t min_rowset_expiration_time = INT64_MAX;
4560
11
    int64_t max_rowset_expiration_time = 0;
4561
4562
11
    DORIS_CLOUD_DEFER {
4563
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4564
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4565
11
                .tag("instance_id", instance_id_)
4566
11
                .tag("tablet_id", tablet_id)
4567
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4568
11
                .tag("recycle segments number", recycle_segments_number)
4569
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4570
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4571
11
                .tag("max rowset version", max_rowset_version)
4572
11
                .tag("min rowset creation time", min_rowset_creation_time)
4573
11
                .tag("max rowset creation time", max_rowset_creation_time)
4574
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4575
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4576
11
                .tag("ret", ret);
4577
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4562
11
    DORIS_CLOUD_DEFER {
4563
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4564
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4565
11
                .tag("instance_id", instance_id_)
4566
11
                .tag("tablet_id", tablet_id)
4567
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4568
11
                .tag("recycle segments number", recycle_segments_number)
4569
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4570
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4571
11
                .tag("max rowset version", max_rowset_version)
4572
11
                .tag("min rowset creation time", min_rowset_creation_time)
4573
11
                .tag("max rowset creation time", max_rowset_creation_time)
4574
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4575
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4576
11
                .tag("ret", ret);
4577
11
    };
4578
4579
11
    std::unique_ptr<Transaction> txn;
4580
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4581
0
        LOG_WARNING("failed to recycle tablet ")
4582
0
                .tag("tablet id", tablet_id)
4583
0
                .tag("instance_id", instance_id_)
4584
0
                .tag("reason", "failed to create txn");
4585
0
        ret = -1;
4586
0
    }
4587
4588
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
4589
    // by the related operation logs.
4590
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
4591
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
4592
11
    MetaReader meta_reader(instance_id_);
4593
11
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
4594
11
    if (err == TxnErrorCode::TXN_OK) {
4595
11
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
4596
11
    }
4597
11
    if (err != TxnErrorCode::TXN_OK) {
4598
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4599
0
                .tag("tablet id", tablet_id)
4600
0
                .tag("err", err)
4601
0
                .tag("instance id", instance_id_);
4602
0
        ret = -1;
4603
0
    }
4604
4605
11
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
4606
11
             load_rowset_metas.size(), compact_rowset_metas.size())
4607
11
            .tag("instance_id", instance_id_)
4608
11
            .tag("tablet_id", tablet_id);
4609
4610
11
    SyncExecutor<int> concurrent_delete_executor(
4611
11
            _thread_pool_group.s3_producer_pool,
4612
11
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4613
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
4614
4615
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
4616
60
        recycle_rowsets_number += 1;
4617
60
        recycle_segments_number += rs_meta.num_segments();
4618
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4619
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4620
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4621
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4622
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4623
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4624
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4625
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
4615
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
4616
60
        recycle_rowsets_number += 1;
4617
60
        recycle_segments_number += rs_meta.num_segments();
4618
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4619
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4620
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4621
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4622
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4623
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4624
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4625
60
    };
4626
4627
11
    std::vector<RowsetDeleteTask> all_tasks;
4628
60
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
4629
60
        update_rowset_stats(rs_meta);
4630
        // Version 0-1 rowset has no resource_id and no actual data files,
4631
        // but still needs ref_count key cleanup, so we add it to all_tasks.
4632
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
4633
60
        RowsetDeleteTask task;
4634
60
        task.rowset_meta = rs_meta;
4635
60
        task.versioned_rowset_key =
4636
60
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
4637
60
        task.non_versioned_rowset_key =
4638
60
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
4639
60
        task.versionstamp = versionstamp;
4640
60
        all_tasks.push_back(std::move(task));
4641
60
    }
4642
4643
11
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
4644
0
        update_rowset_stats(rs_meta);
4645
        // Version 0-1 rowset has no resource_id and no actual data files,
4646
        // but still needs ref_count key cleanup, so we add it to all_tasks.
4647
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
4648
0
        RowsetDeleteTask task;
4649
0
        task.rowset_meta = rs_meta;
4650
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
4651
0
                {instance_id_, tablet_id, rs_meta.end_version()});
4652
0
        task.non_versioned_rowset_key =
4653
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
4654
0
        task.versionstamp = versionstamp;
4655
0
        all_tasks.push_back(std::move(task));
4656
0
    }
4657
4658
11
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
4659
0
        RecycleRowsetPB recycle_rowset;
4660
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
4661
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4662
0
            return -1;
4663
0
        }
4664
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
4665
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
4666
                // in old version, keep this key-value pair and it needs to be checked manually
4667
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4668
0
                return -1;
4669
0
            }
4670
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
4671
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
4672
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
4673
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
4674
0
                return -1;
4675
0
            }
4676
            // decode rowset_id
4677
0
            auto k1 = k;
4678
0
            k1.remove_prefix(1);
4679
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
4680
0
            decode_key(&k1, &out);
4681
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
4682
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
4683
0
            LOG_INFO("delete old-version rowset data")
4684
0
                    .tag("instance_id", instance_id_)
4685
0
                    .tag("tablet_id", tablet_id)
4686
0
                    .tag("rowset_id", rowset_id);
4687
4688
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
4689
            // so we must use prefix deletion directly instead of batch delete.
4690
0
            concurrent_delete_executor.add(
4691
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
4692
                        // delete by prefix, the recycle rowset key will be deleted by range later.
4693
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
4694
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
4695
0
        } else {
4696
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
4697
            // Version 0-1 rowset has no resource_id and no actual data files,
4698
            // but still needs ref_count key cleanup, so we add it to all_tasks.
4699
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
4700
0
            RowsetDeleteTask task;
4701
0
            task.rowset_meta = rowset_meta;
4702
0
            task.recycle_rowset_key = k;
4703
0
            all_tasks.push_back(std::move(task));
4704
0
        }
4705
0
        return 0;
4706
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_
4707
4708
11
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
4709
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
4710
0
                .tag("tablet id", tablet_id)
4711
0
                .tag("instance_id", instance_id_)
4712
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
4713
0
        ret = -1;
4714
0
    }
4715
4716
    // Phase 1: Classify tasks by ref_count
4717
11
    std::vector<RowsetDeleteTask> batch_delete_tasks;
4718
60
    for (auto& task : all_tasks) {
4719
60
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
4720
60
        if (classify_ret < 0) {
4721
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
4722
0
                    .tag("instance_id", instance_id_)
4723
0
                    .tag("tablet_id", tablet_id)
4724
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
4725
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
4726
0
                return recycle_rowset_meta_and_data(t);
4727
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_4clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_4clEv
4728
0
        }
4729
60
    }
4730
4731
11
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
4732
4733
11
    LOG_INFO("batch delete plan created")
4734
11
            .tag("instance_id", instance_id_)
4735
11
            .tag("tablet_id", tablet_id)
4736
11
            .tag("plan_count", batch_delete_tasks.size());
4737
4738
    // Phase 2: Execute batch delete using existing delete_rowset_data
4739
11
    if (!batch_delete_tasks.empty()) {
4740
10
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
4741
49
        for (const auto& task : batch_delete_tasks) {
4742
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
4743
49
            if (task.rowset_meta.resource_id().empty()) {
4744
10
                LOG_INFO("skip rowset with empty resource_id in batch delete")
4745
10
                        .tag("instance_id", instance_id_)
4746
10
                        .tag("tablet_id", tablet_id)
4747
10
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
4748
10
                continue;
4749
10
            }
4750
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
4751
39
        }
4752
4753
        // Only call delete_rowset_data if there are rowsets with actual data to delete
4754
10
        bool delete_success = true;
4755
10
        if (!rowsets_to_delete.empty()) {
4756
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
4757
9
                                                         "batch_delete_versioned_tablet");
4758
9
            int delete_ret = delete_rowset_data(
4759
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
4760
9
            if (delete_ret != 0) {
4761
0
                LOG_WARNING("batch delete execution failed")
4762
0
                        .tag("instance_id", instance_id_)
4763
0
                        .tag("tablet_id", tablet_id);
4764
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
4765
0
                ret = -1;
4766
0
                delete_success = false;
4767
0
            }
4768
9
        }
4769
4770
        // Phase 3: Only cleanup metadata if data deletion succeeded.
4771
        // If deletion failed, keep recycle_rowset_key so next round will retry.
4772
10
        if (delete_success) {
4773
10
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
4774
10
            if (cleanup_ret != 0) {
4775
0
                LOG_WARNING("batch delete cleanup failed")
4776
0
                        .tag("instance_id", instance_id_)
4777
0
                        .tag("tablet_id", tablet_id);
4778
0
                ret = -1;
4779
0
            }
4780
10
        }
4781
10
    }
4782
4783
    // Always wait for fallback tasks to complete before returning
4784
11
    bool finished = true;
4785
11
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4786
11
    for (int r : rets) {
4787
0
        if (r != 0) {
4788
0
            ret = -1;
4789
0
        }
4790
0
    }
4791
4792
11
    ret = finished ? ret : -1;
4793
4794
11
    if (ret != 0) { // failed recycle tablet data
4795
0
        LOG_WARNING("recycle versioned tablet failed")
4796
0
                .tag("finished", finished)
4797
0
                .tag("ret", ret)
4798
0
                .tag("instance_id", instance_id_)
4799
0
                .tag("tablet_id", tablet_id);
4800
0
        return ret;
4801
0
    }
4802
4803
11
    tablet_metrics_context_.total_recycled_data_size +=
4804
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4805
11
    tablet_metrics_context_.total_recycled_num += 1;
4806
11
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
4807
11
    segment_metrics_context_.total_recycled_data_size +=
4808
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4809
11
    metrics_context.total_recycled_data_size +=
4810
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4811
11
    tablet_metrics_context_.report();
4812
11
    segment_metrics_context_.report();
4813
11
    metrics_context.report();
4814
4815
11
    txn.reset();
4816
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4817
0
        LOG_WARNING("failed to recycle tablet ")
4818
0
                .tag("tablet id", tablet_id)
4819
0
                .tag("instance_id", instance_id_)
4820
0
                .tag("reason", "failed to create txn");
4821
0
        ret = -1;
4822
0
    }
4823
    // delete all rowset kv in this tablet
4824
11
    txn->remove(rs_key0, rs_key1);
4825
11
    txn->remove(recyc_rs_key0, recyc_rs_key1);
4826
4827
    // remove delete bitmap for MoW table
4828
11
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
4829
11
    txn->remove(pending_key);
4830
11
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
4831
11
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
4832
11
    txn->remove(delete_bitmap_start, delete_bitmap_end);
4833
4834
11
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
4835
11
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
4836
11
    txn->remove(dbm_start_key, dbm_end_key);
4837
11
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
4838
11
              << " end=" << hex(dbm_end_key);
4839
4840
11
    std::string versioned_idx_key = versioned::tablet_index_key({instance_id_, tablet_id});
4841
11
    std::string tablet_index_val;
4842
11
    err = txn->get(versioned_idx_key, &tablet_index_val);
4843
11
    if (err != TxnErrorCode::TXN_KEY_NOT_FOUND && err != TxnErrorCode::TXN_OK) {
4844
0
        LOG_WARNING("failed to get tablet index kv")
4845
0
                .tag("instance_id", instance_id_)
4846
0
                .tag("tablet_id", tablet_id)
4847
0
                .tag("err", err);
4848
0
        ret = -1;
4849
11
    } else if (err == TxnErrorCode::TXN_OK) {
4850
        // If the tablet index kv exists, we need to delete it
4851
10
        TabletIndexPB tablet_index_pb;
4852
10
        if (!tablet_index_pb.ParseFromString(tablet_index_val)) {
4853
0
            LOG_WARNING("failed to parse tablet index pb")
4854
0
                    .tag("instance_id", instance_id_)
4855
0
                    .tag("tablet_id", tablet_id);
4856
0
            ret = -1;
4857
10
        } else {
4858
10
            std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
4859
10
                    {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
4860
10
                     tablet_index_pb.index_id(), tablet_index_pb.partition_id(), tablet_id});
4861
10
            txn->remove(versioned_inverted_idx_key);
4862
10
            txn->remove(versioned_idx_key);
4863
10
        }
4864
10
    }
4865
4866
11
    err = txn->commit();
4867
11
    if (err != TxnErrorCode::TXN_OK) {
4868
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
4869
0
        ret = -1;
4870
0
    }
4871
4872
11
    if (ret == 0) {
4873
        // All object files under tablet have been deleted
4874
11
        std::lock_guard lock(recycled_tablets_mtx_);
4875
11
        recycled_tablets_.insert(tablet_id);
4876
11
    }
4877
4878
11
    return ret;
4879
11
}
4880
4881
27
int InstanceRecycler::recycle_rowsets() {
4882
27
    if (should_recycle_versioned_keys()) {
4883
5
        return recycle_versioned_rowsets();
4884
5
    }
4885
4886
22
    const std::string task_name = "recycle_rowsets";
4887
22
    int64_t num_scanned = 0;
4888
22
    int64_t num_expired = 0;
4889
22
    int64_t num_prepare = 0;
4890
22
    int64_t num_compacted = 0;
4891
22
    int64_t num_empty_rowset = 0;
4892
22
    size_t total_rowset_key_size = 0;
4893
22
    size_t total_rowset_value_size = 0;
4894
22
    size_t expired_rowset_size = 0;
4895
22
    std::atomic_long num_recycled = 0;
4896
22
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
4897
4898
22
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
4899
22
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
4900
22
    std::string recyc_rs_key0;
4901
22
    std::string recyc_rs_key1;
4902
22
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
4903
22
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
4904
4905
22
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
4906
4907
22
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
4908
22
    register_recycle_task(task_name, start_time);
4909
4910
22
    DORIS_CLOUD_DEFER {
4911
22
        unregister_recycle_task(task_name);
4912
22
        int64_t cost =
4913
22
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4914
22
        metrics_context.finish_report();
4915
22
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
4916
22
                .tag("instance_id", instance_id_)
4917
22
                .tag("num_scanned", num_scanned)
4918
22
                .tag("num_expired", num_expired)
4919
22
                .tag("num_recycled", num_recycled)
4920
22
                .tag("num_recycled.prepare", num_prepare)
4921
22
                .tag("num_recycled.compacted", num_compacted)
4922
22
                .tag("num_recycled.empty_rowset", num_empty_rowset)
4923
22
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
4924
22
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
4925
22
                .tag("expired_rowset_meta_size", expired_rowset_size);
4926
22
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
4910
7
    DORIS_CLOUD_DEFER {
4911
7
        unregister_recycle_task(task_name);
4912
7
        int64_t cost =
4913
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4914
7
        metrics_context.finish_report();
4915
7
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
4916
7
                .tag("instance_id", instance_id_)
4917
7
                .tag("num_scanned", num_scanned)
4918
7
                .tag("num_expired", num_expired)
4919
7
                .tag("num_recycled", num_recycled)
4920
7
                .tag("num_recycled.prepare", num_prepare)
4921
7
                .tag("num_recycled.compacted", num_compacted)
4922
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
4923
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
4924
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
4925
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
4926
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
4910
15
    DORIS_CLOUD_DEFER {
4911
15
        unregister_recycle_task(task_name);
4912
15
        int64_t cost =
4913
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4914
15
        metrics_context.finish_report();
4915
15
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
4916
15
                .tag("instance_id", instance_id_)
4917
15
                .tag("num_scanned", num_scanned)
4918
15
                .tag("num_expired", num_expired)
4919
15
                .tag("num_recycled", num_recycled)
4920
15
                .tag("num_recycled.prepare", num_prepare)
4921
15
                .tag("num_recycled.compacted", num_compacted)
4922
15
                .tag("num_recycled.empty_rowset", num_empty_rowset)
4923
15
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
4924
15
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
4925
15
                .tag("expired_rowset_meta_size", expired_rowset_size);
4926
15
    };
4927
4928
22
    std::vector<std::string> rowset_keys;
4929
22
    std::vector<std::string> rowset_keys_to_mark_recycled;
4930
22
    std::vector<std::string> rowset_keys_to_abort;
4931
22
    std::vector<std::string> prepare_rowset_keys_to_delete;
4932
    // rowset_id -> rowset_meta
4933
    // store rowset id and meta for statistics rs size when delete
4934
22
    std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
4935
4936
    // Store keys of rowset recycled by background workers
4937
22
    std::mutex async_recycled_rowset_keys_mutex;
4938
22
    std::vector<std::string> async_recycled_rowset_keys;
4939
22
    auto worker_pool = std::make_unique<SimpleThreadPool>(
4940
22
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
4941
22
    worker_pool->start();
4942
    // TODO bacth delete
4943
4.00k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
4944
4.00k
        std::string dbm_start_key =
4945
4.00k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4946
4.00k
        std::string dbm_end_key = dbm_start_key;
4947
4.00k
        encode_int64(INT64_MAX, &dbm_end_key);
4948
4.00k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4949
4.00k
        if (ret != 0) {
4950
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
4951
0
                         << instance_id_;
4952
0
        }
4953
4.00k
        return ret;
4954
4.00k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
4943
2
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
4944
2
        std::string dbm_start_key =
4945
2
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4946
2
        std::string dbm_end_key = dbm_start_key;
4947
2
        encode_int64(INT64_MAX, &dbm_end_key);
4948
2
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4949
2
        if (ret != 0) {
4950
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
4951
0
                         << instance_id_;
4952
0
        }
4953
2
        return ret;
4954
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
4943
4.00k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
4944
4.00k
        std::string dbm_start_key =
4945
4.00k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4946
4.00k
        std::string dbm_end_key = dbm_start_key;
4947
4.00k
        encode_int64(INT64_MAX, &dbm_end_key);
4948
4.00k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4949
4.00k
        if (ret != 0) {
4950
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
4951
0
                         << instance_id_;
4952
0
        }
4953
4.00k
        return ret;
4954
4.00k
    };
4955
22
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
4956
250
                                            int64_t tablet_id, const std::string& rowset_id) {
4957
        // Try to delete rowset data in background thread
4958
250
        int ret = worker_pool->submit_with_timeout(
4959
250
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4960
246
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4961
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4962
0
                        return;
4963
0
                    }
4964
246
                    std::vector<std::string> keys;
4965
246
                    {
4966
246
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4967
246
                        async_recycled_rowset_keys.push_back(std::move(key));
4968
246
                        if (async_recycled_rowset_keys.size() > 100) {
4969
2
                            keys.swap(async_recycled_rowset_keys);
4970
2
                        }
4971
246
                    }
4972
246
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4973
246
                    if (keys.empty()) return;
4974
2
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4975
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4976
0
                                     << instance_id_;
4977
2
                    } else {
4978
2
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4979
2
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4980
2
                                           num_recycled, start_time);
4981
2
                    }
4982
2
                },
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
4959
246
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4960
246
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4961
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4962
0
                        return;
4963
0
                    }
4964
246
                    std::vector<std::string> keys;
4965
246
                    {
4966
246
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4967
246
                        async_recycled_rowset_keys.push_back(std::move(key));
4968
246
                        if (async_recycled_rowset_keys.size() > 100) {
4969
2
                            keys.swap(async_recycled_rowset_keys);
4970
2
                        }
4971
246
                    }
4972
246
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4973
246
                    if (keys.empty()) return;
4974
2
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4975
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4976
0
                                     << instance_id_;
4977
2
                    } else {
4978
2
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4979
2
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4980
2
                                           num_recycled, start_time);
4981
2
                    }
4982
2
                },
4983
250
                0);
4984
250
        if (ret == 0) return 0;
4985
        // Submit task failed, delete rowset data in current thread
4986
4
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4987
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4988
0
            return -1;
4989
0
        }
4990
4
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
4991
0
            return -1;
4992
0
        }
4993
4
        rowset_keys.push_back(std::move(key));
4994
4
        return 0;
4995
4
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
4956
250
                                            int64_t tablet_id, const std::string& rowset_id) {
4957
        // Try to delete rowset data in background thread
4958
250
        int ret = worker_pool->submit_with_timeout(
4959
250
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4960
250
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4961
250
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4962
250
                        return;
4963
250
                    }
4964
250
                    std::vector<std::string> keys;
4965
250
                    {
4966
250
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4967
250
                        async_recycled_rowset_keys.push_back(std::move(key));
4968
250
                        if (async_recycled_rowset_keys.size() > 100) {
4969
250
                            keys.swap(async_recycled_rowset_keys);
4970
250
                        }
4971
250
                    }
4972
250
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4973
250
                    if (keys.empty()) return;
4974
250
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4975
250
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4976
250
                                     << instance_id_;
4977
250
                    } else {
4978
250
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4979
250
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4980
250
                                           num_recycled, start_time);
4981
250
                    }
4982
250
                },
4983
250
                0);
4984
250
        if (ret == 0) return 0;
4985
        // Submit task failed, delete rowset data in current thread
4986
4
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4987
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4988
0
            return -1;
4989
0
        }
4990
4
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
4991
0
            return -1;
4992
0
        }
4993
4
        rowset_keys.push_back(std::move(key));
4994
4
        return 0;
4995
4
    };
4996
4997
22
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
4998
4999
7.75k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5000
7.75k
        ++num_scanned;
5001
7.75k
        total_rowset_key_size += k.size();
5002
7.75k
        total_rowset_value_size += v.size();
5003
7.75k
        RecycleRowsetPB rowset;
5004
7.75k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5005
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5006
0
            return -1;
5007
0
        }
5008
5009
7.75k
        int64_t current_time = ::time(nullptr);
5010
7.75k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5011
5012
7.75k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5013
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5014
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5015
7.75k
        if (current_time < expiration) { // not expired
5016
0
            return 0;
5017
0
        }
5018
7.75k
        ++num_expired;
5019
7.75k
        expired_rowset_size += v.size();
5020
5021
7.75k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5022
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5023
                // in old version, keep this key-value pair and it needs to be checked manually
5024
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5025
0
                return -1;
5026
0
            }
5027
250
            if (rowset.resource_id().empty()) [[unlikely]] {
5028
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5029
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5030
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5031
0
                rowset_keys.emplace_back(k);
5032
0
                return -1;
5033
0
            }
5034
            // decode rowset_id
5035
250
            auto k1 = k;
5036
250
            k1.remove_prefix(1);
5037
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5038
250
            decode_key(&k1, &out);
5039
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5040
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5041
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5042
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5043
250
                      << " task_type=" << metrics_context.operation_type;
5044
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5045
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5046
0
                return -1;
5047
0
            }
5048
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5049
250
            metrics_context.total_recycled_num++;
5050
250
            segment_metrics_context_.total_recycled_data_size +=
5051
250
                    rowset.rowset_meta().total_disk_size();
5052
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5053
250
            return 0;
5054
250
        }
5055
5056
7.50k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5057
7.50k
        if (config::enable_mark_delete_rowset_before_recycle) {
5058
7.50k
            if (need_mark_rowset_as_recycled(rowset)) {
5059
3.75k
                rowset_keys_to_mark_recycled.emplace_back(k);
5060
3.75k
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5061
3.75k
                             "at next turn, instance_id="
5062
3.75k
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5063
3.75k
                          << " version=[" << rowset_meta->start_version() << '-'
5064
3.75k
                          << rowset_meta->end_version() << "]";
5065
3.75k
                return 0;
5066
3.75k
            }
5067
7.50k
        }
5068
5069
3.75k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5070
3.75k
            rowset_meta->end_version() != 1) {
5071
3.75k
            if (make_deferred_abort_task(rowset).has_value()) {
5072
2
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5073
2
                             "instance_id="
5074
2
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5075
2
                          << " version=[" << rowset_meta->start_version() << '-'
5076
2
                          << rowset_meta->end_version() << "]";
5077
2
                rowset_keys_to_abort.emplace_back(k);
5078
2
            }
5079
3.75k
        }
5080
5081
        // TODO(plat1ko): check rowset not referenced
5082
3.75k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5083
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5084
0
                LOG_INFO("recycle rowset that has empty resource id");
5085
0
            } else {
5086
                // other situations, keep this key-value pair and it needs to be checked manually
5087
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5088
0
                return -1;
5089
0
            }
5090
0
        }
5091
3.75k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5092
3.75k
                  << " tablet_id=" << rowset_meta->tablet_id()
5093
3.75k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5094
3.75k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5095
3.75k
                  << "] txn_id=" << rowset_meta->txn_id()
5096
3.75k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5097
3.75k
                  << " rowset_meta_size=" << v.size()
5098
3.75k
                  << " creation_time=" << rowset_meta->creation_time()
5099
3.75k
                  << " task_type=" << metrics_context.operation_type;
5100
3.75k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5101
            // unable to calculate file path, can only be deleted by rowset id prefix
5102
652
            num_prepare += 1;
5103
652
            prepare_rowset_keys_to_delete.emplace_back(k);
5104
3.10k
        } else {
5105
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5106
3.10k
            rowset_keys.emplace_back(k);
5107
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5108
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5109
3.10k
                ++num_empty_rowset;
5110
3.10k
            }
5111
3.10k
        }
5112
3.75k
        return 0;
5113
3.75k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
4999
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5000
7
        ++num_scanned;
5001
7
        total_rowset_key_size += k.size();
5002
7
        total_rowset_value_size += v.size();
5003
7
        RecycleRowsetPB rowset;
5004
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5005
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5006
0
            return -1;
5007
0
        }
5008
5009
7
        int64_t current_time = ::time(nullptr);
5010
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5011
5012
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5013
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5014
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5015
7
        if (current_time < expiration) { // not expired
5016
0
            return 0;
5017
0
        }
5018
7
        ++num_expired;
5019
7
        expired_rowset_size += v.size();
5020
5021
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5022
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5023
                // in old version, keep this key-value pair and it needs to be checked manually
5024
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5025
0
                return -1;
5026
0
            }
5027
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5028
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5029
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5030
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5031
0
                rowset_keys.emplace_back(k);
5032
0
                return -1;
5033
0
            }
5034
            // decode rowset_id
5035
0
            auto k1 = k;
5036
0
            k1.remove_prefix(1);
5037
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5038
0
            decode_key(&k1, &out);
5039
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5040
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5041
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5042
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5043
0
                      << " task_type=" << metrics_context.operation_type;
5044
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5045
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5046
0
                return -1;
5047
0
            }
5048
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5049
0
            metrics_context.total_recycled_num++;
5050
0
            segment_metrics_context_.total_recycled_data_size +=
5051
0
                    rowset.rowset_meta().total_disk_size();
5052
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5053
0
            return 0;
5054
0
        }
5055
5056
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
5057
7
        if (config::enable_mark_delete_rowset_before_recycle) {
5058
7
            if (need_mark_rowset_as_recycled(rowset)) {
5059
5
                rowset_keys_to_mark_recycled.emplace_back(k);
5060
5
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5061
5
                             "at next turn, instance_id="
5062
5
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5063
5
                          << " version=[" << rowset_meta->start_version() << '-'
5064
5
                          << rowset_meta->end_version() << "]";
5065
5
                return 0;
5066
5
            }
5067
7
        }
5068
5069
2
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5070
2
            rowset_meta->end_version() != 1) {
5071
2
            if (make_deferred_abort_task(rowset).has_value()) {
5072
2
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5073
2
                             "instance_id="
5074
2
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5075
2
                          << " version=[" << rowset_meta->start_version() << '-'
5076
2
                          << rowset_meta->end_version() << "]";
5077
2
                rowset_keys_to_abort.emplace_back(k);
5078
2
            }
5079
2
        }
5080
5081
        // TODO(plat1ko): check rowset not referenced
5082
2
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5083
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5084
0
                LOG_INFO("recycle rowset that has empty resource id");
5085
0
            } else {
5086
                // other situations, keep this key-value pair and it needs to be checked manually
5087
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5088
0
                return -1;
5089
0
            }
5090
0
        }
5091
2
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5092
2
                  << " tablet_id=" << rowset_meta->tablet_id()
5093
2
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5094
2
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5095
2
                  << "] txn_id=" << rowset_meta->txn_id()
5096
2
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5097
2
                  << " rowset_meta_size=" << v.size()
5098
2
                  << " creation_time=" << rowset_meta->creation_time()
5099
2
                  << " task_type=" << metrics_context.operation_type;
5100
2
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5101
            // unable to calculate file path, can only be deleted by rowset id prefix
5102
2
            num_prepare += 1;
5103
2
            prepare_rowset_keys_to_delete.emplace_back(k);
5104
2
        } else {
5105
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5106
0
            rowset_keys.emplace_back(k);
5107
0
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5108
0
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5109
0
                ++num_empty_rowset;
5110
0
            }
5111
0
        }
5112
2
        return 0;
5113
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
4999
7.75k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5000
7.75k
        ++num_scanned;
5001
7.75k
        total_rowset_key_size += k.size();
5002
7.75k
        total_rowset_value_size += v.size();
5003
7.75k
        RecycleRowsetPB rowset;
5004
7.75k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5005
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5006
0
            return -1;
5007
0
        }
5008
5009
7.75k
        int64_t current_time = ::time(nullptr);
5010
7.75k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5011
5012
7.75k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5013
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5014
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5015
7.75k
        if (current_time < expiration) { // not expired
5016
0
            return 0;
5017
0
        }
5018
7.75k
        ++num_expired;
5019
7.75k
        expired_rowset_size += v.size();
5020
5021
7.75k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5022
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5023
                // in old version, keep this key-value pair and it needs to be checked manually
5024
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5025
0
                return -1;
5026
0
            }
5027
250
            if (rowset.resource_id().empty()) [[unlikely]] {
5028
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5029
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5030
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5031
0
                rowset_keys.emplace_back(k);
5032
0
                return -1;
5033
0
            }
5034
            // decode rowset_id
5035
250
            auto k1 = k;
5036
250
            k1.remove_prefix(1);
5037
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5038
250
            decode_key(&k1, &out);
5039
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5040
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5041
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5042
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5043
250
                      << " task_type=" << metrics_context.operation_type;
5044
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5045
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5046
0
                return -1;
5047
0
            }
5048
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5049
250
            metrics_context.total_recycled_num++;
5050
250
            segment_metrics_context_.total_recycled_data_size +=
5051
250
                    rowset.rowset_meta().total_disk_size();
5052
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5053
250
            return 0;
5054
250
        }
5055
5056
7.50k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5057
7.50k
        if (config::enable_mark_delete_rowset_before_recycle) {
5058
7.50k
            if (need_mark_rowset_as_recycled(rowset)) {
5059
3.75k
                rowset_keys_to_mark_recycled.emplace_back(k);
5060
3.75k
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5061
3.75k
                             "at next turn, instance_id="
5062
3.75k
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5063
3.75k
                          << " version=[" << rowset_meta->start_version() << '-'
5064
3.75k
                          << rowset_meta->end_version() << "]";
5065
3.75k
                return 0;
5066
3.75k
            }
5067
7.50k
        }
5068
5069
3.75k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5070
3.75k
            rowset_meta->end_version() != 1) {
5071
3.75k
            if (make_deferred_abort_task(rowset).has_value()) {
5072
0
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5073
0
                             "instance_id="
5074
0
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5075
0
                          << " version=[" << rowset_meta->start_version() << '-'
5076
0
                          << rowset_meta->end_version() << "]";
5077
0
                rowset_keys_to_abort.emplace_back(k);
5078
0
            }
5079
3.75k
        }
5080
5081
        // TODO(plat1ko): check rowset not referenced
5082
3.75k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5083
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5084
0
                LOG_INFO("recycle rowset that has empty resource id");
5085
0
            } else {
5086
                // other situations, keep this key-value pair and it needs to be checked manually
5087
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5088
0
                return -1;
5089
0
            }
5090
0
        }
5091
3.75k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5092
3.75k
                  << " tablet_id=" << rowset_meta->tablet_id()
5093
3.75k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5094
3.75k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5095
3.75k
                  << "] txn_id=" << rowset_meta->txn_id()
5096
3.75k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5097
3.75k
                  << " rowset_meta_size=" << v.size()
5098
3.75k
                  << " creation_time=" << rowset_meta->creation_time()
5099
3.75k
                  << " task_type=" << metrics_context.operation_type;
5100
3.75k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5101
            // unable to calculate file path, can only be deleted by rowset id prefix
5102
650
            num_prepare += 1;
5103
650
            prepare_rowset_keys_to_delete.emplace_back(k);
5104
3.10k
        } else {
5105
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5106
3.10k
            rowset_keys.emplace_back(k);
5107
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5108
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5109
3.10k
                ++num_empty_rowset;
5110
3.10k
            }
5111
3.10k
        }
5112
3.75k
        return 0;
5113
3.75k
    };
5114
5115
49
    auto loop_done = [&]() -> int {
5116
49
        std::vector<std::string> rowset_keys_to_delete;
5117
49
        std::vector<std::string> mark_keys_to_process;
5118
49
        std::vector<std::string> abort_keys_to_process;
5119
49
        std::vector<std::string> prepare_keys_to_process;
5120
        // rowset_id -> rowset_meta
5121
        // store rowset id and meta for statistics rs size when delete
5122
49
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5123
49
        rowset_keys_to_delete.swap(rowset_keys);
5124
49
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5125
49
        abort_keys_to_process.swap(rowset_keys_to_abort);
5126
49
        prepare_keys_to_process.swap(prepare_rowset_keys_to_delete);
5127
49
        rowsets_to_delete.swap(rowsets);
5128
49
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5129
49
                             rowsets_to_delete = std::move(rowsets_to_delete),
5130
49
                             prepare_keys_to_process = std::move(prepare_keys_to_process),
5131
49
                             mark_keys_to_process = std::move(mark_keys_to_process),
5132
49
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5133
49
            if (!mark_keys_to_process.empty() &&
5134
49
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5135
26
                                                                mark_keys_to_process) != 0) {
5136
0
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5137
0
                             << instance_id_;
5138
0
                return;
5139
0
            }
5140
49
            if (!abort_keys_to_process.empty() &&
5141
49
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5142
2
                        0) {
5143
0
                return;
5144
0
            }
5145
49
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5146
49
            if (!prepare_keys_to_process.empty() &&
5147
49
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5148
23
                                             &prepare_delete_tasks) != 0) {
5149
0
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5150
0
                             << instance_id_;
5151
0
                return;
5152
0
            }
5153
49
            if (!prepare_delete_tasks.empty()) {
5154
23
                std::vector<std::string> prepare_rowset_keys_to_delete;
5155
23
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5156
652
                for (const auto& task : prepare_delete_tasks) {
5157
652
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5158
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5159
0
                        return;
5160
0
                    }
5161
652
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5162
0
                        return;
5163
0
                    }
5164
652
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5165
652
                }
5166
23
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5167
0
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5168
0
                                 << instance_id_;
5169
0
                    return;
5170
0
                }
5171
23
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5172
23
                                       std::memory_order_relaxed);
5173
23
            }
5174
49
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5175
49
                                   metrics_context) != 0) {
5176
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5177
0
                return;
5178
0
            }
5179
3.10k
            for (const auto& [_, rs] : rowsets_to_delete) {
5180
3.10k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5181
0
                    return;
5182
0
                }
5183
3.10k
            }
5184
49
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5185
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5186
0
                return;
5187
0
            }
5188
49
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5189
49
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5132
7
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5133
7
            if (!mark_keys_to_process.empty() &&
5134
7
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5135
5
                                                                mark_keys_to_process) != 0) {
5136
0
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5137
0
                             << instance_id_;
5138
0
                return;
5139
0
            }
5140
7
            if (!abort_keys_to_process.empty() &&
5141
7
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5142
2
                        0) {
5143
0
                return;
5144
0
            }
5145
7
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5146
7
            if (!prepare_keys_to_process.empty() &&
5147
7
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5148
2
                                             &prepare_delete_tasks) != 0) {
5149
0
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5150
0
                             << instance_id_;
5151
0
                return;
5152
0
            }
5153
7
            if (!prepare_delete_tasks.empty()) {
5154
2
                std::vector<std::string> prepare_rowset_keys_to_delete;
5155
2
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5156
2
                for (const auto& task : prepare_delete_tasks) {
5157
2
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5158
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5159
0
                        return;
5160
0
                    }
5161
2
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5162
0
                        return;
5163
0
                    }
5164
2
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5165
2
                }
5166
2
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5167
0
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5168
0
                                 << instance_id_;
5169
0
                    return;
5170
0
                }
5171
2
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5172
2
                                       std::memory_order_relaxed);
5173
2
            }
5174
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5175
7
                                   metrics_context) != 0) {
5176
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5177
0
                return;
5178
0
            }
5179
7
            for (const auto& [_, rs] : rowsets_to_delete) {
5180
0
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5181
0
                    return;
5182
0
                }
5183
0
            }
5184
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5185
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5186
0
                return;
5187
0
            }
5188
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5189
7
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5132
42
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5133
42
            if (!mark_keys_to_process.empty() &&
5134
42
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5135
21
                                                                mark_keys_to_process) != 0) {
5136
0
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5137
0
                             << instance_id_;
5138
0
                return;
5139
0
            }
5140
42
            if (!abort_keys_to_process.empty() &&
5141
42
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5142
0
                        0) {
5143
0
                return;
5144
0
            }
5145
42
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5146
42
            if (!prepare_keys_to_process.empty() &&
5147
42
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5148
21
                                             &prepare_delete_tasks) != 0) {
5149
0
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5150
0
                             << instance_id_;
5151
0
                return;
5152
0
            }
5153
42
            if (!prepare_delete_tasks.empty()) {
5154
21
                std::vector<std::string> prepare_rowset_keys_to_delete;
5155
21
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5156
650
                for (const auto& task : prepare_delete_tasks) {
5157
650
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5158
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5159
0
                        return;
5160
0
                    }
5161
650
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5162
0
                        return;
5163
0
                    }
5164
650
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5165
650
                }
5166
21
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5167
0
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5168
0
                                 << instance_id_;
5169
0
                    return;
5170
0
                }
5171
21
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5172
21
                                       std::memory_order_relaxed);
5173
21
            }
5174
42
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5175
42
                                   metrics_context) != 0) {
5176
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5177
0
                return;
5178
0
            }
5179
3.10k
            for (const auto& [_, rs] : rowsets_to_delete) {
5180
3.10k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5181
0
                    return;
5182
0
                }
5183
3.10k
            }
5184
42
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5185
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5186
0
                return;
5187
0
            }
5188
42
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5189
42
        });
5190
49
        return 0;
5191
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5115
7
    auto loop_done = [&]() -> int {
5116
7
        std::vector<std::string> rowset_keys_to_delete;
5117
7
        std::vector<std::string> mark_keys_to_process;
5118
7
        std::vector<std::string> abort_keys_to_process;
5119
7
        std::vector<std::string> prepare_keys_to_process;
5120
        // rowset_id -> rowset_meta
5121
        // store rowset id and meta for statistics rs size when delete
5122
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5123
7
        rowset_keys_to_delete.swap(rowset_keys);
5124
7
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5125
7
        abort_keys_to_process.swap(rowset_keys_to_abort);
5126
7
        prepare_keys_to_process.swap(prepare_rowset_keys_to_delete);
5127
7
        rowsets_to_delete.swap(rowsets);
5128
7
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5129
7
                             rowsets_to_delete = std::move(rowsets_to_delete),
5130
7
                             prepare_keys_to_process = std::move(prepare_keys_to_process),
5131
7
                             mark_keys_to_process = std::move(mark_keys_to_process),
5132
7
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5133
7
            if (!mark_keys_to_process.empty() &&
5134
7
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5135
7
                                                                mark_keys_to_process) != 0) {
5136
7
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5137
7
                             << instance_id_;
5138
7
                return;
5139
7
            }
5140
7
            if (!abort_keys_to_process.empty() &&
5141
7
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5142
7
                        0) {
5143
7
                return;
5144
7
            }
5145
7
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5146
7
            if (!prepare_keys_to_process.empty() &&
5147
7
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5148
7
                                             &prepare_delete_tasks) != 0) {
5149
7
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5150
7
                             << instance_id_;
5151
7
                return;
5152
7
            }
5153
7
            if (!prepare_delete_tasks.empty()) {
5154
7
                std::vector<std::string> prepare_rowset_keys_to_delete;
5155
7
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5156
7
                for (const auto& task : prepare_delete_tasks) {
5157
7
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5158
7
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5159
7
                        return;
5160
7
                    }
5161
7
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5162
7
                        return;
5163
7
                    }
5164
7
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5165
7
                }
5166
7
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5167
7
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5168
7
                                 << instance_id_;
5169
7
                    return;
5170
7
                }
5171
7
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5172
7
                                       std::memory_order_relaxed);
5173
7
            }
5174
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5175
7
                                   metrics_context) != 0) {
5176
7
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5177
7
                return;
5178
7
            }
5179
7
            for (const auto& [_, rs] : rowsets_to_delete) {
5180
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5181
7
                    return;
5182
7
                }
5183
7
            }
5184
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5185
7
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5186
7
                return;
5187
7
            }
5188
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5189
7
        });
5190
7
        return 0;
5191
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5115
42
    auto loop_done = [&]() -> int {
5116
42
        std::vector<std::string> rowset_keys_to_delete;
5117
42
        std::vector<std::string> mark_keys_to_process;
5118
42
        std::vector<std::string> abort_keys_to_process;
5119
42
        std::vector<std::string> prepare_keys_to_process;
5120
        // rowset_id -> rowset_meta
5121
        // store rowset id and meta for statistics rs size when delete
5122
42
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5123
42
        rowset_keys_to_delete.swap(rowset_keys);
5124
42
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5125
42
        abort_keys_to_process.swap(rowset_keys_to_abort);
5126
42
        prepare_keys_to_process.swap(prepare_rowset_keys_to_delete);
5127
42
        rowsets_to_delete.swap(rowsets);
5128
42
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5129
42
                             rowsets_to_delete = std::move(rowsets_to_delete),
5130
42
                             prepare_keys_to_process = std::move(prepare_keys_to_process),
5131
42
                             mark_keys_to_process = std::move(mark_keys_to_process),
5132
42
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5133
42
            if (!mark_keys_to_process.empty() &&
5134
42
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5135
42
                                                                mark_keys_to_process) != 0) {
5136
42
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5137
42
                             << instance_id_;
5138
42
                return;
5139
42
            }
5140
42
            if (!abort_keys_to_process.empty() &&
5141
42
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5142
42
                        0) {
5143
42
                return;
5144
42
            }
5145
42
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5146
42
            if (!prepare_keys_to_process.empty() &&
5147
42
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5148
42
                                             &prepare_delete_tasks) != 0) {
5149
42
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5150
42
                             << instance_id_;
5151
42
                return;
5152
42
            }
5153
42
            if (!prepare_delete_tasks.empty()) {
5154
42
                std::vector<std::string> prepare_rowset_keys_to_delete;
5155
42
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5156
42
                for (const auto& task : prepare_delete_tasks) {
5157
42
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5158
42
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5159
42
                        return;
5160
42
                    }
5161
42
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5162
42
                        return;
5163
42
                    }
5164
42
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5165
42
                }
5166
42
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5167
42
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5168
42
                                 << instance_id_;
5169
42
                    return;
5170
42
                }
5171
42
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5172
42
                                       std::memory_order_relaxed);
5173
42
            }
5174
42
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5175
42
                                   metrics_context) != 0) {
5176
42
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5177
42
                return;
5178
42
            }
5179
42
            for (const auto& [_, rs] : rowsets_to_delete) {
5180
42
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5181
42
                    return;
5182
42
                }
5183
42
            }
5184
42
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5185
42
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5186
42
                return;
5187
42
            }
5188
42
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5189
42
        });
5190
42
        return 0;
5191
42
    };
5192
5193
22
    if (config::enable_recycler_stats_metrics) {
5194
0
        scan_and_statistics_rowsets();
5195
0
    }
5196
    // recycle_func and loop_done for scan and recycle
5197
22
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
5198
22
                               std::move(loop_done));
5199
5200
22
    worker_pool->stop();
5201
5202
22
    if (!async_recycled_rowset_keys.empty()) {
5203
1
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5204
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5205
0
            return -1;
5206
1
        } else {
5207
1
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5208
1
        }
5209
1
    }
5210
5211
    // Report final metrics after all concurrent tasks completed
5212
22
    segment_metrics_context_.report();
5213
22
    metrics_context.report();
5214
5215
22
    return ret;
5216
22
}
5217
5218
13
int InstanceRecycler::recycle_restore_jobs() {
5219
13
    const std::string task_name = "recycle_restore_jobs";
5220
13
    int64_t num_scanned = 0;
5221
13
    int64_t num_expired = 0;
5222
13
    int64_t num_recycled = 0;
5223
13
    int64_t num_aborted = 0;
5224
5225
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5226
5227
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
5228
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
5229
13
    std::string restore_job_key0;
5230
13
    std::string restore_job_key1;
5231
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
5232
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
5233
5234
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
5235
5236
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5237
13
    register_recycle_task(task_name, start_time);
5238
5239
13
    DORIS_CLOUD_DEFER {
5240
13
        unregister_recycle_task(task_name);
5241
13
        int64_t cost =
5242
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5243
13
        metrics_context.finish_report();
5244
5245
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5246
13
                .tag("instance_id", instance_id_)
5247
13
                .tag("num_scanned", num_scanned)
5248
13
                .tag("num_expired", num_expired)
5249
13
                .tag("num_recycled", num_recycled)
5250
13
                .tag("num_aborted", num_aborted);
5251
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
5239
13
    DORIS_CLOUD_DEFER {
5240
13
        unregister_recycle_task(task_name);
5241
13
        int64_t cost =
5242
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5243
13
        metrics_context.finish_report();
5244
5245
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5246
13
                .tag("instance_id", instance_id_)
5247
13
                .tag("num_scanned", num_scanned)
5248
13
                .tag("num_expired", num_expired)
5249
13
                .tag("num_recycled", num_recycled)
5250
13
                .tag("num_aborted", num_aborted);
5251
13
    };
5252
5253
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5254
5255
13
    std::vector<std::string_view> restore_job_keys;
5256
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5257
41
        ++num_scanned;
5258
41
        RestoreJobCloudPB restore_job_pb;
5259
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5260
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5261
0
            return -1;
5262
0
        }
5263
41
        int64_t expiration =
5264
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5265
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5266
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5267
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5268
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5269
0
                   << " state=" << restore_job_pb.state();
5270
41
        int64_t current_time = ::time(nullptr);
5271
41
        if (current_time < expiration) { // not expired
5272
0
            return 0;
5273
0
        }
5274
41
        ++num_expired;
5275
5276
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5277
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5278
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5279
5280
41
        std::unique_ptr<Transaction> txn;
5281
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5282
41
        if (err != TxnErrorCode::TXN_OK) {
5283
0
            LOG_WARNING("failed to recycle restore job")
5284
0
                    .tag("err", err)
5285
0
                    .tag("tablet id", tablet_id)
5286
0
                    .tag("instance_id", instance_id_)
5287
0
                    .tag("reason", "failed to create txn");
5288
0
            return -1;
5289
0
        }
5290
5291
41
        std::string val;
5292
41
        err = txn->get(k, &val);
5293
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5294
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5295
0
            return 0;
5296
0
        }
5297
41
        if (err != TxnErrorCode::TXN_OK) {
5298
0
            LOG_WARNING("failed to get kv");
5299
0
            return -1;
5300
0
        }
5301
41
        restore_job_pb.Clear();
5302
41
        if (!restore_job_pb.ParseFromString(val)) {
5303
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5304
0
            return -1;
5305
0
        }
5306
5307
        // PREPARED or COMMITTED, change state to DROPPED and return
5308
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5309
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5310
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5311
0
            restore_job_pb.set_need_recycle_data(true);
5312
0
            txn->put(k, restore_job_pb.SerializeAsString());
5313
0
            err = txn->commit();
5314
0
            if (err != TxnErrorCode::TXN_OK) {
5315
0
                LOG_WARNING("failed to commit txn: {}", err);
5316
0
                return -1;
5317
0
            }
5318
0
            num_aborted++;
5319
0
            return 0;
5320
0
        }
5321
5322
        // Change state to RECYCLING
5323
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5324
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5325
21
            txn->put(k, restore_job_pb.SerializeAsString());
5326
21
            err = txn->commit();
5327
21
            if (err != TxnErrorCode::TXN_OK) {
5328
0
                LOG_WARNING("failed to commit txn: {}", err);
5329
0
                return -1;
5330
0
            }
5331
21
            return 0;
5332
21
        }
5333
5334
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5335
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5336
5337
        // Recycle all data associated with the restore job.
5338
        // This includes rowsets, segments, and related resources.
5339
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5340
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5341
0
            LOG_WARNING("failed to recycle tablet")
5342
0
                    .tag("tablet_id", tablet_id)
5343
0
                    .tag("instance_id", instance_id_);
5344
0
            return -1;
5345
0
        }
5346
5347
        // delete all restore job rowset kv
5348
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5349
5350
20
        err = txn->commit();
5351
20
        if (err != TxnErrorCode::TXN_OK) {
5352
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5353
0
                    .tag("err", err)
5354
0
                    .tag("tablet id", tablet_id)
5355
0
                    .tag("instance_id", instance_id_)
5356
0
                    .tag("reason", "failed to commit txn");
5357
0
            return -1;
5358
0
        }
5359
5360
20
        metrics_context.total_recycled_num = ++num_recycled;
5361
20
        metrics_context.report();
5362
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5363
20
        restore_job_keys.push_back(k);
5364
5365
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5366
20
                  << " tablet_id=" << tablet_id;
5367
20
        return 0;
5368
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
5256
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5257
41
        ++num_scanned;
5258
41
        RestoreJobCloudPB restore_job_pb;
5259
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5260
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5261
0
            return -1;
5262
0
        }
5263
41
        int64_t expiration =
5264
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5265
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5266
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5267
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5268
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5269
0
                   << " state=" << restore_job_pb.state();
5270
41
        int64_t current_time = ::time(nullptr);
5271
41
        if (current_time < expiration) { // not expired
5272
0
            return 0;
5273
0
        }
5274
41
        ++num_expired;
5275
5276
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5277
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5278
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5279
5280
41
        std::unique_ptr<Transaction> txn;
5281
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5282
41
        if (err != TxnErrorCode::TXN_OK) {
5283
0
            LOG_WARNING("failed to recycle restore job")
5284
0
                    .tag("err", err)
5285
0
                    .tag("tablet id", tablet_id)
5286
0
                    .tag("instance_id", instance_id_)
5287
0
                    .tag("reason", "failed to create txn");
5288
0
            return -1;
5289
0
        }
5290
5291
41
        std::string val;
5292
41
        err = txn->get(k, &val);
5293
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5294
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5295
0
            return 0;
5296
0
        }
5297
41
        if (err != TxnErrorCode::TXN_OK) {
5298
0
            LOG_WARNING("failed to get kv");
5299
0
            return -1;
5300
0
        }
5301
41
        restore_job_pb.Clear();
5302
41
        if (!restore_job_pb.ParseFromString(val)) {
5303
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5304
0
            return -1;
5305
0
        }
5306
5307
        // PREPARED or COMMITTED, change state to DROPPED and return
5308
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5309
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5310
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5311
0
            restore_job_pb.set_need_recycle_data(true);
5312
0
            txn->put(k, restore_job_pb.SerializeAsString());
5313
0
            err = txn->commit();
5314
0
            if (err != TxnErrorCode::TXN_OK) {
5315
0
                LOG_WARNING("failed to commit txn: {}", err);
5316
0
                return -1;
5317
0
            }
5318
0
            num_aborted++;
5319
0
            return 0;
5320
0
        }
5321
5322
        // Change state to RECYCLING
5323
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5324
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5325
21
            txn->put(k, restore_job_pb.SerializeAsString());
5326
21
            err = txn->commit();
5327
21
            if (err != TxnErrorCode::TXN_OK) {
5328
0
                LOG_WARNING("failed to commit txn: {}", err);
5329
0
                return -1;
5330
0
            }
5331
21
            return 0;
5332
21
        }
5333
5334
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5335
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5336
5337
        // Recycle all data associated with the restore job.
5338
        // This includes rowsets, segments, and related resources.
5339
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5340
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5341
0
            LOG_WARNING("failed to recycle tablet")
5342
0
                    .tag("tablet_id", tablet_id)
5343
0
                    .tag("instance_id", instance_id_);
5344
0
            return -1;
5345
0
        }
5346
5347
        // delete all restore job rowset kv
5348
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5349
5350
20
        err = txn->commit();
5351
20
        if (err != TxnErrorCode::TXN_OK) {
5352
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5353
0
                    .tag("err", err)
5354
0
                    .tag("tablet id", tablet_id)
5355
0
                    .tag("instance_id", instance_id_)
5356
0
                    .tag("reason", "failed to commit txn");
5357
0
            return -1;
5358
0
        }
5359
5360
20
        metrics_context.total_recycled_num = ++num_recycled;
5361
20
        metrics_context.report();
5362
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5363
20
        restore_job_keys.push_back(k);
5364
5365
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5366
20
                  << " tablet_id=" << tablet_id;
5367
20
        return 0;
5368
20
    };
5369
5370
13
    auto loop_done = [&restore_job_keys, this]() -> int {
5371
3
        if (restore_job_keys.empty()) return 0;
5372
1
        DORIS_CLOUD_DEFER {
5373
1
            restore_job_keys.clear();
5374
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5372
1
        DORIS_CLOUD_DEFER {
5373
1
            restore_job_keys.clear();
5374
1
        };
5375
5376
1
        std::unique_ptr<Transaction> txn;
5377
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5378
1
        if (err != TxnErrorCode::TXN_OK) {
5379
0
            LOG_WARNING("failed to recycle restore job")
5380
0
                    .tag("err", err)
5381
0
                    .tag("instance_id", instance_id_)
5382
0
                    .tag("reason", "failed to create txn");
5383
0
            return -1;
5384
0
        }
5385
20
        for (auto& k : restore_job_keys) {
5386
20
            txn->remove(k);
5387
20
        }
5388
1
        err = txn->commit();
5389
1
        if (err != TxnErrorCode::TXN_OK) {
5390
0
            LOG_WARNING("failed to recycle restore job")
5391
0
                    .tag("err", err)
5392
0
                    .tag("instance_id", instance_id_)
5393
0
                    .tag("reason", "failed to commit txn");
5394
0
            return -1;
5395
0
        }
5396
1
        return 0;
5397
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
5370
3
    auto loop_done = [&restore_job_keys, this]() -> int {
5371
3
        if (restore_job_keys.empty()) return 0;
5372
1
        DORIS_CLOUD_DEFER {
5373
1
            restore_job_keys.clear();
5374
1
        };
5375
5376
1
        std::unique_ptr<Transaction> txn;
5377
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5378
1
        if (err != TxnErrorCode::TXN_OK) {
5379
0
            LOG_WARNING("failed to recycle restore job")
5380
0
                    .tag("err", err)
5381
0
                    .tag("instance_id", instance_id_)
5382
0
                    .tag("reason", "failed to create txn");
5383
0
            return -1;
5384
0
        }
5385
20
        for (auto& k : restore_job_keys) {
5386
20
            txn->remove(k);
5387
20
        }
5388
1
        err = txn->commit();
5389
1
        if (err != TxnErrorCode::TXN_OK) {
5390
0
            LOG_WARNING("failed to recycle restore job")
5391
0
                    .tag("err", err)
5392
0
                    .tag("instance_id", instance_id_)
5393
0
                    .tag("reason", "failed to commit txn");
5394
0
            return -1;
5395
0
        }
5396
1
        return 0;
5397
1
    };
5398
5399
13
    if (config::enable_recycler_stats_metrics) {
5400
0
        scan_and_statistics_restore_jobs();
5401
0
    }
5402
5403
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
5404
13
                            std::move(loop_done));
5405
13
}
5406
5407
10
int InstanceRecycler::recycle_versioned_rowsets() {
5408
10
    const std::string task_name = "recycle_rowsets";
5409
10
    int64_t num_scanned = 0;
5410
10
    int64_t num_expired = 0;
5411
10
    int64_t num_prepare = 0;
5412
10
    int64_t num_compacted = 0;
5413
10
    int64_t num_empty_rowset = 0;
5414
10
    size_t total_rowset_key_size = 0;
5415
10
    size_t total_rowset_value_size = 0;
5416
10
    size_t expired_rowset_size = 0;
5417
10
    std::atomic_long num_recycled = 0;
5418
10
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5419
5420
10
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5421
10
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5422
10
    std::string recyc_rs_key0;
5423
10
    std::string recyc_rs_key1;
5424
10
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5425
10
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5426
5427
10
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5428
5429
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5430
10
    register_recycle_task(task_name, start_time);
5431
5432
10
    DORIS_CLOUD_DEFER {
5433
10
        unregister_recycle_task(task_name);
5434
10
        int64_t cost =
5435
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5436
10
        metrics_context.finish_report();
5437
10
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5438
10
                .tag("instance_id", instance_id_)
5439
10
                .tag("num_scanned", num_scanned)
5440
10
                .tag("num_expired", num_expired)
5441
10
                .tag("num_recycled", num_recycled)
5442
10
                .tag("num_recycled.prepare", num_prepare)
5443
10
                .tag("num_recycled.compacted", num_compacted)
5444
10
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5445
10
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5446
10
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5447
10
                .tag("expired_rowset_meta_size", expired_rowset_size);
5448
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
5432
10
    DORIS_CLOUD_DEFER {
5433
10
        unregister_recycle_task(task_name);
5434
10
        int64_t cost =
5435
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5436
10
        metrics_context.finish_report();
5437
10
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5438
10
                .tag("instance_id", instance_id_)
5439
10
                .tag("num_scanned", num_scanned)
5440
10
                .tag("num_expired", num_expired)
5441
10
                .tag("num_recycled", num_recycled)
5442
10
                .tag("num_recycled.prepare", num_prepare)
5443
10
                .tag("num_recycled.compacted", num_compacted)
5444
10
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5445
10
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5446
10
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5447
10
                .tag("expired_rowset_meta_size", expired_rowset_size);
5448
10
    };
5449
5450
10
    std::vector<std::string> orphan_rowset_keys;
5451
5452
    // Store keys of rowset recycled by background workers
5453
10
    std::mutex async_recycled_rowset_keys_mutex;
5454
10
    std::vector<std::string> async_recycled_rowset_keys;
5455
10
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5456
10
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5457
10
    worker_pool->start();
5458
10
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5459
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5460
        // Try to delete rowset data in background thread
5461
400
        int ret = worker_pool->submit_with_timeout(
5462
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5463
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5464
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5465
400
                        return;
5466
400
                    }
5467
                    // The async recycled rowsets are staled format or has not been used,
5468
                    // so we don't need to check the rowset ref count key.
5469
0
                    std::vector<std::string> keys;
5470
0
                    {
5471
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5472
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5473
0
                        if (async_recycled_rowset_keys.size() > 100) {
5474
0
                            keys.swap(async_recycled_rowset_keys);
5475
0
                        }
5476
0
                    }
5477
0
                    if (keys.empty()) return;
5478
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5479
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5480
0
                                     << instance_id_;
5481
0
                    } else {
5482
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5483
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5484
0
                                           num_recycled, start_time);
5485
0
                    }
5486
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
5462
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5463
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5464
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5465
400
                        return;
5466
400
                    }
5467
                    // The async recycled rowsets are staled format or has not been used,
5468
                    // so we don't need to check the rowset ref count key.
5469
0
                    std::vector<std::string> keys;
5470
0
                    {
5471
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5472
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5473
0
                        if (async_recycled_rowset_keys.size() > 100) {
5474
0
                            keys.swap(async_recycled_rowset_keys);
5475
0
                        }
5476
0
                    }
5477
0
                    if (keys.empty()) return;
5478
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5479
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5480
0
                                     << instance_id_;
5481
0
                    } else {
5482
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5483
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5484
0
                                           num_recycled, start_time);
5485
0
                    }
5486
0
                },
5487
400
                0);
5488
400
        if (ret == 0) return 0;
5489
        // Submit task failed, delete rowset data in current thread
5490
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5491
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5492
0
            return -1;
5493
0
        }
5494
0
        orphan_rowset_keys.push_back(std::move(key));
5495
0
        return 0;
5496
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
5459
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5460
        // Try to delete rowset data in background thread
5461
400
        int ret = worker_pool->submit_with_timeout(
5462
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5463
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5464
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5465
400
                        return;
5466
400
                    }
5467
                    // The async recycled rowsets are staled format or has not been used,
5468
                    // so we don't need to check the rowset ref count key.
5469
400
                    std::vector<std::string> keys;
5470
400
                    {
5471
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5472
400
                        async_recycled_rowset_keys.push_back(std::move(key));
5473
400
                        if (async_recycled_rowset_keys.size() > 100) {
5474
400
                            keys.swap(async_recycled_rowset_keys);
5475
400
                        }
5476
400
                    }
5477
400
                    if (keys.empty()) return;
5478
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5479
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5480
400
                                     << instance_id_;
5481
400
                    } else {
5482
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5483
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5484
400
                                           num_recycled, start_time);
5485
400
                    }
5486
400
                },
5487
400
                0);
5488
400
        if (ret == 0) return 0;
5489
        // Submit task failed, delete rowset data in current thread
5490
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5491
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5492
0
            return -1;
5493
0
        }
5494
0
        orphan_rowset_keys.push_back(std::move(key));
5495
0
        return 0;
5496
0
    };
5497
5498
10
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5499
5500
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
5501
2.01k
        ++num_scanned;
5502
2.01k
        total_rowset_key_size += k.size();
5503
2.01k
        total_rowset_value_size += v.size();
5504
2.01k
        RecycleRowsetPB rowset;
5505
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5506
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5507
0
            return -1;
5508
0
        }
5509
5510
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5511
5512
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5513
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
5514
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5515
2.01k
        int64_t current_time = ::time(nullptr);
5516
2.01k
        if (current_time < final_expiration) { // not expired
5517
0
            return 0;
5518
0
        }
5519
2.01k
        ++num_expired;
5520
2.01k
        expired_rowset_size += v.size();
5521
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5522
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5523
                // in old version, keep this key-value pair and it needs to be checked manually
5524
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5525
0
                return -1;
5526
0
            }
5527
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5528
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5529
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5530
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5531
0
                orphan_rowset_keys.emplace_back(k);
5532
0
                return -1;
5533
0
            }
5534
            // decode rowset_id
5535
0
            auto k1 = k;
5536
0
            k1.remove_prefix(1);
5537
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5538
0
            decode_key(&k1, &out);
5539
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5540
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5541
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5542
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
5543
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5544
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5545
0
                return -1;
5546
0
            }
5547
0
            return 0;
5548
0
        }
5549
        // TODO(plat1ko): check rowset not referenced
5550
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
5551
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5552
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5553
0
                LOG_INFO("recycle rowset that has empty resource id");
5554
0
            } else {
5555
                // other situations, keep this key-value pair and it needs to be checked manually
5556
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5557
0
                return -1;
5558
0
            }
5559
0
        }
5560
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5561
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
5562
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5563
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5564
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
5565
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5566
2.01k
                  << " rowset_meta_size=" << v.size()
5567
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
5568
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5569
            // unable to calculate file path, can only be deleted by rowset id prefix
5570
400
            num_prepare += 1;
5571
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5572
400
                                             rowset_meta->tablet_id(),
5573
400
                                             rowset_meta->rowset_id_v2()) != 0) {
5574
0
                return -1;
5575
0
            }
5576
1.61k
        } else {
5577
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
5578
1.61k
            worker_pool->submit(
5579
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5580
                        // The load & compact rowset keys are recycled during recycling operation logs.
5581
1.61k
                        RowsetDeleteTask task;
5582
1.61k
                        task.rowset_meta = rowset_meta;
5583
1.61k
                        task.recycle_rowset_key = k;
5584
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
5585
1.60k
                            return;
5586
1.60k
                        }
5587
13
                        num_compacted += is_compacted;
5588
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5589
13
                        if (rowset_meta.num_segments() == 0) {
5590
0
                            ++num_empty_rowset;
5591
0
                        }
5592
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
5579
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5580
                        // The load & compact rowset keys are recycled during recycling operation logs.
5581
1.61k
                        RowsetDeleteTask task;
5582
1.61k
                        task.rowset_meta = rowset_meta;
5583
1.61k
                        task.recycle_rowset_key = k;
5584
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
5585
1.60k
                            return;
5586
1.60k
                        }
5587
13
                        num_compacted += is_compacted;
5588
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5589
13
                        if (rowset_meta.num_segments() == 0) {
5590
0
                            ++num_empty_rowset;
5591
0
                        }
5592
13
                    });
5593
1.61k
        }
5594
2.01k
        return 0;
5595
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
5500
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
5501
2.01k
        ++num_scanned;
5502
2.01k
        total_rowset_key_size += k.size();
5503
2.01k
        total_rowset_value_size += v.size();
5504
2.01k
        RecycleRowsetPB rowset;
5505
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5506
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5507
0
            return -1;
5508
0
        }
5509
5510
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5511
5512
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5513
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
5514
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5515
2.01k
        int64_t current_time = ::time(nullptr);
5516
2.01k
        if (current_time < final_expiration) { // not expired
5517
0
            return 0;
5518
0
        }
5519
2.01k
        ++num_expired;
5520
2.01k
        expired_rowset_size += v.size();
5521
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5522
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5523
                // in old version, keep this key-value pair and it needs to be checked manually
5524
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5525
0
                return -1;
5526
0
            }
5527
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5528
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5529
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5530
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5531
0
                orphan_rowset_keys.emplace_back(k);
5532
0
                return -1;
5533
0
            }
5534
            // decode rowset_id
5535
0
            auto k1 = k;
5536
0
            k1.remove_prefix(1);
5537
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5538
0
            decode_key(&k1, &out);
5539
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5540
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5541
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5542
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
5543
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5544
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5545
0
                return -1;
5546
0
            }
5547
0
            return 0;
5548
0
        }
5549
        // TODO(plat1ko): check rowset not referenced
5550
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
5551
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5552
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5553
0
                LOG_INFO("recycle rowset that has empty resource id");
5554
0
            } else {
5555
                // other situations, keep this key-value pair and it needs to be checked manually
5556
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5557
0
                return -1;
5558
0
            }
5559
0
        }
5560
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5561
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
5562
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5563
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5564
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
5565
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5566
2.01k
                  << " rowset_meta_size=" << v.size()
5567
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
5568
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5569
            // unable to calculate file path, can only be deleted by rowset id prefix
5570
400
            num_prepare += 1;
5571
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5572
400
                                             rowset_meta->tablet_id(),
5573
400
                                             rowset_meta->rowset_id_v2()) != 0) {
5574
0
                return -1;
5575
0
            }
5576
1.61k
        } else {
5577
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
5578
1.61k
            worker_pool->submit(
5579
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5580
                        // The load & compact rowset keys are recycled during recycling operation logs.
5581
1.61k
                        RowsetDeleteTask task;
5582
1.61k
                        task.rowset_meta = rowset_meta;
5583
1.61k
                        task.recycle_rowset_key = k;
5584
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
5585
1.61k
                            return;
5586
1.61k
                        }
5587
1.61k
                        num_compacted += is_compacted;
5588
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5589
1.61k
                        if (rowset_meta.num_segments() == 0) {
5590
1.61k
                            ++num_empty_rowset;
5591
1.61k
                        }
5592
1.61k
                    });
5593
1.61k
        }
5594
2.01k
        return 0;
5595
2.01k
    };
5596
5597
10
    if (config::enable_recycler_stats_metrics) {
5598
0
        scan_and_statistics_rowsets();
5599
0
    }
5600
5601
10
    auto loop_done = [&]() -> int {
5602
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
5603
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5604
0
        }
5605
6
        orphan_rowset_keys.clear();
5606
6
        return 0;
5607
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
Line
Count
Source
5601
6
    auto loop_done = [&]() -> int {
5602
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
5603
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5604
0
        }
5605
6
        orphan_rowset_keys.clear();
5606
6
        return 0;
5607
6
    };
5608
5609
    // recycle_func and loop_done for scan and recycle
5610
10
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
5611
10
                               std::move(loop_done));
5612
5613
10
    worker_pool->stop();
5614
5615
10
    if (!async_recycled_rowset_keys.empty()) {
5616
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5617
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5618
0
            return -1;
5619
0
        } else {
5620
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5621
0
        }
5622
0
    }
5623
5624
    // Report final metrics after all concurrent tasks completed
5625
10
    segment_metrics_context_.report();
5626
10
    metrics_context.report();
5627
5628
10
    return ret;
5629
10
}
5630
5631
1.61k
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task) {
5632
1.61k
    constexpr int MAX_RETRY = 10;
5633
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
5634
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
5635
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
5636
1.61k
    std::string_view reference_instance_id = instance_id_;
5637
1.61k
    if (rowset_meta.has_reference_instance_id()) {
5638
8
        reference_instance_id = rowset_meta.reference_instance_id();
5639
8
    }
5640
5641
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
5642
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
5643
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
5644
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
5645
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
5646
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
5647
1.61k
        std::unique_ptr<Transaction> txn;
5648
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5649
1.61k
        if (err != TxnErrorCode::TXN_OK) {
5650
0
            LOG_WARNING("failed to create txn").tag("err", err);
5651
0
            return -1;
5652
0
        }
5653
5654
1.61k
        std::string rowset_ref_count_key =
5655
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
5656
1.61k
        int64_t ref_count = 0;
5657
1.61k
        {
5658
1.61k
            std::string value;
5659
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
5660
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
5661
                // This is the old version rowset, we could recycle it directly.
5662
1.60k
                ref_count = 1;
5663
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
5664
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
5665
0
                return -1;
5666
11
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
5667
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
5668
0
                return -1;
5669
0
            }
5670
1.61k
        }
5671
5672
1.61k
        if (ref_count == 1) {
5673
            // It would not be added since it is recycling.
5674
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
5675
1.60k
                LOG_WARNING("failed to delete rowset data");
5676
1.60k
                return -1;
5677
1.60k
            }
5678
5679
            // Reset the transaction to avoid timeout.
5680
10
            err = txn_kv_->create_txn(&txn);
5681
10
            if (err != TxnErrorCode::TXN_OK) {
5682
0
                LOG_WARNING("failed to create txn").tag("err", err);
5683
0
                return -1;
5684
0
            }
5685
10
            txn->remove(rowset_ref_count_key);
5686
10
            LOG_INFO("delete rowset data ref count key")
5687
10
                    .tag("txn_id", rowset_meta.txn_id())
5688
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
5689
5690
10
            std::string dbm_start_key =
5691
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
5692
10
            std::string dbm_end_key = meta_delete_bitmap_key(
5693
10
                    {reference_instance_id, tablet_id, rowset_id,
5694
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
5695
10
            txn->remove(dbm_start_key, dbm_end_key);
5696
10
            LOG_INFO("remove delete bitmap kv")
5697
10
                    .tag("begin", hex(dbm_start_key))
5698
10
                    .tag("end", hex(dbm_end_key));
5699
5700
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
5701
10
                    {reference_instance_id, tablet_id, rowset_id});
5702
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
5703
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
5704
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
5705
10
            LOG_INFO("remove versioned delete bitmap kv")
5706
10
                    .tag("begin", hex(versioned_dbm_start_key))
5707
10
                    .tag("end", hex(versioned_dbm_end_key));
5708
10
        } else {
5709
            // Decrease the rowset ref count.
5710
            //
5711
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
5712
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
5713
3
            txn->atomic_add(rowset_ref_count_key, -1);
5714
3
            LOG_INFO("decrease rowset data ref count")
5715
3
                    .tag("txn_id", rowset_meta.txn_id())
5716
3
                    .tag("ref_count", ref_count - 1)
5717
3
                    .tag("ref_count_key", hex(rowset_ref_count_key));
5718
3
        }
5719
5720
13
        if (!task.versioned_rowset_key.empty()) {
5721
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
5722
0
                                                          task.versionstamp);
5723
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
5724
0
        }
5725
5726
13
        if (!task.non_versioned_rowset_key.empty()) {
5727
0
            txn->remove(task.non_versioned_rowset_key);
5728
0
            LOG_INFO("remove non versioned rowset key")
5729
0
                    .tag("key", hex(task.non_versioned_rowset_key));
5730
0
        }
5731
5732
        // empty when recycle ref rowsets for deleted instance
5733
13
        if (!task.recycle_rowset_key.empty()) {
5734
13
            txn->remove(task.recycle_rowset_key);
5735
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
5736
13
        }
5737
5738
13
        err = txn->commit();
5739
13
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
5740
            // The rowset ref count key has been changed, we need to retry.
5741
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
5742
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
5743
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
5744
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
5745
0
            continue;
5746
13
        } else if (err != TxnErrorCode::TXN_OK) {
5747
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
5748
0
            return -1;
5749
0
        }
5750
13
        LOG_INFO("recycle rowset meta and data success");
5751
13
        return 0;
5752
13
    }
5753
0
    LOG_WARNING("failed to recycle rowset meta and data after retry")
5754
0
            .tag("tablet_id", tablet_id)
5755
0
            .tag("rowset_id", rowset_id)
5756
0
            .tag("retry", MAX_RETRY);
5757
0
    return -1;
5758
1.61k
}
5759
5760
39
int InstanceRecycler::recycle_tmp_rowsets() {
5761
39
    const std::string task_name = "recycle_tmp_rowsets";
5762
39
    int64_t num_scanned = 0;
5763
39
    int64_t num_expired = 0;
5764
39
    std::atomic_long num_recycled = 0;
5765
39
    size_t expired_rowset_size = 0;
5766
39
    size_t total_rowset_key_size = 0;
5767
39
    size_t total_rowset_value_size = 0;
5768
39
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5769
5770
39
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
5771
39
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
5772
39
    std::string tmp_rs_key0;
5773
39
    std::string tmp_rs_key1;
5774
39
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
5775
39
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
5776
5777
39
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
5778
5779
39
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5780
39
    register_recycle_task(task_name, start_time);
5781
5782
39
    DORIS_CLOUD_DEFER {
5783
39
        unregister_recycle_task(task_name);
5784
39
        int64_t cost =
5785
39
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5786
39
        metrics_context.finish_report();
5787
39
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5788
39
                .tag("instance_id", instance_id_)
5789
39
                .tag("num_scanned", num_scanned)
5790
39
                .tag("num_expired", num_expired)
5791
39
                .tag("num_recycled", num_recycled)
5792
39
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5793
39
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5794
39
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5795
39
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
5782
12
    DORIS_CLOUD_DEFER {
5783
12
        unregister_recycle_task(task_name);
5784
12
        int64_t cost =
5785
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5786
12
        metrics_context.finish_report();
5787
12
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5788
12
                .tag("instance_id", instance_id_)
5789
12
                .tag("num_scanned", num_scanned)
5790
12
                .tag("num_expired", num_expired)
5791
12
                .tag("num_recycled", num_recycled)
5792
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5793
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5794
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5795
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
5782
27
    DORIS_CLOUD_DEFER {
5783
27
        unregister_recycle_task(task_name);
5784
27
        int64_t cost =
5785
27
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5786
27
        metrics_context.finish_report();
5787
27
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5788
27
                .tag("instance_id", instance_id_)
5789
27
                .tag("num_scanned", num_scanned)
5790
27
                .tag("num_expired", num_expired)
5791
27
                .tag("num_recycled", num_recycled)
5792
27
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5793
27
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5794
27
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5795
27
    };
5796
5797
    // Elements in `tmp_rowset_keys` has the same lifetime as `it`
5798
5799
39
    std::vector<std::string> tmp_rowset_keys;
5800
39
    std::vector<std::string> tmp_rowset_ref_count_keys;
5801
39
    std::vector<std::string> tmp_rowset_keys_to_mark_recycled;
5802
39
    std::vector<std::string> tmp_rowset_keys_to_abort;
5803
5804
    // rowset_id -> rowset_meta
5805
    // store tmp_rowset id and meta for statistics rs size when delete
5806
39
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
5807
39
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5808
39
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
5809
39
    worker_pool->start();
5810
5811
39
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5812
5813
39
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &tmp_rowsets,
5814
39
                             &expired_rowset_size, &total_rowset_key_size, &total_rowset_value_size,
5815
39
                             &earlest_ts, &tmp_rowset_ref_count_keys,
5816
39
                             &tmp_rowset_keys_to_mark_recycled, &tmp_rowset_keys_to_abort, this,
5817
106k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5818
106k
        ++num_scanned;
5819
106k
        total_rowset_key_size += k.size();
5820
106k
        total_rowset_value_size += v.size();
5821
106k
        doris::RowsetMetaCloudPB rowset;
5822
106k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5823
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5824
0
            return -1;
5825
0
        }
5826
106k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5827
106k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5828
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5829
0
                   << " txn_expiration=" << rowset.txn_expiration()
5830
0
                   << " rowset_creation_time=" << rowset.creation_time();
5831
106k
        int64_t current_time = ::time(nullptr);
5832
106k
        if (current_time < expiration) { // not expired
5833
0
            return 0;
5834
0
        }
5835
5836
106k
        if (config::enable_mark_delete_rowset_before_recycle) {
5837
106k
            if (need_mark_rowset_as_recycled(rowset)) {
5838
52.0k
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
5839
52.0k
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5840
52.0k
                             "at next turn, instance_id="
5841
52.0k
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5842
52.0k
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
5843
52.0k
                return 0;
5844
52.0k
            }
5845
106k
        }
5846
5847
54.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
5848
54.0k
            if (make_deferred_abort_task(rowset).has_value()) {
5849
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5850
3
                             "instance_id="
5851
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5852
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
5853
3
                tmp_rowset_keys_to_abort.emplace_back(k);
5854
3
            }
5855
54.0k
        }
5856
5857
54.0k
        ++num_expired;
5858
54.0k
        expired_rowset_size += v.size();
5859
54.0k
        if (!rowset.has_resource_id()) {
5860
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
5861
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
5862
0
                return -1;
5863
0
            }
5864
            // might be a delete pred rowset
5865
0
            tmp_rowset_keys.emplace_back(k);
5866
0
            return 0;
5867
0
        }
5868
        // TODO(plat1ko): check rowset not referenced
5869
54.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5870
54.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
5871
54.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
5872
54.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
5873
54.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
5874
54.0k
                  << " num_expired=" << num_expired
5875
54.0k
                  << " task_type=" << metrics_context.operation_type;
5876
5877
54.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
5878
        // Remove the rowset ref count key directly since it has not been used.
5879
54.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
5880
54.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
5881
54.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
5882
54.0k
                  << "key=" << hex(rowset_ref_count_key);
5883
54.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
5884
5885
54.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
5886
54.0k
        return 0;
5887
54.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5817
16
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5818
16
        ++num_scanned;
5819
16
        total_rowset_key_size += k.size();
5820
16
        total_rowset_value_size += v.size();
5821
16
        doris::RowsetMetaCloudPB rowset;
5822
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5823
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5824
0
            return -1;
5825
0
        }
5826
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5827
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5828
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5829
0
                   << " txn_expiration=" << rowset.txn_expiration()
5830
0
                   << " rowset_creation_time=" << rowset.creation_time();
5831
16
        int64_t current_time = ::time(nullptr);
5832
16
        if (current_time < expiration) { // not expired
5833
0
            return 0;
5834
0
        }
5835
5836
16
        if (config::enable_mark_delete_rowset_before_recycle) {
5837
16
            if (need_mark_rowset_as_recycled(rowset)) {
5838
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
5839
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5840
9
                             "at next turn, instance_id="
5841
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5842
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
5843
9
                return 0;
5844
9
            }
5845
16
        }
5846
5847
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
5848
7
            if (make_deferred_abort_task(rowset).has_value()) {
5849
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5850
3
                             "instance_id="
5851
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5852
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
5853
3
                tmp_rowset_keys_to_abort.emplace_back(k);
5854
3
            }
5855
7
        }
5856
5857
7
        ++num_expired;
5858
7
        expired_rowset_size += v.size();
5859
7
        if (!rowset.has_resource_id()) {
5860
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
5861
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
5862
0
                return -1;
5863
0
            }
5864
            // might be a delete pred rowset
5865
0
            tmp_rowset_keys.emplace_back(k);
5866
0
            return 0;
5867
0
        }
5868
        // TODO(plat1ko): check rowset not referenced
5869
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5870
7
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
5871
7
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
5872
7
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
5873
7
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
5874
7
                  << " num_expired=" << num_expired
5875
7
                  << " task_type=" << metrics_context.operation_type;
5876
5877
7
        tmp_rowset_keys.emplace_back(k.data(), k.size());
5878
        // Remove the rowset ref count key directly since it has not been used.
5879
7
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
5880
7
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
5881
7
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
5882
7
                  << "key=" << hex(rowset_ref_count_key);
5883
7
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
5884
5885
7
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
5886
7
        return 0;
5887
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5817
106k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5818
106k
        ++num_scanned;
5819
106k
        total_rowset_key_size += k.size();
5820
106k
        total_rowset_value_size += v.size();
5821
106k
        doris::RowsetMetaCloudPB rowset;
5822
106k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5823
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5824
0
            return -1;
5825
0
        }
5826
106k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5827
106k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5828
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5829
0
                   << " txn_expiration=" << rowset.txn_expiration()
5830
0
                   << " rowset_creation_time=" << rowset.creation_time();
5831
106k
        int64_t current_time = ::time(nullptr);
5832
106k
        if (current_time < expiration) { // not expired
5833
0
            return 0;
5834
0
        }
5835
5836
106k
        if (config::enable_mark_delete_rowset_before_recycle) {
5837
106k
            if (need_mark_rowset_as_recycled(rowset)) {
5838
52.0k
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
5839
52.0k
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5840
52.0k
                             "at next turn, instance_id="
5841
52.0k
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5842
52.0k
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
5843
52.0k
                return 0;
5844
52.0k
            }
5845
106k
        }
5846
5847
54.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
5848
54.0k
            if (make_deferred_abort_task(rowset).has_value()) {
5849
0
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5850
0
                             "instance_id="
5851
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5852
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
5853
0
                tmp_rowset_keys_to_abort.emplace_back(k);
5854
0
            }
5855
54.0k
        }
5856
5857
54.0k
        ++num_expired;
5858
54.0k
        expired_rowset_size += v.size();
5859
54.0k
        if (!rowset.has_resource_id()) {
5860
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
5861
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
5862
0
                return -1;
5863
0
            }
5864
            // might be a delete pred rowset
5865
0
            tmp_rowset_keys.emplace_back(k);
5866
0
            return 0;
5867
0
        }
5868
        // TODO(plat1ko): check rowset not referenced
5869
54.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5870
54.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
5871
54.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
5872
54.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
5873
54.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
5874
54.0k
                  << " num_expired=" << num_expired
5875
54.0k
                  << " task_type=" << metrics_context.operation_type;
5876
5877
54.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
5878
        // Remove the rowset ref count key directly since it has not been used.
5879
54.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
5880
54.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
5881
54.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
5882
54.0k
                  << "key=" << hex(rowset_ref_count_key);
5883
54.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
5884
5885
54.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
5886
54.0k
        return 0;
5887
54.0k
    };
5888
5889
    // TODO bacth delete
5890
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5891
51.0k
        std::string dbm_start_key =
5892
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5893
51.0k
        std::string dbm_end_key = dbm_start_key;
5894
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
5895
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5896
51.0k
        if (ret != 0) {
5897
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5898
0
                         << instance_id_ << ", tablet_id=" << tablet_id
5899
0
                         << ", rowset_id=" << rowset_id;
5900
0
        }
5901
51.0k
        return ret;
5902
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5890
7
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5891
7
        std::string dbm_start_key =
5892
7
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5893
7
        std::string dbm_end_key = dbm_start_key;
5894
7
        encode_int64(INT64_MAX, &dbm_end_key);
5895
7
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5896
7
        if (ret != 0) {
5897
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5898
0
                         << instance_id_ << ", tablet_id=" << tablet_id
5899
0
                         << ", rowset_id=" << rowset_id;
5900
0
        }
5901
7
        return ret;
5902
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5890
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5891
51.0k
        std::string dbm_start_key =
5892
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5893
51.0k
        std::string dbm_end_key = dbm_start_key;
5894
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
5895
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5896
51.0k
        if (ret != 0) {
5897
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5898
0
                         << instance_id_ << ", tablet_id=" << tablet_id
5899
0
                         << ", rowset_id=" << rowset_id;
5900
0
        }
5901
51.0k
        return ret;
5902
51.0k
    };
5903
5904
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5905
51.0k
        auto delete_bitmap_start =
5906
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
5907
51.0k
        auto delete_bitmap_end =
5908
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
5909
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
5910
51.0k
        if (ret != 0) {
5911
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
5912
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
5913
0
        }
5914
51.0k
        return ret;
5915
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5904
7
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5905
7
        auto delete_bitmap_start =
5906
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
5907
7
        auto delete_bitmap_end =
5908
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
5909
7
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
5910
7
        if (ret != 0) {
5911
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
5912
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
5913
0
        }
5914
7
        return ret;
5915
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5904
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5905
51.0k
        auto delete_bitmap_start =
5906
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
5907
51.0k
        auto delete_bitmap_end =
5908
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
5909
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
5910
51.0k
        if (ret != 0) {
5911
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
5912
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
5913
0
        }
5914
51.0k
        return ret;
5915
51.0k
    };
5916
5917
39
    auto loop_done = [&]() -> int {
5918
32
        std::vector<std::string> tmp_rowset_keys_to_delete;
5919
32
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
5920
32
        std::vector<std::string> mark_keys_to_process;
5921
32
        std::vector<std::string> abort_keys_to_process;
5922
32
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
5923
32
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
5924
32
        tmp_rowsets_to_delete.swap(tmp_rowsets);
5925
32
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
5926
32
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
5927
32
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
5928
32
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
5929
32
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
5930
32
                             tmp_rowset_ref_count_keys_to_delete =
5931
32
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
5932
32
                             mark_keys_to_process = std::move(mark_keys_to_process),
5933
32
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5934
32
            if (!mark_keys_to_process.empty() &&
5935
32
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
5936
16
                                                                  mark_keys_to_process) != 0) {
5937
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
5938
0
                             << instance_id_;
5939
0
                return;
5940
0
            }
5941
32
            if (!abort_keys_to_process.empty() &&
5942
32
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
5943
3
                                                                      false) != 0) {
5944
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
5945
0
                             << instance_id_;
5946
0
                return;
5947
0
            }
5948
32
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5949
32
                                   metrics_context) != 0) {
5950
3
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5951
3
                return;
5952
3
            }
5953
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5954
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5955
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5956
0
                                 << rs.ShortDebugString();
5957
0
                    return;
5958
0
                }
5959
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5960
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5961
0
                                 << rs.ShortDebugString();
5962
0
                    return;
5963
0
                }
5964
51.0k
            }
5965
29
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5966
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5967
0
                return;
5968
0
            }
5969
29
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5970
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5971
0
                return;
5972
0
            }
5973
29
            num_recycled += tmp_rowset_keys_to_delete.size();
5974
29
            return;
5975
29
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5933
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5934
12
            if (!mark_keys_to_process.empty() &&
5935
12
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
5936
7
                                                                  mark_keys_to_process) != 0) {
5937
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
5938
0
                             << instance_id_;
5939
0
                return;
5940
0
            }
5941
12
            if (!abort_keys_to_process.empty() &&
5942
12
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
5943
3
                                                                      false) != 0) {
5944
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
5945
0
                             << instance_id_;
5946
0
                return;
5947
0
            }
5948
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5949
12
                                   metrics_context) != 0) {
5950
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5951
0
                return;
5952
0
            }
5953
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5954
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5955
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5956
0
                                 << rs.ShortDebugString();
5957
0
                    return;
5958
0
                }
5959
7
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5960
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5961
0
                                 << rs.ShortDebugString();
5962
0
                    return;
5963
0
                }
5964
7
            }
5965
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5966
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5967
0
                return;
5968
0
            }
5969
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5970
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5971
0
                return;
5972
0
            }
5973
12
            num_recycled += tmp_rowset_keys_to_delete.size();
5974
12
            return;
5975
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5933
20
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5934
20
            if (!mark_keys_to_process.empty() &&
5935
20
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
5936
9
                                                                  mark_keys_to_process) != 0) {
5937
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
5938
0
                             << instance_id_;
5939
0
                return;
5940
0
            }
5941
20
            if (!abort_keys_to_process.empty() &&
5942
20
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
5943
0
                                                                      false) != 0) {
5944
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
5945
0
                             << instance_id_;
5946
0
                return;
5947
0
            }
5948
20
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5949
20
                                   metrics_context) != 0) {
5950
3
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5951
3
                return;
5952
3
            }
5953
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5954
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5955
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5956
0
                                 << rs.ShortDebugString();
5957
0
                    return;
5958
0
                }
5959
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5960
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5961
0
                                 << rs.ShortDebugString();
5962
0
                    return;
5963
0
                }
5964
51.0k
            }
5965
17
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5966
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5967
0
                return;
5968
0
            }
5969
17
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5970
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5971
0
                return;
5972
0
            }
5973
17
            num_recycled += tmp_rowset_keys_to_delete.size();
5974
17
            return;
5975
17
        });
5976
32
        return 0;
5977
32
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEv
Line
Count
Source
5917
12
    auto loop_done = [&]() -> int {
5918
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
5919
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
5920
12
        std::vector<std::string> mark_keys_to_process;
5921
12
        std::vector<std::string> abort_keys_to_process;
5922
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
5923
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
5924
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
5925
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
5926
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
5927
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
5928
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
5929
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
5930
12
                             tmp_rowset_ref_count_keys_to_delete =
5931
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
5932
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
5933
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5934
12
            if (!mark_keys_to_process.empty() &&
5935
12
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
5936
12
                                                                  mark_keys_to_process) != 0) {
5937
12
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
5938
12
                             << instance_id_;
5939
12
                return;
5940
12
            }
5941
12
            if (!abort_keys_to_process.empty() &&
5942
12
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
5943
12
                                                                      false) != 0) {
5944
12
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
5945
12
                             << instance_id_;
5946
12
                return;
5947
12
            }
5948
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5949
12
                                   metrics_context) != 0) {
5950
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5951
12
                return;
5952
12
            }
5953
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5954
12
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5955
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5956
12
                                 << rs.ShortDebugString();
5957
12
                    return;
5958
12
                }
5959
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5960
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5961
12
                                 << rs.ShortDebugString();
5962
12
                    return;
5963
12
                }
5964
12
            }
5965
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5966
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5967
12
                return;
5968
12
            }
5969
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5970
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5971
12
                return;
5972
12
            }
5973
12
            num_recycled += tmp_rowset_keys_to_delete.size();
5974
12
            return;
5975
12
        });
5976
12
        return 0;
5977
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEv
Line
Count
Source
5917
20
    auto loop_done = [&]() -> int {
5918
20
        std::vector<std::string> tmp_rowset_keys_to_delete;
5919
20
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
5920
20
        std::vector<std::string> mark_keys_to_process;
5921
20
        std::vector<std::string> abort_keys_to_process;
5922
20
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
5923
20
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
5924
20
        tmp_rowsets_to_delete.swap(tmp_rowsets);
5925
20
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
5926
20
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
5927
20
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
5928
20
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
5929
20
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
5930
20
                             tmp_rowset_ref_count_keys_to_delete =
5931
20
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
5932
20
                             mark_keys_to_process = std::move(mark_keys_to_process),
5933
20
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5934
20
            if (!mark_keys_to_process.empty() &&
5935
20
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
5936
20
                                                                  mark_keys_to_process) != 0) {
5937
20
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
5938
20
                             << instance_id_;
5939
20
                return;
5940
20
            }
5941
20
            if (!abort_keys_to_process.empty() &&
5942
20
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
5943
20
                                                                      false) != 0) {
5944
20
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
5945
20
                             << instance_id_;
5946
20
                return;
5947
20
            }
5948
20
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5949
20
                                   metrics_context) != 0) {
5950
20
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5951
20
                return;
5952
20
            }
5953
20
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5954
20
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5955
20
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5956
20
                                 << rs.ShortDebugString();
5957
20
                    return;
5958
20
                }
5959
20
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5960
20
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5961
20
                                 << rs.ShortDebugString();
5962
20
                    return;
5963
20
                }
5964
20
            }
5965
20
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5966
20
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5967
20
                return;
5968
20
            }
5969
20
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5970
20
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5971
20
                return;
5972
20
            }
5973
20
            num_recycled += tmp_rowset_keys_to_delete.size();
5974
20
            return;
5975
20
        });
5976
20
        return 0;
5977
20
    };
5978
5979
39
    if (config::enable_recycler_stats_metrics) {
5980
0
        scan_and_statistics_tmp_rowsets();
5981
0
    }
5982
    // recycle_func and loop_done for scan and recycle
5983
39
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
5984
39
                               std::move(loop_done));
5985
5986
39
    worker_pool->stop();
5987
5988
    // Report final metrics after all concurrent tasks completed
5989
39
    segment_metrics_context_.report();
5990
39
    metrics_context.report();
5991
5992
39
    return ret;
5993
39
}
5994
5995
int InstanceRecycler::scan_and_recycle(
5996
        std::string begin, std::string_view end,
5997
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
5998
271
        std::function<int()> loop_done) {
5999
271
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
6000
271
    int ret = 0;
6001
271
    int64_t cnt = 0;
6002
271
    int get_range_retried = 0;
6003
271
    std::string err;
6004
271
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6005
271
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6006
271
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6007
271
                  << " ret=" << ret << " err=" << err;
6008
271
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
6004
31
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6005
31
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6006
31
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6007
31
                  << " ret=" << ret << " err=" << err;
6008
31
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
6004
240
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6005
240
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6006
240
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6007
240
                  << " ret=" << ret << " err=" << err;
6008
240
    };
6009
6010
271
    std::unique_ptr<RangeGetIterator> it;
6011
454
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
6012
323
        if (get_range_retried > 1000) {
6013
0
            err = "txn_get exceeds max retry(1000), may not scan all keys";
6014
0
            ret = -3;
6015
0
            return ret;
6016
0
        }
6017
323
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
6018
323
        if (get_ret != 0) { // txn kv may complain "Request for future version"
6019
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
6020
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
6021
0
                         << " get_range_retried=" << get_range_retried;
6022
0
            ++get_range_retried;
6023
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6024
0
            continue; // try again
6025
0
        }
6026
323
        if (!it->has_next()) {
6027
140
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
6028
140
            break; // scan finished
6029
140
        }
6030
154k
        while (it->has_next()) {
6031
154k
            ++cnt;
6032
            // recycle corresponding resources
6033
154k
            auto [k, v] = it->next();
6034
154k
            if (!it->has_next()) {
6035
184
                begin = k;
6036
184
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
6037
184
            }
6038
            // FIXME(gavin): if we want to continue scanning, the recycle_func should not return non-zero
6039
154k
            if (recycle_func(k, v) != 0) {
6040
4.00k
                err = "recycle_func error";
6041
4.00k
                ret = -1;
6042
4.00k
            }
6043
154k
        }
6044
183
        begin.push_back('\x00'); // Update to next smallest key for iteration
6045
        // FIXME(gavin): if we want to continue scanning, the loop_done should not return non-zero
6046
183
        if (loop_done && loop_done() != 0) {
6047
5
            err = "loop_done error";
6048
5
            ret = -1;
6049
5
        }
6050
183
    }
6051
271
    return ret;
6052
271
}
6053
6054
19
int InstanceRecycler::abort_timeout_txn() {
6055
19
    const std::string task_name = "abort_timeout_txn";
6056
19
    int64_t num_scanned = 0;
6057
19
    int64_t num_timeout = 0;
6058
19
    int64_t num_abort = 0;
6059
19
    int64_t num_advance = 0;
6060
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6061
6062
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6063
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6064
19
    std::string begin_txn_running_key;
6065
19
    std::string end_txn_running_key;
6066
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6067
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6068
6069
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
6070
6071
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6072
19
    register_recycle_task(task_name, start_time);
6073
6074
19
    DORIS_CLOUD_DEFER {
6075
19
        unregister_recycle_task(task_name);
6076
19
        int64_t cost =
6077
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6078
19
        metrics_context.finish_report();
6079
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6080
19
                .tag("instance_id", instance_id_)
6081
19
                .tag("num_scanned", num_scanned)
6082
19
                .tag("num_timeout", num_timeout)
6083
19
                .tag("num_abort", num_abort)
6084
19
                .tag("num_advance", num_advance);
6085
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6074
3
    DORIS_CLOUD_DEFER {
6075
3
        unregister_recycle_task(task_name);
6076
3
        int64_t cost =
6077
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6078
3
        metrics_context.finish_report();
6079
3
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6080
3
                .tag("instance_id", instance_id_)
6081
3
                .tag("num_scanned", num_scanned)
6082
3
                .tag("num_timeout", num_timeout)
6083
3
                .tag("num_abort", num_abort)
6084
3
                .tag("num_advance", num_advance);
6085
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6074
16
    DORIS_CLOUD_DEFER {
6075
16
        unregister_recycle_task(task_name);
6076
16
        int64_t cost =
6077
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6078
16
        metrics_context.finish_report();
6079
16
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6080
16
                .tag("instance_id", instance_id_)
6081
16
                .tag("num_scanned", num_scanned)
6082
16
                .tag("num_timeout", num_timeout)
6083
16
                .tag("num_abort", num_abort)
6084
16
                .tag("num_advance", num_advance);
6085
16
    };
6086
6087
19
    int64_t current_time =
6088
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6089
6090
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
6091
19
                                  &current_time, &metrics_context,
6092
19
                                  this](std::string_view k, std::string_view v) -> int {
6093
9
        ++num_scanned;
6094
6095
9
        std::unique_ptr<Transaction> txn;
6096
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6097
9
        if (err != TxnErrorCode::TXN_OK) {
6098
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6099
0
            return -1;
6100
0
        }
6101
9
        std::string_view k1 = k;
6102
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6103
9
        k1.remove_prefix(1); // Remove key space
6104
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6105
9
        if (decode_key(&k1, &out) != 0) {
6106
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6107
0
            return -1;
6108
0
        }
6109
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6110
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6111
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6112
        // Update txn_info
6113
9
        std::string txn_inf_key, txn_inf_val;
6114
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6115
9
        err = txn->get(txn_inf_key, &txn_inf_val);
6116
9
        if (err != TxnErrorCode::TXN_OK) {
6117
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6118
0
            return -1;
6119
0
        }
6120
9
        TxnInfoPB txn_info;
6121
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
6122
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6123
0
            return -1;
6124
0
        }
6125
6126
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6127
3
            txn.reset();
6128
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6129
3
            std::shared_ptr<TxnLazyCommitTask> task =
6130
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6131
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6132
3
            if (ret.first != MetaServiceCode::OK) {
6133
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6134
0
                             << "msg=" << ret.second;
6135
0
                return -1;
6136
0
            }
6137
3
            ++num_advance;
6138
3
            return 0;
6139
6
        } else {
6140
6
            TxnRunningPB txn_running_pb;
6141
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6142
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6143
0
                return -1;
6144
0
            }
6145
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6146
4
                return 0;
6147
4
            }
6148
2
            ++num_timeout;
6149
6150
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6151
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6152
2
            txn_info.set_finish_time(current_time);
6153
2
            txn_info.set_reason("timeout");
6154
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6155
2
            txn_inf_val.clear();
6156
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6157
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6158
0
                return -1;
6159
0
            }
6160
2
            txn->put(txn_inf_key, txn_inf_val);
6161
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6162
            // Put recycle txn key
6163
2
            std::string recyc_txn_key, recyc_txn_val;
6164
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6165
2
            RecycleTxnPB recycle_txn_pb;
6166
2
            recycle_txn_pb.set_creation_time(current_time);
6167
2
            recycle_txn_pb.set_label(txn_info.label());
6168
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6169
0
                LOG_WARNING("failed to serialize txn recycle info")
6170
0
                        .tag("key", hex(k))
6171
0
                        .tag("db_id", db_id)
6172
0
                        .tag("txn_id", txn_id);
6173
0
                return -1;
6174
0
            }
6175
2
            txn->put(recyc_txn_key, recyc_txn_val);
6176
            // Remove txn running key
6177
2
            txn->remove(k);
6178
2
            err = txn->commit();
6179
2
            if (err != TxnErrorCode::TXN_OK) {
6180
0
                LOG_WARNING("failed to commit txn err={}", err)
6181
0
                        .tag("key", hex(k))
6182
0
                        .tag("db_id", db_id)
6183
0
                        .tag("txn_id", txn_id);
6184
0
                return -1;
6185
0
            }
6186
2
            metrics_context.total_recycled_num = ++num_abort;
6187
2
            metrics_context.report();
6188
2
        }
6189
6190
2
        return 0;
6191
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6092
3
                                  this](std::string_view k, std::string_view v) -> int {
6093
3
        ++num_scanned;
6094
6095
3
        std::unique_ptr<Transaction> txn;
6096
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6097
3
        if (err != TxnErrorCode::TXN_OK) {
6098
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6099
0
            return -1;
6100
0
        }
6101
3
        std::string_view k1 = k;
6102
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6103
3
        k1.remove_prefix(1); // Remove key space
6104
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6105
3
        if (decode_key(&k1, &out) != 0) {
6106
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6107
0
            return -1;
6108
0
        }
6109
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6110
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6111
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6112
        // Update txn_info
6113
3
        std::string txn_inf_key, txn_inf_val;
6114
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6115
3
        err = txn->get(txn_inf_key, &txn_inf_val);
6116
3
        if (err != TxnErrorCode::TXN_OK) {
6117
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6118
0
            return -1;
6119
0
        }
6120
3
        TxnInfoPB txn_info;
6121
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
6122
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6123
0
            return -1;
6124
0
        }
6125
6126
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6127
3
            txn.reset();
6128
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6129
3
            std::shared_ptr<TxnLazyCommitTask> task =
6130
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6131
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6132
3
            if (ret.first != MetaServiceCode::OK) {
6133
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6134
0
                             << "msg=" << ret.second;
6135
0
                return -1;
6136
0
            }
6137
3
            ++num_advance;
6138
3
            return 0;
6139
3
        } else {
6140
0
            TxnRunningPB txn_running_pb;
6141
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6142
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6143
0
                return -1;
6144
0
            }
6145
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6146
0
                return 0;
6147
0
            }
6148
0
            ++num_timeout;
6149
6150
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6151
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6152
0
            txn_info.set_finish_time(current_time);
6153
0
            txn_info.set_reason("timeout");
6154
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6155
0
            txn_inf_val.clear();
6156
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6157
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6158
0
                return -1;
6159
0
            }
6160
0
            txn->put(txn_inf_key, txn_inf_val);
6161
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6162
            // Put recycle txn key
6163
0
            std::string recyc_txn_key, recyc_txn_val;
6164
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6165
0
            RecycleTxnPB recycle_txn_pb;
6166
0
            recycle_txn_pb.set_creation_time(current_time);
6167
0
            recycle_txn_pb.set_label(txn_info.label());
6168
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6169
0
                LOG_WARNING("failed to serialize txn recycle info")
6170
0
                        .tag("key", hex(k))
6171
0
                        .tag("db_id", db_id)
6172
0
                        .tag("txn_id", txn_id);
6173
0
                return -1;
6174
0
            }
6175
0
            txn->put(recyc_txn_key, recyc_txn_val);
6176
            // Remove txn running key
6177
0
            txn->remove(k);
6178
0
            err = txn->commit();
6179
0
            if (err != TxnErrorCode::TXN_OK) {
6180
0
                LOG_WARNING("failed to commit txn err={}", err)
6181
0
                        .tag("key", hex(k))
6182
0
                        .tag("db_id", db_id)
6183
0
                        .tag("txn_id", txn_id);
6184
0
                return -1;
6185
0
            }
6186
0
            metrics_context.total_recycled_num = ++num_abort;
6187
0
            metrics_context.report();
6188
0
        }
6189
6190
0
        return 0;
6191
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6092
6
                                  this](std::string_view k, std::string_view v) -> int {
6093
6
        ++num_scanned;
6094
6095
6
        std::unique_ptr<Transaction> txn;
6096
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6097
6
        if (err != TxnErrorCode::TXN_OK) {
6098
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6099
0
            return -1;
6100
0
        }
6101
6
        std::string_view k1 = k;
6102
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6103
6
        k1.remove_prefix(1); // Remove key space
6104
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6105
6
        if (decode_key(&k1, &out) != 0) {
6106
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6107
0
            return -1;
6108
0
        }
6109
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6110
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6111
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6112
        // Update txn_info
6113
6
        std::string txn_inf_key, txn_inf_val;
6114
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6115
6
        err = txn->get(txn_inf_key, &txn_inf_val);
6116
6
        if (err != TxnErrorCode::TXN_OK) {
6117
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6118
0
            return -1;
6119
0
        }
6120
6
        TxnInfoPB txn_info;
6121
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
6122
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6123
0
            return -1;
6124
0
        }
6125
6126
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6127
0
            txn.reset();
6128
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6129
0
            std::shared_ptr<TxnLazyCommitTask> task =
6130
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6131
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6132
0
            if (ret.first != MetaServiceCode::OK) {
6133
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6134
0
                             << "msg=" << ret.second;
6135
0
                return -1;
6136
0
            }
6137
0
            ++num_advance;
6138
0
            return 0;
6139
6
        } else {
6140
6
            TxnRunningPB txn_running_pb;
6141
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6142
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6143
0
                return -1;
6144
0
            }
6145
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6146
4
                return 0;
6147
4
            }
6148
2
            ++num_timeout;
6149
6150
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6151
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6152
2
            txn_info.set_finish_time(current_time);
6153
2
            txn_info.set_reason("timeout");
6154
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6155
2
            txn_inf_val.clear();
6156
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6157
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6158
0
                return -1;
6159
0
            }
6160
2
            txn->put(txn_inf_key, txn_inf_val);
6161
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6162
            // Put recycle txn key
6163
2
            std::string recyc_txn_key, recyc_txn_val;
6164
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6165
2
            RecycleTxnPB recycle_txn_pb;
6166
2
            recycle_txn_pb.set_creation_time(current_time);
6167
2
            recycle_txn_pb.set_label(txn_info.label());
6168
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6169
0
                LOG_WARNING("failed to serialize txn recycle info")
6170
0
                        .tag("key", hex(k))
6171
0
                        .tag("db_id", db_id)
6172
0
                        .tag("txn_id", txn_id);
6173
0
                return -1;
6174
0
            }
6175
2
            txn->put(recyc_txn_key, recyc_txn_val);
6176
            // Remove txn running key
6177
2
            txn->remove(k);
6178
2
            err = txn->commit();
6179
2
            if (err != TxnErrorCode::TXN_OK) {
6180
0
                LOG_WARNING("failed to commit txn err={}", err)
6181
0
                        .tag("key", hex(k))
6182
0
                        .tag("db_id", db_id)
6183
0
                        .tag("txn_id", txn_id);
6184
0
                return -1;
6185
0
            }
6186
2
            metrics_context.total_recycled_num = ++num_abort;
6187
2
            metrics_context.report();
6188
2
        }
6189
6190
2
        return 0;
6191
6
    };
6192
6193
19
    if (config::enable_recycler_stats_metrics) {
6194
0
        scan_and_statistics_abort_timeout_txn();
6195
0
    }
6196
    // recycle_func and loop_done for scan and recycle
6197
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
6198
19
                            std::move(handle_txn_running_kv));
6199
19
}
6200
6201
19
int InstanceRecycler::recycle_expired_txn_label() {
6202
19
    const std::string task_name = "recycle_expired_txn_label";
6203
19
    int64_t num_scanned = 0;
6204
19
    int64_t num_expired = 0;
6205
19
    std::atomic_long num_recycled = 0;
6206
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6207
19
    int ret = 0;
6208
6209
19
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
6210
19
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6211
19
    std::string begin_recycle_txn_key;
6212
19
    std::string end_recycle_txn_key;
6213
19
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
6214
19
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
6215
19
    std::vector<std::string> recycle_txn_info_keys;
6216
6217
19
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
6218
6219
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6220
19
    register_recycle_task(task_name, start_time);
6221
19
    DORIS_CLOUD_DEFER {
6222
19
        unregister_recycle_task(task_name);
6223
19
        int64_t cost =
6224
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6225
19
        metrics_context.finish_report();
6226
19
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6227
19
                .tag("instance_id", instance_id_)
6228
19
                .tag("num_scanned", num_scanned)
6229
19
                .tag("num_expired", num_expired)
6230
19
                .tag("num_recycled", num_recycled);
6231
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6221
1
    DORIS_CLOUD_DEFER {
6222
1
        unregister_recycle_task(task_name);
6223
1
        int64_t cost =
6224
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6225
1
        metrics_context.finish_report();
6226
1
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6227
1
                .tag("instance_id", instance_id_)
6228
1
                .tag("num_scanned", num_scanned)
6229
1
                .tag("num_expired", num_expired)
6230
1
                .tag("num_recycled", num_recycled);
6231
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6221
18
    DORIS_CLOUD_DEFER {
6222
18
        unregister_recycle_task(task_name);
6223
18
        int64_t cost =
6224
18
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6225
18
        metrics_context.finish_report();
6226
18
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6227
18
                .tag("instance_id", instance_id_)
6228
18
                .tag("num_scanned", num_scanned)
6229
18
                .tag("num_expired", num_expired)
6230
18
                .tag("num_recycled", num_recycled);
6231
18
    };
6232
6233
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6234
6235
19
    SyncExecutor<int> concurrent_delete_executor(
6236
19
            _thread_pool_group.s3_producer_pool,
6237
19
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
6238
23.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
6238
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
6238
23.0k
            [](const int& ret) { return ret != 0; });
6239
6240
19
    int64_t current_time_ms =
6241
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6242
6243
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6244
30.0k
        ++num_scanned;
6245
30.0k
        RecycleTxnPB recycle_txn_pb;
6246
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6247
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6248
0
            return -1;
6249
0
        }
6250
30.0k
        if ((config::force_immediate_recycle) ||
6251
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6252
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6253
30.0k
             current_time_ms)) {
6254
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6255
23.0k
            num_expired++;
6256
23.0k
            recycle_txn_info_keys.emplace_back(k);
6257
23.0k
        }
6258
30.0k
        return 0;
6259
30.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6243
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6244
1
        ++num_scanned;
6245
1
        RecycleTxnPB recycle_txn_pb;
6246
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6247
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6248
0
            return -1;
6249
0
        }
6250
1
        if ((config::force_immediate_recycle) ||
6251
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6252
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6253
1
             current_time_ms)) {
6254
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6255
1
            num_expired++;
6256
1
            recycle_txn_info_keys.emplace_back(k);
6257
1
        }
6258
1
        return 0;
6259
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6243
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6244
30.0k
        ++num_scanned;
6245
30.0k
        RecycleTxnPB recycle_txn_pb;
6246
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6247
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6248
0
            return -1;
6249
0
        }
6250
30.0k
        if ((config::force_immediate_recycle) ||
6251
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6252
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6253
30.0k
             current_time_ms)) {
6254
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6255
23.0k
            num_expired++;
6256
23.0k
            recycle_txn_info_keys.emplace_back(k);
6257
23.0k
        }
6258
30.0k
        return 0;
6259
30.0k
    };
6260
6261
    // int 0 for success, 1 for conflict, -1 for error
6262
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6263
23.0k
        std::string_view k1 = k;
6264
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6265
23.0k
        k1.remove_prefix(1); // Remove key space
6266
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6267
23.0k
        int ret = decode_key(&k1, &out);
6268
23.0k
        if (ret != 0) {
6269
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6270
0
            return -1;
6271
0
        }
6272
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6273
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6274
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6275
23.0k
        std::unique_ptr<Transaction> txn;
6276
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6277
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6278
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6279
0
            return -1;
6280
0
        }
6281
        // Remove txn index kv
6282
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6283
23.0k
        txn->remove(index_key);
6284
        // Remove txn info kv
6285
23.0k
        std::string info_key, info_val;
6286
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6287
23.0k
        err = txn->get(info_key, &info_val);
6288
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6289
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6290
0
            return -1;
6291
0
        }
6292
23.0k
        TxnInfoPB txn_info;
6293
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6294
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6295
0
            return -1;
6296
0
        }
6297
23.0k
        txn->remove(info_key);
6298
        // Remove sub txn index kvs
6299
23.0k
        std::vector<std::string> sub_txn_index_keys;
6300
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6301
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6302
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6303
22.9k
        }
6304
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6305
22.9k
            txn->remove(sub_txn_index_key);
6306
22.9k
        }
6307
        // Update txn label
6308
23.0k
        std::string label_key, label_val;
6309
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6310
23.0k
        err = txn->get(label_key, &label_val);
6311
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6312
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6313
0
                         << " err=" << err;
6314
0
            return -1;
6315
0
        }
6316
23.0k
        TxnLabelPB txn_label;
6317
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6318
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6319
0
            return -1;
6320
0
        }
6321
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6322
23.0k
        if (it != txn_label.txn_ids().end()) {
6323
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6324
23.0k
        }
6325
23.0k
        if (txn_label.txn_ids().empty()) {
6326
23.0k
            txn->remove(label_key);
6327
23.0k
            TEST_SYNC_POINT_CALLBACK(
6328
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6329
23.0k
        } else {
6330
73
            if (!txn_label.SerializeToString(&label_val)) {
6331
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6332
0
                return -1;
6333
0
            }
6334
73
            TEST_SYNC_POINT_CALLBACK(
6335
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6336
73
            txn->atomic_set_ver_value(label_key, label_val);
6337
73
            TEST_SYNC_POINT_CALLBACK(
6338
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6339
73
        }
6340
        // Remove recycle txn kv
6341
23.0k
        txn->remove(k);
6342
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6343
23.0k
        err = txn->commit();
6344
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6345
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6346
62
                TEST_SYNC_POINT_CALLBACK(
6347
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6348
                // log the txn_id and label
6349
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6350
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6351
62
                             << " txn_label=" << txn_info.label();
6352
62
                return 1;
6353
62
            }
6354
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6355
0
            return -1;
6356
62
        }
6357
23.0k
        ++num_recycled;
6358
6359
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6360
23.0k
        return 0;
6361
23.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6262
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6263
1
        std::string_view k1 = k;
6264
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6265
1
        k1.remove_prefix(1); // Remove key space
6266
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6267
1
        int ret = decode_key(&k1, &out);
6268
1
        if (ret != 0) {
6269
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6270
0
            return -1;
6271
0
        }
6272
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6273
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6274
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6275
1
        std::unique_ptr<Transaction> txn;
6276
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6277
1
        if (err != TxnErrorCode::TXN_OK) {
6278
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6279
0
            return -1;
6280
0
        }
6281
        // Remove txn index kv
6282
1
        auto index_key = txn_index_key({instance_id_, txn_id});
6283
1
        txn->remove(index_key);
6284
        // Remove txn info kv
6285
1
        std::string info_key, info_val;
6286
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6287
1
        err = txn->get(info_key, &info_val);
6288
1
        if (err != TxnErrorCode::TXN_OK) {
6289
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6290
0
            return -1;
6291
0
        }
6292
1
        TxnInfoPB txn_info;
6293
1
        if (!txn_info.ParseFromString(info_val)) {
6294
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6295
0
            return -1;
6296
0
        }
6297
1
        txn->remove(info_key);
6298
        // Remove sub txn index kvs
6299
1
        std::vector<std::string> sub_txn_index_keys;
6300
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6301
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6302
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
6303
0
        }
6304
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6305
0
            txn->remove(sub_txn_index_key);
6306
0
        }
6307
        // Update txn label
6308
1
        std::string label_key, label_val;
6309
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6310
1
        err = txn->get(label_key, &label_val);
6311
1
        if (err != TxnErrorCode::TXN_OK) {
6312
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6313
0
                         << " err=" << err;
6314
0
            return -1;
6315
0
        }
6316
1
        TxnLabelPB txn_label;
6317
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6318
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6319
0
            return -1;
6320
0
        }
6321
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6322
1
        if (it != txn_label.txn_ids().end()) {
6323
1
            txn_label.mutable_txn_ids()->erase(it);
6324
1
        }
6325
1
        if (txn_label.txn_ids().empty()) {
6326
1
            txn->remove(label_key);
6327
1
            TEST_SYNC_POINT_CALLBACK(
6328
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6329
1
        } else {
6330
0
            if (!txn_label.SerializeToString(&label_val)) {
6331
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6332
0
                return -1;
6333
0
            }
6334
0
            TEST_SYNC_POINT_CALLBACK(
6335
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6336
0
            txn->atomic_set_ver_value(label_key, label_val);
6337
0
            TEST_SYNC_POINT_CALLBACK(
6338
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6339
0
        }
6340
        // Remove recycle txn kv
6341
1
        txn->remove(k);
6342
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6343
1
        err = txn->commit();
6344
1
        if (err != TxnErrorCode::TXN_OK) {
6345
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
6346
0
                TEST_SYNC_POINT_CALLBACK(
6347
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6348
                // log the txn_id and label
6349
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6350
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6351
0
                             << " txn_label=" << txn_info.label();
6352
0
                return 1;
6353
0
            }
6354
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6355
0
            return -1;
6356
0
        }
6357
1
        ++num_recycled;
6358
6359
1
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6360
1
        return 0;
6361
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6262
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6263
23.0k
        std::string_view k1 = k;
6264
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6265
23.0k
        k1.remove_prefix(1); // Remove key space
6266
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6267
23.0k
        int ret = decode_key(&k1, &out);
6268
23.0k
        if (ret != 0) {
6269
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6270
0
            return -1;
6271
0
        }
6272
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6273
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6274
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6275
23.0k
        std::unique_ptr<Transaction> txn;
6276
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6277
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6278
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6279
0
            return -1;
6280
0
        }
6281
        // Remove txn index kv
6282
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6283
23.0k
        txn->remove(index_key);
6284
        // Remove txn info kv
6285
23.0k
        std::string info_key, info_val;
6286
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6287
23.0k
        err = txn->get(info_key, &info_val);
6288
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6289
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6290
0
            return -1;
6291
0
        }
6292
23.0k
        TxnInfoPB txn_info;
6293
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6294
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6295
0
            return -1;
6296
0
        }
6297
23.0k
        txn->remove(info_key);
6298
        // Remove sub txn index kvs
6299
23.0k
        std::vector<std::string> sub_txn_index_keys;
6300
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6301
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6302
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6303
22.9k
        }
6304
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6305
22.9k
            txn->remove(sub_txn_index_key);
6306
22.9k
        }
6307
        // Update txn label
6308
23.0k
        std::string label_key, label_val;
6309
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6310
23.0k
        err = txn->get(label_key, &label_val);
6311
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6312
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6313
0
                         << " err=" << err;
6314
0
            return -1;
6315
0
        }
6316
23.0k
        TxnLabelPB txn_label;
6317
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6318
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6319
0
            return -1;
6320
0
        }
6321
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6322
23.0k
        if (it != txn_label.txn_ids().end()) {
6323
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6324
23.0k
        }
6325
23.0k
        if (txn_label.txn_ids().empty()) {
6326
23.0k
            txn->remove(label_key);
6327
23.0k
            TEST_SYNC_POINT_CALLBACK(
6328
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6329
23.0k
        } else {
6330
73
            if (!txn_label.SerializeToString(&label_val)) {
6331
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6332
0
                return -1;
6333
0
            }
6334
73
            TEST_SYNC_POINT_CALLBACK(
6335
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6336
73
            txn->atomic_set_ver_value(label_key, label_val);
6337
73
            TEST_SYNC_POINT_CALLBACK(
6338
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6339
73
        }
6340
        // Remove recycle txn kv
6341
23.0k
        txn->remove(k);
6342
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6343
23.0k
        err = txn->commit();
6344
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6345
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6346
62
                TEST_SYNC_POINT_CALLBACK(
6347
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6348
                // log the txn_id and label
6349
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6350
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6351
62
                             << " txn_label=" << txn_info.label();
6352
62
                return 1;
6353
62
            }
6354
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6355
0
            return -1;
6356
62
        }
6357
23.0k
        ++num_recycled;
6358
6359
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6360
23.0k
        return 0;
6361
23.0k
    };
6362
6363
19
    auto loop_done = [&]() -> int {
6364
10
        DORIS_CLOUD_DEFER {
6365
10
            recycle_txn_info_keys.clear();
6366
10
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6364
1
        DORIS_CLOUD_DEFER {
6365
1
            recycle_txn_info_keys.clear();
6366
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6364
9
        DORIS_CLOUD_DEFER {
6365
9
            recycle_txn_info_keys.clear();
6366
9
        };
6367
10
        TEST_SYNC_POINT_CALLBACK(
6368
10
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6369
10
                &recycle_txn_info_keys);
6370
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6371
23.0k
            concurrent_delete_executor.add([&]() {
6372
23.0k
                int ret = delete_recycle_txn_kv(k);
6373
23.0k
                if (ret == 1) {
6374
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6375
54
                    for (int i = 1; i <= max_retry; ++i) {
6376
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6377
54
                        ret = delete_recycle_txn_kv(k);
6378
                        // clang-format off
6379
54
                        TEST_SYNC_POINT_CALLBACK(
6380
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6381
                        // clang-format off
6382
54
                        if (ret != 1) {
6383
18
                            break;
6384
18
                        }
6385
                        // random sleep 0-100 ms to retry
6386
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6387
36
                    }
6388
18
                }
6389
23.0k
                if (ret != 0) {
6390
9
                    LOG_WARNING("failed to delete recycle txn kv")
6391
9
                            .tag("instance id", instance_id_)
6392
9
                            .tag("key", hex(k));
6393
9
                    return -1;
6394
9
                }
6395
23.0k
                return 0;
6396
23.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6371
1
            concurrent_delete_executor.add([&]() {
6372
1
                int ret = delete_recycle_txn_kv(k);
6373
1
                if (ret == 1) {
6374
0
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6375
0
                    for (int i = 1; i <= max_retry; ++i) {
6376
0
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6377
0
                        ret = delete_recycle_txn_kv(k);
6378
                        // clang-format off
6379
0
                        TEST_SYNC_POINT_CALLBACK(
6380
0
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6381
                        // clang-format off
6382
0
                        if (ret != 1) {
6383
0
                            break;
6384
0
                        }
6385
                        // random sleep 0-100 ms to retry
6386
0
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6387
0
                    }
6388
0
                }
6389
1
                if (ret != 0) {
6390
0
                    LOG_WARNING("failed to delete recycle txn kv")
6391
0
                            .tag("instance id", instance_id_)
6392
0
                            .tag("key", hex(k));
6393
0
                    return -1;
6394
0
                }
6395
1
                return 0;
6396
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6371
23.0k
            concurrent_delete_executor.add([&]() {
6372
23.0k
                int ret = delete_recycle_txn_kv(k);
6373
23.0k
                if (ret == 1) {
6374
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6375
54
                    for (int i = 1; i <= max_retry; ++i) {
6376
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6377
54
                        ret = delete_recycle_txn_kv(k);
6378
                        // clang-format off
6379
54
                        TEST_SYNC_POINT_CALLBACK(
6380
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6381
                        // clang-format off
6382
54
                        if (ret != 1) {
6383
18
                            break;
6384
18
                        }
6385
                        // random sleep 0-100 ms to retry
6386
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6387
36
                    }
6388
18
                }
6389
23.0k
                if (ret != 0) {
6390
9
                    LOG_WARNING("failed to delete recycle txn kv")
6391
9
                            .tag("instance id", instance_id_)
6392
9
                            .tag("key", hex(k));
6393
9
                    return -1;
6394
9
                }
6395
23.0k
                return 0;
6396
23.0k
            });
6397
23.0k
        }
6398
10
        bool finished = true;
6399
10
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6400
23.0k
        for (int r : rets) {
6401
23.0k
            if (r != 0) {
6402
9
                ret = -1;
6403
9
            }
6404
23.0k
        }
6405
6406
10
        ret = finished ? ret : -1;
6407
6408
        // Update metrics after all concurrent tasks completed
6409
10
        metrics_context.total_recycled_num = num_recycled.load();
6410
10
        metrics_context.report();
6411
6412
10
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6413
6414
10
        if (ret != 0) {
6415
3
            LOG_WARNING("recycle txn kv ret!=0")
6416
3
                    .tag("finished", finished)
6417
3
                    .tag("ret", ret)
6418
3
                    .tag("instance_id", instance_id_);
6419
3
            return ret;
6420
3
        }
6421
7
        return ret;
6422
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6363
1
    auto loop_done = [&]() -> int {
6364
1
        DORIS_CLOUD_DEFER {
6365
1
            recycle_txn_info_keys.clear();
6366
1
        };
6367
1
        TEST_SYNC_POINT_CALLBACK(
6368
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6369
1
                &recycle_txn_info_keys);
6370
1
        for (const auto& k : recycle_txn_info_keys) {
6371
1
            concurrent_delete_executor.add([&]() {
6372
1
                int ret = delete_recycle_txn_kv(k);
6373
1
                if (ret == 1) {
6374
1
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6375
1
                    for (int i = 1; i <= max_retry; ++i) {
6376
1
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6377
1
                        ret = delete_recycle_txn_kv(k);
6378
                        // clang-format off
6379
1
                        TEST_SYNC_POINT_CALLBACK(
6380
1
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6381
                        // clang-format off
6382
1
                        if (ret != 1) {
6383
1
                            break;
6384
1
                        }
6385
                        // random sleep 0-100 ms to retry
6386
1
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6387
1
                    }
6388
1
                }
6389
1
                if (ret != 0) {
6390
1
                    LOG_WARNING("failed to delete recycle txn kv")
6391
1
                            .tag("instance id", instance_id_)
6392
1
                            .tag("key", hex(k));
6393
1
                    return -1;
6394
1
                }
6395
1
                return 0;
6396
1
            });
6397
1
        }
6398
1
        bool finished = true;
6399
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6400
1
        for (int r : rets) {
6401
1
            if (r != 0) {
6402
0
                ret = -1;
6403
0
            }
6404
1
        }
6405
6406
1
        ret = finished ? ret : -1;
6407
6408
        // Update metrics after all concurrent tasks completed
6409
1
        metrics_context.total_recycled_num = num_recycled.load();
6410
1
        metrics_context.report();
6411
6412
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6413
6414
1
        if (ret != 0) {
6415
0
            LOG_WARNING("recycle txn kv ret!=0")
6416
0
                    .tag("finished", finished)
6417
0
                    .tag("ret", ret)
6418
0
                    .tag("instance_id", instance_id_);
6419
0
            return ret;
6420
0
        }
6421
1
        return ret;
6422
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6363
9
    auto loop_done = [&]() -> int {
6364
9
        DORIS_CLOUD_DEFER {
6365
9
            recycle_txn_info_keys.clear();
6366
9
        };
6367
9
        TEST_SYNC_POINT_CALLBACK(
6368
9
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6369
9
                &recycle_txn_info_keys);
6370
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6371
23.0k
            concurrent_delete_executor.add([&]() {
6372
23.0k
                int ret = delete_recycle_txn_kv(k);
6373
23.0k
                if (ret == 1) {
6374
23.0k
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6375
23.0k
                    for (int i = 1; i <= max_retry; ++i) {
6376
23.0k
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6377
23.0k
                        ret = delete_recycle_txn_kv(k);
6378
                        // clang-format off
6379
23.0k
                        TEST_SYNC_POINT_CALLBACK(
6380
23.0k
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6381
                        // clang-format off
6382
23.0k
                        if (ret != 1) {
6383
23.0k
                            break;
6384
23.0k
                        }
6385
                        // random sleep 0-100 ms to retry
6386
23.0k
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6387
23.0k
                    }
6388
23.0k
                }
6389
23.0k
                if (ret != 0) {
6390
23.0k
                    LOG_WARNING("failed to delete recycle txn kv")
6391
23.0k
                            .tag("instance id", instance_id_)
6392
23.0k
                            .tag("key", hex(k));
6393
23.0k
                    return -1;
6394
23.0k
                }
6395
23.0k
                return 0;
6396
23.0k
            });
6397
23.0k
        }
6398
9
        bool finished = true;
6399
9
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6400
23.0k
        for (int r : rets) {
6401
23.0k
            if (r != 0) {
6402
9
                ret = -1;
6403
9
            }
6404
23.0k
        }
6405
6406
9
        ret = finished ? ret : -1;
6407
6408
        // Update metrics after all concurrent tasks completed
6409
9
        metrics_context.total_recycled_num = num_recycled.load();
6410
9
        metrics_context.report();
6411
6412
9
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6413
6414
9
        if (ret != 0) {
6415
3
            LOG_WARNING("recycle txn kv ret!=0")
6416
3
                    .tag("finished", finished)
6417
3
                    .tag("ret", ret)
6418
3
                    .tag("instance_id", instance_id_);
6419
3
            return ret;
6420
3
        }
6421
6
        return ret;
6422
9
    };
6423
6424
19
    if (config::enable_recycler_stats_metrics) {
6425
0
        scan_and_statistics_expired_txn_label();
6426
0
    }
6427
    // recycle_func and loop_done for scan and recycle
6428
19
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
6429
19
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
6430
19
}
6431
6432
struct CopyJobIdTuple {
6433
    std::string instance_id;
6434
    std::string stage_id;
6435
    long table_id;
6436
    std::string copy_id;
6437
    std::string stage_path;
6438
};
6439
struct BatchObjStoreAccessor {
6440
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
6441
                          TxnKv* txn_kv)
6442
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
6443
3
    ~BatchObjStoreAccessor() {
6444
3
        if (!paths_.empty()) {
6445
3
            consume();
6446
3
        }
6447
3
    }
6448
6449
    /**
6450
    * To implicitely do batch work and submit the batch delete task to s3
6451
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
6452
    *
6453
    * @param copy_job The protubuf struct consists of the copy job files.
6454
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
6455
    *            it would last until we finish the delete task, here we need pass one string value
6456
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
6457
    */
6458
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
6459
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
6460
5
        auto& file_keys = copy_file_keys_[key];
6461
5
        file_keys.log_trace =
6462
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
6463
5
                            instance_id, stage_id, table_id, copy_id, path);
6464
5
        std::string_view log_trace = file_keys.log_trace;
6465
2.03k
        for (const auto& file : copy_job.object_files()) {
6466
2.03k
            auto relative_path = file.relative_path();
6467
2.03k
            paths_.push_back(relative_path);
6468
2.03k
            file_keys.keys.push_back(copy_file_key(
6469
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
6470
2.03k
            LOG_INFO(log_trace)
6471
2.03k
                    .tag("relative_path", relative_path)
6472
2.03k
                    .tag("batch_count", batch_count_);
6473
2.03k
        }
6474
5
        LOG_INFO(log_trace)
6475
5
                .tag("objects_num", copy_job.object_files().size())
6476
5
                .tag("batch_count", batch_count_);
6477
        // 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
6478
        // recommend using delete objects when objects num is less than 10)
6479
5
        if (paths_.size() < 1000) {
6480
3
            return;
6481
3
        }
6482
2
        consume();
6483
2
    }
6484
6485
private:
6486
5
    void consume() {
6487
5
        DORIS_CLOUD_DEFER {
6488
5
            paths_.clear();
6489
5
            copy_file_keys_.clear();
6490
5
            batch_count_++;
6491
6492
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
6493
5
                        batch_count_);
6494
5
        };
6495
6496
5
        StopWatch sw;
6497
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
6498
5
        if (0 != accessor_->delete_files(paths_)) {
6499
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
6500
2
                        paths_.size(), batch_count_, sw.elapsed_us());
6501
2
            return;
6502
2
        }
6503
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
6504
3
                    paths_.size(), batch_count_, sw.elapsed_us());
6505
        // delete fdb's keys
6506
3
        for (auto& file_keys : copy_file_keys_) {
6507
3
            auto& [log_trace, keys] = file_keys.second;
6508
3
            std::unique_ptr<Transaction> txn;
6509
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
6510
0
                LOG(WARNING) << "failed to create txn";
6511
0
                continue;
6512
0
            }
6513
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6514
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6515
            // limited, should not cause the txn commit failed.
6516
1.02k
            for (const auto& key : keys) {
6517
1.02k
                txn->remove(key);
6518
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
6519
1.02k
            }
6520
3
            txn->remove(file_keys.first);
6521
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
6522
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
6523
0
                continue;
6524
0
            }
6525
3
        }
6526
3
    }
6527
    std::shared_ptr<StorageVaultAccessor> accessor_;
6528
    // the path of the s3 files to be deleted
6529
    std::vector<std::string> paths_;
6530
    struct CopyFiles {
6531
        std::string log_trace;
6532
        std::vector<std::string> keys;
6533
    };
6534
    // pair<std::string, std::vector<std::string>>
6535
    // first: instance_id_ stage_id table_id query_id
6536
    // second: keys to be deleted
6537
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
6538
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
6539
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
6540
    // which can together uniquely identifies different tasks for tracing log
6541
    uint64_t& batch_count_;
6542
    TxnKv* txn_kv_;
6543
};
6544
6545
13
int InstanceRecycler::recycle_copy_jobs() {
6546
13
    int64_t num_scanned = 0;
6547
13
    int64_t num_finished = 0;
6548
13
    int64_t num_expired = 0;
6549
13
    int64_t num_recycled = 0;
6550
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
6551
13
    uint64_t batch_count = 0;
6552
13
    const std::string task_name = "recycle_copy_jobs";
6553
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6554
6555
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
6556
6557
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6558
13
    register_recycle_task(task_name, start_time);
6559
6560
13
    DORIS_CLOUD_DEFER {
6561
13
        unregister_recycle_task(task_name);
6562
13
        int64_t cost =
6563
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6564
13
        metrics_context.finish_report();
6565
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
6566
13
                .tag("instance_id", instance_id_)
6567
13
                .tag("num_scanned", num_scanned)
6568
13
                .tag("num_finished", num_finished)
6569
13
                .tag("num_expired", num_expired)
6570
13
                .tag("num_recycled", num_recycled);
6571
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
6560
13
    DORIS_CLOUD_DEFER {
6561
13
        unregister_recycle_task(task_name);
6562
13
        int64_t cost =
6563
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6564
13
        metrics_context.finish_report();
6565
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
6566
13
                .tag("instance_id", instance_id_)
6567
13
                .tag("num_scanned", num_scanned)
6568
13
                .tag("num_finished", num_finished)
6569
13
                .tag("num_expired", num_expired)
6570
13
                .tag("num_recycled", num_recycled);
6571
13
    };
6572
6573
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
6574
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
6575
13
    std::string key0;
6576
13
    std::string key1;
6577
13
    copy_job_key(key_info0, &key0);
6578
13
    copy_job_key(key_info1, &key1);
6579
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
6580
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
6581
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
6582
16
                         this](std::string_view k, std::string_view v) -> int {
6583
16
        ++num_scanned;
6584
16
        CopyJobPB copy_job;
6585
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
6586
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
6587
0
            return -1;
6588
0
        }
6589
6590
        // decode copy job key
6591
16
        auto k1 = k;
6592
16
        k1.remove_prefix(1);
6593
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6594
16
        decode_key(&k1, &out);
6595
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
6596
        // -> CopyJobPB
6597
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
6598
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
6599
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
6600
6601
16
        bool check_storage = true;
6602
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
6603
12
            ++num_finished;
6604
6605
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
6606
7
                auto it = stage_accessor_map.find(stage_id);
6607
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
6608
7
                std::string_view path;
6609
7
                if (it != stage_accessor_map.end()) {
6610
2
                    accessor = it->second;
6611
5
                } else {
6612
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
6613
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
6614
5
                                                      &inner_accessor);
6615
5
                    if (ret < 0) { // error
6616
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
6617
0
                        return -1;
6618
5
                    } else if (ret == 0) {
6619
3
                        path = inner_accessor->uri();
6620
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
6621
3
                                inner_accessor, batch_count, txn_kv_.get());
6622
3
                        stage_accessor_map.emplace(stage_id, accessor);
6623
3
                    } else { // stage not found, skip check storage
6624
2
                        check_storage = false;
6625
2
                    }
6626
5
                }
6627
7
                if (check_storage) {
6628
                    // TODO delete objects with key and etag is not supported
6629
5
                    accessor->add(std::move(copy_job), std::string(k),
6630
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
6631
5
                    return 0;
6632
5
                }
6633
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
6634
5
                int64_t current_time =
6635
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6636
5
                if (copy_job.finish_time_ms() > 0) {
6637
2
                    if (!config::force_immediate_recycle &&
6638
2
                        current_time < copy_job.finish_time_ms() +
6639
2
                                               config::copy_job_max_retention_second * 1000) {
6640
1
                        return 0;
6641
1
                    }
6642
3
                } else {
6643
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
6644
3
                    if (!config::force_immediate_recycle &&
6645
3
                        current_time < copy_job.start_time_ms() +
6646
3
                                               config::copy_job_max_retention_second * 1000) {
6647
1
                        return 0;
6648
1
                    }
6649
3
                }
6650
5
            }
6651
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
6652
4
            int64_t current_time =
6653
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6654
            // if copy job is timeout: delete all copy file kvs and copy job kv
6655
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
6656
2
                return 0;
6657
2
            }
6658
2
            ++num_expired;
6659
2
        }
6660
6661
        // delete all copy files
6662
7
        std::vector<std::string> copy_file_keys;
6663
70
        for (auto& file : copy_job.object_files()) {
6664
70
            copy_file_keys.push_back(copy_file_key(
6665
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
6666
70
        }
6667
7
        std::unique_ptr<Transaction> txn;
6668
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
6669
0
            LOG(WARNING) << "failed to create txn";
6670
0
            return -1;
6671
0
        }
6672
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6673
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6674
        // limited, should not cause the txn commit failed.
6675
70
        for (const auto& key : copy_file_keys) {
6676
70
            txn->remove(key);
6677
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
6678
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
6679
70
                      << ", query_id=" << copy_id;
6680
70
        }
6681
7
        txn->remove(k);
6682
7
        TxnErrorCode err = txn->commit();
6683
7
        if (err != TxnErrorCode::TXN_OK) {
6684
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
6685
0
            return -1;
6686
0
        }
6687
6688
7
        metrics_context.total_recycled_num = ++num_recycled;
6689
7
        metrics_context.report();
6690
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6691
7
        return 0;
6692
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
6582
16
                         this](std::string_view k, std::string_view v) -> int {
6583
16
        ++num_scanned;
6584
16
        CopyJobPB copy_job;
6585
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
6586
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
6587
0
            return -1;
6588
0
        }
6589
6590
        // decode copy job key
6591
16
        auto k1 = k;
6592
16
        k1.remove_prefix(1);
6593
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6594
16
        decode_key(&k1, &out);
6595
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
6596
        // -> CopyJobPB
6597
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
6598
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
6599
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
6600
6601
16
        bool check_storage = true;
6602
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
6603
12
            ++num_finished;
6604
6605
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
6606
7
                auto it = stage_accessor_map.find(stage_id);
6607
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
6608
7
                std::string_view path;
6609
7
                if (it != stage_accessor_map.end()) {
6610
2
                    accessor = it->second;
6611
5
                } else {
6612
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
6613
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
6614
5
                                                      &inner_accessor);
6615
5
                    if (ret < 0) { // error
6616
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
6617
0
                        return -1;
6618
5
                    } else if (ret == 0) {
6619
3
                        path = inner_accessor->uri();
6620
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
6621
3
                                inner_accessor, batch_count, txn_kv_.get());
6622
3
                        stage_accessor_map.emplace(stage_id, accessor);
6623
3
                    } else { // stage not found, skip check storage
6624
2
                        check_storage = false;
6625
2
                    }
6626
5
                }
6627
7
                if (check_storage) {
6628
                    // TODO delete objects with key and etag is not supported
6629
5
                    accessor->add(std::move(copy_job), std::string(k),
6630
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
6631
5
                    return 0;
6632
5
                }
6633
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
6634
5
                int64_t current_time =
6635
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6636
5
                if (copy_job.finish_time_ms() > 0) {
6637
2
                    if (!config::force_immediate_recycle &&
6638
2
                        current_time < copy_job.finish_time_ms() +
6639
2
                                               config::copy_job_max_retention_second * 1000) {
6640
1
                        return 0;
6641
1
                    }
6642
3
                } else {
6643
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
6644
3
                    if (!config::force_immediate_recycle &&
6645
3
                        current_time < copy_job.start_time_ms() +
6646
3
                                               config::copy_job_max_retention_second * 1000) {
6647
1
                        return 0;
6648
1
                    }
6649
3
                }
6650
5
            }
6651
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
6652
4
            int64_t current_time =
6653
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6654
            // if copy job is timeout: delete all copy file kvs and copy job kv
6655
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
6656
2
                return 0;
6657
2
            }
6658
2
            ++num_expired;
6659
2
        }
6660
6661
        // delete all copy files
6662
7
        std::vector<std::string> copy_file_keys;
6663
70
        for (auto& file : copy_job.object_files()) {
6664
70
            copy_file_keys.push_back(copy_file_key(
6665
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
6666
70
        }
6667
7
        std::unique_ptr<Transaction> txn;
6668
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
6669
0
            LOG(WARNING) << "failed to create txn";
6670
0
            return -1;
6671
0
        }
6672
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6673
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6674
        // limited, should not cause the txn commit failed.
6675
70
        for (const auto& key : copy_file_keys) {
6676
70
            txn->remove(key);
6677
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
6678
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
6679
70
                      << ", query_id=" << copy_id;
6680
70
        }
6681
7
        txn->remove(k);
6682
7
        TxnErrorCode err = txn->commit();
6683
7
        if (err != TxnErrorCode::TXN_OK) {
6684
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
6685
0
            return -1;
6686
0
        }
6687
6688
7
        metrics_context.total_recycled_num = ++num_recycled;
6689
7
        metrics_context.report();
6690
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6691
7
        return 0;
6692
7
    };
6693
6694
13
    if (config::enable_recycler_stats_metrics) {
6695
0
        scan_and_statistics_copy_jobs();
6696
0
    }
6697
    // recycle_func and loop_done for scan and recycle
6698
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
6699
13
}
6700
6701
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
6702
                                             const StagePB::StageType& stage_type,
6703
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
6704
5
#ifdef UNIT_TEST
6705
    // In unit test, external use the same accessor as the internal stage
6706
5
    auto it = accessor_map_.find(stage_id);
6707
5
    if (it != accessor_map_.end()) {
6708
3
        *accessor = it->second;
6709
3
    } else {
6710
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
6711
2
        return 1;
6712
2
    }
6713
#else
6714
    // init s3 accessor and add to accessor map
6715
    auto stage_it =
6716
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
6717
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
6718
6719
    if (stage_it == instance_info_.stages().end()) {
6720
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
6721
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
6722
        return 1;
6723
    }
6724
6725
    const auto& object_store_info = stage_it->obj_info();
6726
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
6727
6728
    S3Conf s3_conf;
6729
    if (stage_type == StagePB::EXTERNAL) {
6730
        if (stage_access_type == StagePB::AKSK) {
6731
            auto conf = S3Conf::from_obj_store_info(object_store_info);
6732
            if (!conf) {
6733
                return -1;
6734
            }
6735
6736
            s3_conf = std::move(*conf);
6737
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
6738
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
6739
            if (!conf) {
6740
                return -1;
6741
            }
6742
6743
            s3_conf = std::move(*conf);
6744
            if (instance_info_.ram_user().has_encryption_info()) {
6745
                AkSkPair plain_ak_sk_pair;
6746
                int ret = decrypt_ak_sk_helper(
6747
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
6748
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
6749
                if (ret != 0) {
6750
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
6751
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
6752
                    return -1;
6753
                }
6754
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
6755
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
6756
            } else {
6757
                s3_conf.ak = instance_info_.ram_user().ak();
6758
                s3_conf.sk = instance_info_.ram_user().sk();
6759
            }
6760
        } else {
6761
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
6762
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
6763
            return -1;
6764
        }
6765
    } else if (stage_type == StagePB::INTERNAL) {
6766
        int idx = stoi(object_store_info.id());
6767
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6768
            LOG(WARNING) << "invalid idx: " << idx;
6769
            return -1;
6770
        }
6771
6772
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
6773
        auto conf = S3Conf::from_obj_store_info(old_obj);
6774
        if (!conf) {
6775
            return -1;
6776
        }
6777
6778
        s3_conf = std::move(*conf);
6779
        s3_conf.prefix = object_store_info.prefix();
6780
    } else {
6781
        LOG(WARNING) << "unknown stage type " << stage_type;
6782
        return -1;
6783
    }
6784
6785
    std::shared_ptr<S3Accessor> s3_accessor;
6786
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
6787
    if (ret != 0) {
6788
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
6789
        return -1;
6790
    }
6791
6792
    *accessor = std::move(s3_accessor);
6793
#endif
6794
3
    return 0;
6795
5
}
6796
6797
11
int InstanceRecycler::recycle_stage() {
6798
11
    int64_t num_scanned = 0;
6799
11
    int64_t num_recycled = 0;
6800
11
    const std::string task_name = "recycle_stage";
6801
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6802
6803
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
6804
6805
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6806
11
    register_recycle_task(task_name, start_time);
6807
6808
11
    DORIS_CLOUD_DEFER {
6809
11
        unregister_recycle_task(task_name);
6810
11
        int64_t cost =
6811
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6812
11
        metrics_context.finish_report();
6813
11
        LOG_WARNING("recycle stage, cost={}s", cost)
6814
11
                .tag("instance_id", instance_id_)
6815
11
                .tag("num_scanned", num_scanned)
6816
11
                .tag("num_recycled", num_recycled);
6817
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
6808
11
    DORIS_CLOUD_DEFER {
6809
11
        unregister_recycle_task(task_name);
6810
11
        int64_t cost =
6811
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6812
11
        metrics_context.finish_report();
6813
11
        LOG_WARNING("recycle stage, cost={}s", cost)
6814
11
                .tag("instance_id", instance_id_)
6815
11
                .tag("num_scanned", num_scanned)
6816
11
                .tag("num_recycled", num_recycled);
6817
11
    };
6818
6819
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
6820
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
6821
11
    std::string key0 = recycle_stage_key(key_info0);
6822
11
    std::string key1 = recycle_stage_key(key_info1);
6823
6824
11
    std::vector<std::string_view> stage_keys;
6825
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
6826
11
                         this](std::string_view k, std::string_view v) -> int {
6827
1
        ++num_scanned;
6828
1
        RecycleStagePB recycle_stage;
6829
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
6830
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
6831
0
            return -1;
6832
0
        }
6833
6834
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
6835
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6836
0
            LOG(WARNING) << "invalid idx: " << idx;
6837
0
            return -1;
6838
0
        }
6839
6840
1
        std::shared_ptr<StorageVaultAccessor> accessor;
6841
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
6842
1
                [&] {
6843
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
6844
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
6845
1
                    if (!s3_conf) {
6846
1
                        return -1;
6847
1
                    }
6848
6849
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
6850
1
                    std::shared_ptr<S3Accessor> s3_accessor;
6851
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
6852
1
                    if (ret != 0) {
6853
1
                        return -1;
6854
1
                    }
6855
6856
1
                    accessor = std::move(s3_accessor);
6857
1
                    return 0;
6858
1
                }(),
6859
1
                "recycle_stage:get_accessor", &accessor);
6860
6861
1
        if (ret != 0) {
6862
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
6863
0
            return ret;
6864
0
        }
6865
6866
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
6867
1
                .tag("instance_id", instance_id_)
6868
1
                .tag("stage_id", recycle_stage.stage().stage_id())
6869
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
6870
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
6871
1
                .tag("obj_info_id", idx)
6872
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
6873
1
        ret = accessor->delete_all();
6874
1
        if (ret != 0) {
6875
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
6876
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
6877
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
6878
0
                         << ", ret=" << ret;
6879
0
            return -1;
6880
0
        }
6881
1
        metrics_context.total_recycled_num = ++num_recycled;
6882
1
        metrics_context.report();
6883
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
6884
1
        stage_keys.push_back(k);
6885
1
        return 0;
6886
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6826
1
                         this](std::string_view k, std::string_view v) -> int {
6827
1
        ++num_scanned;
6828
1
        RecycleStagePB recycle_stage;
6829
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
6830
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
6831
0
            return -1;
6832
0
        }
6833
6834
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
6835
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6836
0
            LOG(WARNING) << "invalid idx: " << idx;
6837
0
            return -1;
6838
0
        }
6839
6840
1
        std::shared_ptr<StorageVaultAccessor> accessor;
6841
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
6842
1
                [&] {
6843
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
6844
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
6845
1
                    if (!s3_conf) {
6846
1
                        return -1;
6847
1
                    }
6848
6849
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
6850
1
                    std::shared_ptr<S3Accessor> s3_accessor;
6851
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
6852
1
                    if (ret != 0) {
6853
1
                        return -1;
6854
1
                    }
6855
6856
1
                    accessor = std::move(s3_accessor);
6857
1
                    return 0;
6858
1
                }(),
6859
1
                "recycle_stage:get_accessor", &accessor);
6860
6861
1
        if (ret != 0) {
6862
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
6863
0
            return ret;
6864
0
        }
6865
6866
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
6867
1
                .tag("instance_id", instance_id_)
6868
1
                .tag("stage_id", recycle_stage.stage().stage_id())
6869
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
6870
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
6871
1
                .tag("obj_info_id", idx)
6872
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
6873
1
        ret = accessor->delete_all();
6874
1
        if (ret != 0) {
6875
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
6876
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
6877
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
6878
0
                         << ", ret=" << ret;
6879
0
            return -1;
6880
0
        }
6881
1
        metrics_context.total_recycled_num = ++num_recycled;
6882
1
        metrics_context.report();
6883
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
6884
1
        stage_keys.push_back(k);
6885
1
        return 0;
6886
1
    };
6887
6888
11
    auto loop_done = [&stage_keys, this]() -> int {
6889
1
        if (stage_keys.empty()) return 0;
6890
1
        DORIS_CLOUD_DEFER {
6891
1
            stage_keys.clear();
6892
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6890
1
        DORIS_CLOUD_DEFER {
6891
1
            stage_keys.clear();
6892
1
        };
6893
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
6894
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
6895
0
            return -1;
6896
0
        }
6897
1
        return 0;
6898
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
6888
1
    auto loop_done = [&stage_keys, this]() -> int {
6889
1
        if (stage_keys.empty()) return 0;
6890
1
        DORIS_CLOUD_DEFER {
6891
1
            stage_keys.clear();
6892
1
        };
6893
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
6894
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
6895
0
            return -1;
6896
0
        }
6897
1
        return 0;
6898
1
    };
6899
11
    if (config::enable_recycler_stats_metrics) {
6900
0
        scan_and_statistics_stage();
6901
0
    }
6902
    // recycle_func and loop_done for scan and recycle
6903
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
6904
11
}
6905
6906
10
int InstanceRecycler::recycle_expired_stage_objects() {
6907
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
6908
6909
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6910
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
6911
6912
10
    DORIS_CLOUD_DEFER {
6913
10
        int64_t cost =
6914
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6915
10
        metrics_context.finish_report();
6916
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
6917
10
                .tag("instance_id", instance_id_);
6918
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
6912
10
    DORIS_CLOUD_DEFER {
6913
10
        int64_t cost =
6914
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6915
10
        metrics_context.finish_report();
6916
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
6917
10
                .tag("instance_id", instance_id_);
6918
10
    };
6919
6920
10
    int ret = 0;
6921
6922
10
    if (config::enable_recycler_stats_metrics) {
6923
0
        scan_and_statistics_expired_stage_objects();
6924
0
    }
6925
6926
10
    for (const auto& stage : instance_info_.stages()) {
6927
0
        std::stringstream ss;
6928
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
6929
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
6930
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
6931
0
           << ", prefix=" << stage.obj_info().prefix();
6932
6933
0
        if (stopped()) {
6934
0
            break;
6935
0
        }
6936
0
        if (stage.type() == StagePB::EXTERNAL) {
6937
0
            continue;
6938
0
        }
6939
0
        int idx = stoi(stage.obj_info().id());
6940
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6941
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
6942
0
            continue;
6943
0
        }
6944
6945
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
6946
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
6947
0
        if (!s3_conf) {
6948
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
6949
0
            continue;
6950
0
        }
6951
6952
0
        s3_conf->prefix = stage.obj_info().prefix();
6953
0
        std::shared_ptr<S3Accessor> accessor;
6954
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
6955
0
        if (ret1 != 0) {
6956
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
6957
0
            ret = -1;
6958
0
            continue;
6959
0
        }
6960
6961
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
6962
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
6963
0
            ret = -1;
6964
0
            continue;
6965
0
        }
6966
6967
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
6968
0
        int64_t expiration_time =
6969
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
6970
0
                config::internal_stage_objects_expire_time_second;
6971
0
        if (config::force_immediate_recycle) {
6972
0
            expiration_time = INT64_MAX;
6973
0
        }
6974
0
        ret1 = accessor->delete_all(expiration_time);
6975
0
        if (ret1 != 0) {
6976
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
6977
0
                         << ss.str();
6978
0
            ret = -1;
6979
0
            continue;
6980
0
        }
6981
0
        metrics_context.total_recycled_num++;
6982
0
        metrics_context.report();
6983
0
    }
6984
10
    return ret;
6985
10
}
6986
6987
193
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
6988
193
    std::lock_guard lock(recycle_tasks_mutex);
6989
193
    running_recycle_tasks[task_name] = start_time;
6990
193
}
6991
6992
193
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
6993
193
    std::lock_guard lock(recycle_tasks_mutex);
6994
193
    DCHECK(running_recycle_tasks[task_name] > 0);
6995
193
    running_recycle_tasks.erase(task_name);
6996
193
}
6997
6998
21
bool InstanceRecycler::check_recycle_tasks() {
6999
21
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
7000
21
    {
7001
21
        std::lock_guard lock(recycle_tasks_mutex);
7002
21
        tmp_running_recycle_tasks = running_recycle_tasks;
7003
21
    }
7004
7005
21
    bool found = false;
7006
21
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7007
21
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
7008
20
        int64_t cost = now - start_time;
7009
20
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
7010
20
            LOG_INFO("recycle task cost too much time cost={}s", cost)
7011
20
                    .tag("instance_id", instance_id_)
7012
20
                    .tag("task", task_name);
7013
20
            found = true;
7014
20
        }
7015
20
    }
7016
7017
21
    return found;
7018
21
}
7019
7020
// Scan and statistics indexes that need to be recycled
7021
0
int InstanceRecycler::scan_and_statistics_indexes() {
7022
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
7023
7024
0
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
7025
0
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
7026
0
    std::string index_key0;
7027
0
    std::string index_key1;
7028
0
    recycle_index_key(index_key_info0, &index_key0);
7029
0
    recycle_index_key(index_key_info1, &index_key1);
7030
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7031
7032
0
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7033
0
        RecycleIndexPB index_pb;
7034
0
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7035
0
            return 0;
7036
0
        }
7037
0
        int64_t current_time = ::time(nullptr);
7038
0
        if (current_time <
7039
0
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7040
0
            return 0;
7041
0
        }
7042
        // decode index_id
7043
0
        auto k1 = k;
7044
0
        k1.remove_prefix(1);
7045
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7046
0
        decode_key(&k1, &out);
7047
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7048
0
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7049
0
        std::unique_ptr<Transaction> txn;
7050
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7051
0
        if (err != TxnErrorCode::TXN_OK) {
7052
0
            return 0;
7053
0
        }
7054
0
        std::string val;
7055
0
        err = txn->get(k, &val);
7056
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7057
0
            return 0;
7058
0
        }
7059
0
        if (err != TxnErrorCode::TXN_OK) {
7060
0
            return 0;
7061
0
        }
7062
0
        index_pb.Clear();
7063
0
        if (!index_pb.ParseFromString(val)) {
7064
0
            return 0;
7065
0
        }
7066
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7067
0
            return 0;
7068
0
        }
7069
0
        metrics_context.total_need_recycle_num++;
7070
0
        return 0;
7071
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
7072
7073
0
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
7074
0
    metrics_context.report(true);
7075
0
    segment_metrics_context_.report(true);
7076
0
    tablet_metrics_context_.report(true);
7077
0
    return ret;
7078
0
}
7079
7080
// Scan and statistics partitions that need to be recycled
7081
0
int InstanceRecycler::scan_and_statistics_partitions() {
7082
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
7083
7084
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
7085
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
7086
0
    std::string part_key0;
7087
0
    std::string part_key1;
7088
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7089
7090
0
    recycle_partition_key(part_key_info0, &part_key0);
7091
0
    recycle_partition_key(part_key_info1, &part_key1);
7092
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
7093
0
        RecyclePartitionPB part_pb;
7094
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
7095
0
            return 0;
7096
0
        }
7097
0
        int64_t current_time = ::time(nullptr);
7098
0
        if (current_time <
7099
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
7100
0
            return 0;
7101
0
        }
7102
        // decode partition_id
7103
0
        auto k1 = k;
7104
0
        k1.remove_prefix(1);
7105
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7106
0
        decode_key(&k1, &out);
7107
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
7108
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
7109
        // Change state to RECYCLING
7110
0
        std::unique_ptr<Transaction> txn;
7111
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7112
0
        if (err != TxnErrorCode::TXN_OK) {
7113
0
            return 0;
7114
0
        }
7115
0
        std::string val;
7116
0
        err = txn->get(k, &val);
7117
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7118
0
            return 0;
7119
0
        }
7120
0
        if (err != TxnErrorCode::TXN_OK) {
7121
0
            return 0;
7122
0
        }
7123
0
        part_pb.Clear();
7124
0
        if (!part_pb.ParseFromString(val)) {
7125
0
            return 0;
7126
0
        }
7127
        // Partitions with PREPARED state MUST have no data
7128
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
7129
0
        int ret = 0;
7130
0
        for (int64_t index_id : part_pb.index_id()) {
7131
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
7132
0
                                            partition_id, is_empty_tablet) != 0) {
7133
0
                ret = 0;
7134
0
            }
7135
0
        }
7136
0
        metrics_context.total_need_recycle_num++;
7137
0
        return ret;
7138
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_
7139
7140
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
7141
0
    metrics_context.report(true);
7142
0
    segment_metrics_context_.report(true);
7143
0
    tablet_metrics_context_.report(true);
7144
0
    return ret;
7145
0
}
7146
7147
// Scan and statistics rowsets that need to be recycled
7148
0
int InstanceRecycler::scan_and_statistics_rowsets() {
7149
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
7150
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
7151
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
7152
0
    std::string recyc_rs_key0;
7153
0
    std::string recyc_rs_key1;
7154
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
7155
0
                recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
7156
0
       int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7157
7158
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
7159
0
        RecycleRowsetPB rowset;
7160
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7161
0
            return 0;
7162
0
        }
7163
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
7164
0
        int64_t current_time = ::time(nullptr);
7165
0
        if (current_time <
7166
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
7167
0
            return 0;
7168
0
        }
7169
7170
0
        if (!rowset.has_type()) {
7171
0
            if (!rowset.has_resource_id()) [[unlikely]] {
7172
0
                return 0;
7173
0
            }
7174
0
            if (rowset.resource_id().empty()) [[unlikely]] {
7175
0
                return 0;
7176
0
            }
7177
0
            metrics_context.total_need_recycle_num++;
7178
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7179
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
7180
0
            segment_metrics_context_.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7181
0
            return 0;
7182
0
        }
7183
7184
0
        if(!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled()) {
7185
0
            return 0;
7186
0
        }
7187
7188
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
7189
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
7190
0
                return 0;
7191
0
            }
7192
0
        }
7193
0
        metrics_context.total_need_recycle_num++;
7194
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
7195
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
7196
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
7197
0
        return 0;
7198
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_
7199
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
7200
0
    metrics_context.report(true);
7201
0
    segment_metrics_context_.report(true);
7202
0
    return ret;
7203
0
}
7204
7205
// Scan and statistics tmp_rowsets that need to be recycled
7206
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
7207
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
7208
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
7209
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
7210
0
    std::string tmp_rs_key0;
7211
0
    std::string tmp_rs_key1;
7212
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
7213
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
7214
7215
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7216
7217
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
7218
0
        doris::RowsetMetaCloudPB rowset;
7219
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7220
0
            return 0;
7221
0
        }
7222
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
7223
0
        int64_t current_time = ::time(nullptr);
7224
0
        if (current_time < expiration) {
7225
0
            return 0;
7226
0
        }
7227
7228
0
        DCHECK_GT(rowset.txn_id(), 0)
7229
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
7230
7231
0
        if(!rowset.has_is_recycled() || !rowset.is_recycled()) {
7232
0
            return 0;
7233
0
        }
7234
7235
0
        if (!rowset.has_resource_id()) {
7236
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
7237
0
                return 0;
7238
0
            }
7239
0
            return 0;
7240
0
        }
7241
7242
0
        metrics_context.total_need_recycle_num++;
7243
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
7244
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
7245
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
7246
0
        return 0;
7247
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_
7248
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
7249
0
    metrics_context.report(true);
7250
0
    segment_metrics_context_.report(true);
7251
0
    return ret;
7252
0
}
7253
7254
// Scan and statistics abort_timeout_txn that need to be recycled
7255
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
7256
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
7257
7258
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
7259
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7260
0
    std::string begin_txn_running_key;
7261
0
    std::string end_txn_running_key;
7262
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
7263
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
7264
7265
0
    int64_t current_time =
7266
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7267
7268
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
7269
0
                                               std::string_view k, std::string_view v) -> int {
7270
0
        std::unique_ptr<Transaction> txn;
7271
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7272
0
        if (err != TxnErrorCode::TXN_OK) {
7273
0
            return 0;
7274
0
        }
7275
0
        std::string_view k1 = k;
7276
0
        k1.remove_prefix(1);
7277
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7278
0
        if (decode_key(&k1, &out) != 0) {
7279
0
            return 0;
7280
0
        }
7281
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7282
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7283
        // Update txn_info
7284
0
        std::string txn_inf_key, txn_inf_val;
7285
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
7286
0
        err = txn->get(txn_inf_key, &txn_inf_val);
7287
0
        if (err != TxnErrorCode::TXN_OK) {
7288
0
            return 0;
7289
0
        }
7290
0
        TxnInfoPB txn_info;
7291
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
7292
0
            return 0;
7293
0
        }
7294
7295
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
7296
0
            TxnRunningPB txn_running_pb;
7297
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7298
0
                return 0;
7299
0
            }
7300
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7301
0
                return 0;
7302
0
            }
7303
0
            metrics_context.total_need_recycle_num++;
7304
0
        }
7305
0
        return 0;
7306
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_
7307
7308
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key, std::move(handle_abort_timeout_txn_kv));
7309
0
    metrics_context.report(true);
7310
0
    return ret;
7311
0
}
7312
7313
// Scan and statistics expired_txn_label that need to be recycled
7314
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
7315
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
7316
7317
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7318
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7319
0
    std::string begin_recycle_txn_key;
7320
0
    std::string end_recycle_txn_key;
7321
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7322
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7323
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7324
0
    int64_t current_time_ms =
7325
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7326
7327
    // for calculate the total num or bytes of recyled objects
7328
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
7329
0
        RecycleTxnPB recycle_txn_pb;
7330
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7331
0
            return 0;
7332
0
        }
7333
0
        if ((config::force_immediate_recycle) ||
7334
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7335
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7336
0
             current_time_ms)) {
7337
0
            metrics_context.total_need_recycle_num++;
7338
0
        }
7339
0
        return 0;
7340
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_
7341
7342
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key, std::move(handle_expired_txn_label_kv));
7343
0
    metrics_context.report(true);
7344
0
    return ret;
7345
0
}
7346
7347
// Scan and statistics copy_jobs that need to be recycled
7348
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
7349
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
7350
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7351
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7352
0
    std::string key0;
7353
0
    std::string key1;
7354
0
    copy_job_key(key_info0, &key0);
7355
0
    copy_job_key(key_info1, &key1);
7356
7357
    // for calculate the total num or bytes of recyled objects
7358
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
7359
0
        CopyJobPB copy_job;
7360
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7361
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7362
0
            return 0;
7363
0
        }
7364
7365
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7366
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
7367
0
                int64_t current_time =
7368
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7369
0
                if (copy_job.finish_time_ms() > 0) {
7370
0
                    if (!config::force_immediate_recycle &&
7371
0
                        current_time < copy_job.finish_time_ms() +
7372
0
                                               config::copy_job_max_retention_second * 1000) {
7373
0
                        return 0;
7374
0
                    }
7375
0
                } else {
7376
0
                    if (!config::force_immediate_recycle &&
7377
0
                        current_time < copy_job.start_time_ms() +
7378
0
                                               config::copy_job_max_retention_second * 1000) {
7379
0
                        return 0;
7380
0
                    }
7381
0
                }
7382
0
            }
7383
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7384
0
            int64_t current_time =
7385
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7386
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7387
0
                return 0;
7388
0
            }
7389
0
        }
7390
0
        metrics_context.total_need_recycle_num++;
7391
0
        return 0;
7392
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_
7393
7394
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7395
0
    metrics_context.report(true);
7396
0
    return ret;
7397
0
}
7398
7399
// Scan and statistics stage that need to be recycled
7400
0
int InstanceRecycler::scan_and_statistics_stage() {
7401
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
7402
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7403
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7404
0
    std::string key0 = recycle_stage_key(key_info0);
7405
0
    std::string key1 = recycle_stage_key(key_info1);
7406
7407
    // for calculate the total num or bytes of recyled objects
7408
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
7409
0
                                                        std::string_view v) -> int {
7410
0
        RecycleStagePB recycle_stage;
7411
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7412
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7413
0
            return 0;
7414
0
        }
7415
7416
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
7417
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7418
0
            LOG(WARNING) << "invalid idx: " << idx;
7419
0
            return 0;
7420
0
        }
7421
7422
0
        std::shared_ptr<StorageVaultAccessor> accessor;
7423
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7424
0
                [&] {
7425
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7426
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7427
0
                    if (!s3_conf) {
7428
0
                        return 0;
7429
0
                    }
7430
7431
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7432
0
                    std::shared_ptr<S3Accessor> s3_accessor;
7433
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7434
0
                    if (ret != 0) {
7435
0
                        return 0;
7436
0
                    }
7437
7438
0
                    accessor = std::move(s3_accessor);
7439
0
                    return 0;
7440
0
                }(),
7441
0
                "recycle_stage:get_accessor", &accessor);
7442
7443
0
        if (ret != 0) {
7444
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7445
0
            return 0;
7446
0
        }
7447
7448
0
        metrics_context.total_need_recycle_num++;
7449
0
        return 0;
7450
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_
7451
7452
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7453
0
    metrics_context.report(true);
7454
0
    return ret;
7455
0
}
7456
7457
// Scan and statistics expired_stage_objects that need to be recycled
7458
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
7459
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7460
7461
    // for calculate the total num or bytes of recyled objects
7462
0
    auto scan_and_statistics = [&metrics_context, this]() {
7463
0
        for (const auto& stage : instance_info_.stages()) {
7464
0
            if (stopped()) {
7465
0
                break;
7466
0
            }
7467
0
            if (stage.type() == StagePB::EXTERNAL) {
7468
0
                continue;
7469
0
            }
7470
0
            int idx = stoi(stage.obj_info().id());
7471
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
7472
0
                continue;
7473
0
            }
7474
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
7475
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7476
0
            if (!s3_conf) {
7477
0
                continue;
7478
0
            }
7479
0
            s3_conf->prefix = stage.obj_info().prefix();
7480
0
            std::shared_ptr<S3Accessor> accessor;
7481
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
7482
0
            if (ret1 != 0) {
7483
0
                continue;
7484
0
            }
7485
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7486
0
                continue;
7487
0
            }
7488
0
            metrics_context.total_need_recycle_num++;
7489
0
        }
7490
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
7491
7492
0
    scan_and_statistics();
7493
0
    metrics_context.report(true);
7494
0
    return 0;
7495
0
}
7496
7497
// Scan and statistics versions that need to be recycled
7498
0
int InstanceRecycler::scan_and_statistics_versions() {
7499
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
7500
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
7501
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
7502
7503
0
    int64_t last_scanned_table_id = 0;
7504
0
    bool is_recycled = false; // Is last scanned kv recycled
7505
    // for calculate the total num or bytes of recyled objects
7506
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
7507
0
                                       std::string_view k, std::string_view) {
7508
0
        auto k1 = k;
7509
0
        k1.remove_prefix(1);
7510
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
7511
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7512
0
        decode_key(&k1, &out);
7513
0
        DCHECK_EQ(out.size(), 6) << k;
7514
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
7515
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
7516
0
            metrics_context.total_need_recycle_num +=
7517
0
                    is_recycled; // Version kv of this table has been recycled
7518
0
            return 0;
7519
0
        }
7520
0
        last_scanned_table_id = table_id;
7521
0
        is_recycled = false;
7522
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
7523
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
7524
0
        std::unique_ptr<Transaction> txn;
7525
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7526
0
        if (err != TxnErrorCode::TXN_OK) {
7527
0
            return 0;
7528
0
        }
7529
0
        std::unique_ptr<RangeGetIterator> iter;
7530
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
7531
0
        if (err != TxnErrorCode::TXN_OK) {
7532
0
            return 0;
7533
0
        }
7534
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
7535
0
            return 0;
7536
0
        }
7537
0
        metrics_context.total_need_recycle_num++;
7538
0
        is_recycled = true;
7539
0
        return 0;
7540
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_
7541
7542
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
7543
0
    metrics_context.report(true);
7544
0
    return ret;
7545
0
}
7546
7547
// Scan and statistics restore jobs that need to be recycled
7548
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
7549
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
7550
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
7551
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
7552
0
    std::string restore_job_key0;
7553
0
    std::string restore_job_key1;
7554
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
7555
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
7556
7557
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7558
7559
    // for calculate the total num or bytes of recyled objects
7560
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
7561
0
        RestoreJobCloudPB restore_job_pb;
7562
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
7563
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
7564
0
            return 0;
7565
0
        }
7566
0
        int64_t expiration =
7567
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
7568
0
        int64_t current_time = ::time(nullptr);
7569
0
        if (current_time < expiration) { // not expired
7570
0
            return 0;
7571
0
        }
7572
0
        metrics_context.total_need_recycle_num++;
7573
0
        if(restore_job_pb.need_recycle_data()) {
7574
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
7575
0
        }
7576
0
        return 0;
7577
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_
7578
7579
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
7580
0
    metrics_context.report(true);
7581
0
    return ret;
7582
0
}
7583
7584
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
7585
3
    if (!should_recycle_versioned_keys()) {
7586
0
        return;
7587
0
    }
7588
7589
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
7590
7591
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
7592
3
    if (recycle_checker.init() != 0) {
7593
0
        return;
7594
0
    }
7595
7596
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
7597
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
7598
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
7599
7600
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
7601
8
    for (; iter->valid(); iter->next()) {
7602
5
        OperationLogPB operation_log;
7603
5
        if (!iter->parse_value(&operation_log)) {
7604
0
            continue;
7605
0
        }
7606
7607
5
        std::string_view key = iter->key();
7608
5
        Versionstamp log_versionstamp;
7609
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
7610
0
            continue;
7611
0
        }
7612
7613
5
        OperationLogReferenceInfo ref_info;
7614
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
7615
5
                                         &ref_info)) {
7616
4
            metrics_context.total_need_recycle_num++;
7617
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
7618
4
        }
7619
5
    }
7620
7621
3
    metrics_context.report(true);
7622
3
}
7623
7624
int InstanceRecycler::classify_rowset_task_by_ref_count(
7625
60
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
7626
60
    constexpr int MAX_RETRY = 10;
7627
60
    const auto& rowset_meta = task.rowset_meta;
7628
60
    int64_t tablet_id = rowset_meta.tablet_id();
7629
60
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
7630
60
    std::string_view reference_instance_id = instance_id_;
7631
60
    if (rowset_meta.has_reference_instance_id()) {
7632
5
        reference_instance_id = rowset_meta.reference_instance_id();
7633
5
    }
7634
7635
61
    for (int i = 0; i < MAX_RETRY; ++i) {
7636
61
        std::unique_ptr<Transaction> txn;
7637
61
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7638
61
        if (err != TxnErrorCode::TXN_OK) {
7639
0
            LOG_WARNING("failed to create txn when classifying rowset task")
7640
0
                    .tag("instance_id", instance_id_)
7641
0
                    .tag("tablet_id", tablet_id)
7642
0
                    .tag("rowset_id", rowset_id)
7643
0
                    .tag("err", err);
7644
0
            return -1;
7645
0
        }
7646
7647
61
        std::string rowset_ref_count_key =
7648
61
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
7649
61
        task.rowset_ref_count_key = rowset_ref_count_key;
7650
7651
61
        int64_t ref_count = 0;
7652
61
        {
7653
61
            std::string value;
7654
61
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
7655
61
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7656
0
                ref_count = 1;
7657
61
            } else if (err != TxnErrorCode::TXN_OK) {
7658
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
7659
0
                        .tag("instance_id", instance_id_)
7660
0
                        .tag("tablet_id", tablet_id)
7661
0
                        .tag("rowset_id", rowset_id)
7662
0
                        .tag("err", err);
7663
0
                return -1;
7664
61
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
7665
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
7666
0
                        .tag("instance_id", instance_id_)
7667
0
                        .tag("tablet_id", tablet_id)
7668
0
                        .tag("rowset_id", rowset_id)
7669
0
                        .tag("value", hex(value));
7670
0
                return -1;
7671
0
            }
7672
61
        }
7673
7674
61
        if (ref_count > 1) {
7675
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
7676
12
            txn->atomic_add(rowset_ref_count_key, -1);
7677
12
            LOG_INFO("decrease rowset data ref count in classification phase")
7678
12
                    .tag("instance_id", instance_id_)
7679
12
                    .tag("tablet_id", tablet_id)
7680
12
                    .tag("rowset_id", rowset_id)
7681
12
                    .tag("ref_count", ref_count - 1)
7682
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
7683
7684
12
            if (!task.recycle_rowset_key.empty()) {
7685
0
                txn->remove(task.recycle_rowset_key);
7686
0
                LOG_INFO("remove recycle rowset key in classification phase")
7687
0
                        .tag("key", hex(task.recycle_rowset_key));
7688
0
            }
7689
12
            if (!task.non_versioned_rowset_key.empty()) {
7690
12
                txn->remove(task.non_versioned_rowset_key);
7691
12
                LOG_INFO("remove non versioned rowset key in classification phase")
7692
12
                        .tag("key", hex(task.non_versioned_rowset_key));
7693
12
            }
7694
7695
12
            err = txn->commit();
7696
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
7697
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
7698
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
7699
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
7700
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
7701
1
                continue;
7702
11
            } else if (err != TxnErrorCode::TXN_OK) {
7703
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
7704
0
                        .tag("instance_id", instance_id_)
7705
0
                        .tag("tablet_id", tablet_id)
7706
0
                        .tag("rowset_id", rowset_id)
7707
0
                        .tag("err", err);
7708
0
                return -1;
7709
0
            }
7710
11
            return 1; // handled, not added to batch delete
7711
49
        } else {
7712
            // ref_count == 1: Add to batch delete plan without modifying any KV.
7713
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
7714
49
            LOG_INFO("add rowset to batch delete plan")
7715
49
                    .tag("instance_id", instance_id_)
7716
49
                    .tag("tablet_id", tablet_id)
7717
49
                    .tag("rowset_id", rowset_id)
7718
49
                    .tag("resource_id", rowset_meta.resource_id())
7719
49
                    .tag("ref_count", ref_count);
7720
7721
49
            batch_delete_tasks.push_back(std::move(task));
7722
49
            return 0; // added to batch delete
7723
49
        }
7724
61
    }
7725
7726
0
    LOG_WARNING("failed to classify rowset task after retry")
7727
0
            .tag("instance_id", instance_id_)
7728
0
            .tag("tablet_id", tablet_id)
7729
0
            .tag("rowset_id", rowset_id)
7730
0
            .tag("retry", MAX_RETRY);
7731
0
    return -1;
7732
60
}
7733
7734
10
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
7735
10
    int ret = 0;
7736
49
    for (const auto& task : tasks) {
7737
49
        int64_t tablet_id = task.rowset_meta.tablet_id();
7738
49
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
7739
7740
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
7741
        // so we don't need to call it again here.
7742
7743
        // Remove all metadata keys in one transaction
7744
49
        std::unique_ptr<Transaction> txn;
7745
49
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7746
49
        if (err != TxnErrorCode::TXN_OK) {
7747
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
7748
0
                    .tag("instance_id", instance_id_)
7749
0
                    .tag("tablet_id", tablet_id)
7750
0
                    .tag("rowset_id", rowset_id)
7751
0
                    .tag("err", err);
7752
0
            ret = -1;
7753
0
            continue;
7754
0
        }
7755
7756
49
        std::string_view reference_instance_id = instance_id_;
7757
49
        if (task.rowset_meta.has_reference_instance_id()) {
7758
0
            reference_instance_id = task.rowset_meta.reference_instance_id();
7759
0
        }
7760
7761
49
        txn->remove(task.rowset_ref_count_key);
7762
49
        LOG_INFO("delete rowset data ref count key in cleanup phase")
7763
49
                .tag("instance_id", instance_id_)
7764
49
                .tag("tablet_id", tablet_id)
7765
49
                .tag("rowset_id", rowset_id)
7766
49
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
7767
7768
49
        std::string dbm_start_key =
7769
49
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
7770
49
        std::string dbm_end_key = meta_delete_bitmap_key(
7771
49
                {reference_instance_id, tablet_id, rowset_id,
7772
49
                 std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
7773
49
        txn->remove(dbm_start_key, dbm_end_key);
7774
49
        LOG_INFO("remove delete bitmap kv in cleanup phase")
7775
49
                .tag("instance_id", instance_id_)
7776
49
                .tag("tablet_id", tablet_id)
7777
49
                .tag("rowset_id", rowset_id)
7778
49
                .tag("begin", hex(dbm_start_key))
7779
49
                .tag("end", hex(dbm_end_key));
7780
7781
49
        std::string versioned_dbm_start_key =
7782
49
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
7783
49
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
7784
49
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
7785
49
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
7786
49
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
7787
49
                .tag("instance_id", instance_id_)
7788
49
                .tag("tablet_id", tablet_id)
7789
49
                .tag("rowset_id", rowset_id)
7790
49
                .tag("begin", hex(versioned_dbm_start_key))
7791
49
                .tag("end", hex(versioned_dbm_end_key));
7792
7793
        // Remove versioned meta rowset key
7794
49
        if (!task.versioned_rowset_key.empty()) {
7795
49
            versioned::document_remove<RowsetMetaCloudPB>(
7796
49
                txn.get(), task.versioned_rowset_key, task.versionstamp);
7797
49
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
7798
49
                    .tag("instance_id", instance_id_)
7799
49
                    .tag("tablet_id", tablet_id)
7800
49
                    .tag("rowset_id", rowset_id)
7801
49
                    .tag("key_prefix", hex(task.versioned_rowset_key));
7802
49
        }
7803
7804
49
        if (!task.non_versioned_rowset_key.empty()) {
7805
49
            txn->remove(task.non_versioned_rowset_key);
7806
49
            LOG_INFO("remove non versioned rowset key in cleanup phase")
7807
49
                    .tag("instance_id", instance_id_)
7808
49
                    .tag("tablet_id", tablet_id)
7809
49
                    .tag("rowset_id", rowset_id)
7810
49
                    .tag("key", hex(task.non_versioned_rowset_key));
7811
49
        }
7812
7813
        // Remove recycle_rowset_key last to ensure retry safety:
7814
        // if cleanup fails, this key remains and triggers next round retry.
7815
49
        if (!task.recycle_rowset_key.empty()) {
7816
0
            txn->remove(task.recycle_rowset_key);
7817
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
7818
0
                    .tag("instance_id", instance_id_)
7819
0
                    .tag("tablet_id", tablet_id)
7820
0
                    .tag("rowset_id", rowset_id)
7821
0
                    .tag("key", hex(task.recycle_rowset_key));
7822
0
        }
7823
7824
49
        err = txn->commit();
7825
49
        if (err != TxnErrorCode::TXN_OK) {
7826
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
7827
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
7828
0
                    .tag("instance_id", instance_id_)
7829
0
                    .tag("tablet_id", tablet_id)
7830
0
                    .tag("rowset_id", rowset_id)
7831
0
                    .tag("err", err);
7832
0
            ret = -1;
7833
0
            continue;
7834
0
        }
7835
7836
49
        LOG_INFO("cleanup rowset metadata success")
7837
49
                .tag("instance_id", instance_id_)
7838
49
                .tag("tablet_id", tablet_id)
7839
49
                .tag("rowset_id", rowset_id);
7840
49
    }
7841
10
    return ret;
7842
10
}
7843
7844
} // namespace doris::cloud