Coverage Report

Created: 2026-08-11 19:20

/root/doris/cloud/src/recycler/recycler.cpp
Line
Count
Source (jump to first uncovered line)
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "recycler/recycler.h"
19
20
#include <brpc/builtin_service.pb.h>
21
#include <brpc/server.h>
22
#include <butil/endpoint.h>
23
#include <butil/strings/string_split.h>
24
#include <bvar/status.h>
25
#include <gen_cpp/cloud.pb.h>
26
#include <gen_cpp/olap_file.pb.h>
27
28
#include <algorithm>
29
#include <atomic>
30
#include <chrono>
31
#include <cstddef>
32
#include <cstdint>
33
#include <cstdlib>
34
#include <deque>
35
#include <functional>
36
#include <initializer_list>
37
#include <memory>
38
#include <numeric>
39
#include <optional>
40
#include <random>
41
#include <string>
42
#include <string_view>
43
#include <thread>
44
#include <unordered_map>
45
#include <unordered_set>
46
#include <utility>
47
#include <variant>
48
49
#include "common/defer.h"
50
#include "common/stopwatch.h"
51
#include "meta-service/meta_service.h"
52
#include "meta-service/meta_service_helper.h"
53
#include "meta-service/meta_service_schema.h"
54
#include "meta-store/blob_message.h"
55
#include "meta-store/meta_reader.h"
56
#include "meta-store/txn_kv.h"
57
#include "meta-store/txn_kv_error.h"
58
#include "meta-store/versioned_value.h"
59
#include "recycler/checker.h"
60
#ifdef ENABLE_HDFS_STORAGE_VAULT
61
#include "recycler/hdfs_accessor.h"
62
#endif
63
#include "recycler/s3_accessor.h"
64
#include "recycler/storage_vault_accessor.h"
65
#ifdef UNIT_TEST
66
#include "../test/mock_accessor.h"
67
#endif
68
#include "common/bvars.h"
69
#include "common/config.h"
70
#include "common/encryption_util.h"
71
#include "common/logging.h"
72
#include "common/simple_thread_pool.h"
73
#include "common/util.h"
74
#include "cpp/sync_point.h"
75
#include "meta-store/codec.h"
76
#include "meta-store/document_message.h"
77
#include "meta-store/keys.h"
78
#include "recycler/recycler_service.h"
79
#include "recycler/sync_executor.h"
80
#include "recycler/util.h"
81
#include "snapshot/snapshot_manager_factory.h"
82
83
namespace doris::cloud {
84
85
using namespace std::chrono;
86
87
namespace {
88
89
0
int64_t packed_file_retry_sleep_ms() {
90
0
    const int64_t min_ms = std::max<int64_t>(0, config::packed_file_txn_retry_sleep_min_ms);
91
0
    const int64_t max_ms = std::max<int64_t>(min_ms, config::packed_file_txn_retry_sleep_max_ms);
92
0
    thread_local std::mt19937_64 gen(std::random_device {}());
93
0
    std::uniform_int_distribution<int64_t> dist(min_ms, max_ms);
94
0
    return dist(gen);
95
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_126packed_file_retry_sleep_msEv
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_126packed_file_retry_sleep_msEv
96
97
0
void sleep_for_packed_file_retry() {
98
0
    std::this_thread::sleep_for(std::chrono::milliseconds(packed_file_retry_sleep_ms()));
99
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_127sleep_for_packed_file_retryEv
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_127sleep_for_packed_file_retryEv
100
101
868k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
102
868k
    const auto& locations = rowset.packed_slice_locations();
103
868k
    auto it = locations.find(path);
104
868k
    return it != locations.end() && it->second.has_packed_file_path() &&
105
868k
           !it->second.packed_file_path().empty();
106
868k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
101
7
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
102
7
    const auto& locations = rowset.packed_slice_locations();
103
7
    auto it = locations.find(path);
104
7
    return it != locations.end() && it->second.has_packed_file_path() &&
105
7
           !it->second.packed_file_path().empty();
106
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
101
868k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
102
868k
    const auto& locations = rowset.packed_slice_locations();
103
868k
    auto it = locations.find(path);
104
868k
    return it != locations.end() && it->second.has_packed_file_path() &&
105
868k
           !it->second.packed_file_path().empty();
106
868k
}
107
108
void add_file_to_delete_if_not_packed(const doris::RowsetMetaCloudPB& rowset,
109
                                      const std::string& path,
110
866k
                                      std::vector<std::string>* file_paths) {
111
869k
    if (!is_packed_slice_path(rowset, path)) {
112
869k
        file_paths->push_back(path);
113
869k
    }
114
866k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
110
7
                                      std::vector<std::string>* file_paths) {
111
7
    if (!is_packed_slice_path(rowset, path)) {
112
7
        file_paths->push_back(path);
113
7
    }
114
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
110
866k
                                      std::vector<std::string>* file_paths) {
111
869k
    if (!is_packed_slice_path(rowset, path)) {
112
869k
        file_paths->push_back(path);
113
869k
    }
114
866k
}
115
116
37
bool filter_out_instance(const std::string& instance_id) {
117
37
    if (config::recycle_whitelist.empty()) {
118
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
119
35
               config::recycle_blacklist.end();
120
35
    }
121
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
122
2
           config::recycle_whitelist.end();
123
37
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_119filter_out_instanceERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_119filter_out_instanceERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
116
37
bool filter_out_instance(const std::string& instance_id) {
117
37
    if (config::recycle_whitelist.empty()) {
118
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
119
35
               config::recycle_blacklist.end();
120
35
    }
121
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
122
2
           config::recycle_whitelist.end();
123
37
}
124
125
} // namespace
126
127
// return 0 for success get a key, 1 for key not found, negative for error
128
0
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
129
0
    std::unique_ptr<Transaction> txn;
130
0
    TxnErrorCode err = txn_kv->create_txn(&txn);
131
0
    if (err != TxnErrorCode::TXN_OK) {
132
0
        return -1;
133
0
    }
134
0
    switch (txn->get(key, &val, true)) {
135
0
    case TxnErrorCode::TXN_OK:
136
0
        return 0;
137
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
138
0
        return 1;
139
0
    default:
140
0
        return -1;
141
0
    };
142
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
143
144
// 0 for success, negative for error
145
static int txn_get(TxnKv* txn_kv, std::string_view begin, std::string_view end,
146
372
                   std::unique_ptr<RangeGetIterator>& it) {
147
372
    std::unique_ptr<Transaction> txn;
148
372
    TxnErrorCode err = txn_kv->create_txn(&txn);
149
372
    if (err != TxnErrorCode::TXN_OK) {
150
0
        return -1;
151
0
    }
152
372
    switch (txn->get(begin, end, &it, true)) {
153
373
    case TxnErrorCode::TXN_OK:
154
373
        return 0;
155
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
156
0
        return 1;
157
0
    default:
158
0
        return -1;
159
372
    };
160
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
146
36
                   std::unique_ptr<RangeGetIterator>& it) {
147
36
    std::unique_ptr<Transaction> txn;
148
36
    TxnErrorCode err = txn_kv->create_txn(&txn);
149
36
    if (err != TxnErrorCode::TXN_OK) {
150
0
        return -1;
151
0
    }
152
36
    switch (txn->get(begin, end, &it, true)) {
153
36
    case TxnErrorCode::TXN_OK:
154
36
        return 0;
155
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
156
0
        return 1;
157
0
    default:
158
0
        return -1;
159
36
    };
160
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
146
336
                   std::unique_ptr<RangeGetIterator>& it) {
147
336
    std::unique_ptr<Transaction> txn;
148
336
    TxnErrorCode err = txn_kv->create_txn(&txn);
149
336
    if (err != TxnErrorCode::TXN_OK) {
150
0
        return -1;
151
0
    }
152
336
    switch (txn->get(begin, end, &it, true)) {
153
337
    case TxnErrorCode::TXN_OK:
154
337
        return 0;
155
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
156
0
        return 1;
157
0
    default:
158
0
        return -1;
159
336
    };
160
0
}
161
162
// return 0 for success otherwise error
163
10
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
164
10
    std::unique_ptr<Transaction> txn;
165
10
    TxnErrorCode err = txn_kv->create_txn(&txn);
166
10
    if (err != TxnErrorCode::TXN_OK) {
167
0
        return -1;
168
0
    }
169
18
    for (auto k : keys) {
170
18
        txn->remove(k);
171
18
    }
172
10
    switch (txn->commit()) {
173
10
    case TxnErrorCode::TXN_OK:
174
10
        return 0;
175
0
    case TxnErrorCode::TXN_CONFLICT:
176
0
        return -1;
177
0
    default:
178
0
        return -1;
179
10
    }
180
10
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
163
3
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
164
3
    std::unique_ptr<Transaction> txn;
165
3
    TxnErrorCode err = txn_kv->create_txn(&txn);
166
3
    if (err != TxnErrorCode::TXN_OK) {
167
0
        return -1;
168
0
    }
169
3
    for (auto k : keys) {
170
3
        txn->remove(k);
171
3
    }
172
3
    switch (txn->commit()) {
173
3
    case TxnErrorCode::TXN_OK:
174
3
        return 0;
175
0
    case TxnErrorCode::TXN_CONFLICT:
176
0
        return -1;
177
0
    default:
178
0
        return -1;
179
3
    }
180
3
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
163
7
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
164
7
    std::unique_ptr<Transaction> txn;
165
7
    TxnErrorCode err = txn_kv->create_txn(&txn);
166
7
    if (err != TxnErrorCode::TXN_OK) {
167
0
        return -1;
168
0
    }
169
15
    for (auto k : keys) {
170
15
        txn->remove(k);
171
15
    }
172
7
    switch (txn->commit()) {
173
7
    case TxnErrorCode::TXN_OK:
174
7
        return 0;
175
0
    case TxnErrorCode::TXN_CONFLICT:
176
0
        return -1;
177
0
    default:
178
0
        return -1;
179
7
    }
180
7
}
181
182
// return 0 for success otherwise error
183
81
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
184
81
    std::unique_ptr<Transaction> txn;
185
81
    TxnErrorCode err = txn_kv->create_txn(&txn);
186
81
    if (err != TxnErrorCode::TXN_OK) {
187
0
        return -1;
188
0
    }
189
105k
    for (auto& k : keys) {
190
105k
        txn->remove(k);
191
105k
    }
192
81
    switch (txn->commit()) {
193
81
    case TxnErrorCode::TXN_OK:
194
81
        return 0;
195
0
    case TxnErrorCode::TXN_CONFLICT:
196
0
        return -1;
197
0
    default:
198
0
        return -1;
199
81
    }
200
81
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
183
27
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
184
27
    std::unique_ptr<Transaction> txn;
185
27
    TxnErrorCode err = txn_kv->create_txn(&txn);
186
27
    if (err != TxnErrorCode::TXN_OK) {
187
0
        return -1;
188
0
    }
189
27
    for (auto& k : keys) {
190
17
        txn->remove(k);
191
17
    }
192
27
    switch (txn->commit()) {
193
27
    case TxnErrorCode::TXN_OK:
194
27
        return 0;
195
0
    case TxnErrorCode::TXN_CONFLICT:
196
0
        return -1;
197
0
    default:
198
0
        return -1;
199
27
    }
200
27
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
183
54
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
184
54
    std::unique_ptr<Transaction> txn;
185
54
    TxnErrorCode err = txn_kv->create_txn(&txn);
186
54
    if (err != TxnErrorCode::TXN_OK) {
187
0
        return -1;
188
0
    }
189
105k
    for (auto& k : keys) {
190
105k
        txn->remove(k);
191
105k
    }
192
54
    switch (txn->commit()) {
193
54
    case TxnErrorCode::TXN_OK:
194
54
        return 0;
195
0
    case TxnErrorCode::TXN_CONFLICT:
196
0
        return -1;
197
0
    default:
198
0
        return -1;
199
54
    }
200
54
}
201
202
// return 0 for success otherwise error
203
[[maybe_unused]] static int txn_remove(TxnKv* txn_kv, std::string_view begin,
204
106k
                                       std::string_view end) {
205
106k
    std::unique_ptr<Transaction> txn;
206
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
207
106k
    if (err != TxnErrorCode::TXN_OK) {
208
0
        return -1;
209
0
    }
210
106k
    txn->remove(begin, end);
211
106k
    switch (txn->commit()) {
212
106k
    case TxnErrorCode::TXN_OK:
213
106k
        return 0;
214
0
    case TxnErrorCode::TXN_CONFLICT:
215
0
        return -1;
216
0
    default:
217
0
        return -1;
218
106k
    }
219
106k
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
204
17
                                       std::string_view end) {
205
17
    std::unique_ptr<Transaction> txn;
206
17
    TxnErrorCode err = txn_kv->create_txn(&txn);
207
17
    if (err != TxnErrorCode::TXN_OK) {
208
0
        return -1;
209
0
    }
210
17
    txn->remove(begin, end);
211
17
    switch (txn->commit()) {
212
17
    case TxnErrorCode::TXN_OK:
213
17
        return 0;
214
0
    case TxnErrorCode::TXN_CONFLICT:
215
0
        return -1;
216
0
    default:
217
0
        return -1;
218
17
    }
219
17
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
204
106k
                                       std::string_view end) {
205
106k
    std::unique_ptr<Transaction> txn;
206
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
207
106k
    if (err != TxnErrorCode::TXN_OK) {
208
0
        return -1;
209
0
    }
210
106k
    txn->remove(begin, end);
211
106k
    switch (txn->commit()) {
212
106k
    case TxnErrorCode::TXN_OK:
213
106k
        return 0;
214
0
    case TxnErrorCode::TXN_CONFLICT:
215
0
        return -1;
216
0
    default:
217
0
        return -1;
218
106k
    }
219
106k
}
220
221
void scan_restore_job_rowset(
222
        Transaction* txn, const std::string& instance_id, int64_t tablet_id, MetaServiceCode& code,
223
        std::string& msg,
224
        std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>* restore_job_rs_metas);
225
226
static inline void check_recycle_task(const std::string& instance_id, const std::string& task_name,
227
                                      int64_t num_scanned, int64_t num_recycled,
228
56
                                      int64_t start_time) {
229
56
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
230
0
        int64_t cost =
231
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
232
0
        if (cost > config::recycle_task_threshold_seconds) {
233
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
234
0
                    .tag("instance_id", instance_id)
235
0
                    .tag("task", task_name)
236
0
                    .tag("num_scanned", num_scanned)
237
0
                    .tag("num_recycled", num_recycled);
238
0
        }
239
0
    }
240
56
    return;
241
56
}
recycler.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
228
4
                                      int64_t start_time) {
229
4
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
230
0
        int64_t cost =
231
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
232
0
        if (cost > config::recycle_task_threshold_seconds) {
233
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
234
0
                    .tag("instance_id", instance_id)
235
0
                    .tag("task", task_name)
236
0
                    .tag("num_scanned", num_scanned)
237
0
                    .tag("num_recycled", num_recycled);
238
0
        }
239
0
    }
240
4
    return;
241
4
}
recycler_test.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
228
52
                                      int64_t start_time) {
229
52
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
230
0
        int64_t cost =
231
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
232
0
        if (cost > config::recycle_task_threshold_seconds) {
233
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
234
0
                    .tag("instance_id", instance_id)
235
0
                    .tag("task", task_name)
236
0
                    .tag("num_scanned", num_scanned)
237
0
                    .tag("num_recycled", num_recycled);
238
0
        }
239
0
    }
240
52
    return;
241
52
}
242
243
6
Recycler::Recycler(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
244
6
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
245
246
6
    auto s3_producer_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
247
6
                                                               "s3_producer_pool");
248
6
    s3_producer_pool->start();
249
6
    auto recycle_tablet_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
250
6
                                                                  "recycle_tablet_pool");
251
6
    recycle_tablet_pool->start();
252
6
    auto group_recycle_function_pool = std::make_shared<SimpleThreadPool>(
253
6
            config::recycle_pool_parallelism, "group_recycle_function_pool");
254
6
    group_recycle_function_pool->start();
255
6
    _thread_pool_group =
256
6
            RecyclerThreadPoolGroup(std::move(s3_producer_pool), std::move(recycle_tablet_pool),
257
6
                                    std::move(group_recycle_function_pool));
258
259
6
    auto resource_mgr = std::make_shared<ResourceManager>(txn_kv_);
260
6
    txn_lazy_committer_ = std::make_shared<TxnLazyCommitter>(txn_kv_, std::move(resource_mgr));
261
6
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
262
6
}
263
264
6
Recycler::~Recycler() {
265
6
    if (!stopped()) {
266
0
        stop();
267
0
    }
268
6
}
269
270
5
void Recycler::instance_scanner_callback() {
271
    // sleep 60 seconds before scheduling for the launch procedure to complete:
272
    // some bad hdfs connection may cause some log to stdout stderr
273
    // which may pollute .out file and affect the script to check success
274
5
    std::this_thread::sleep_for(
275
5
            std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
276
1.31k
    while (!stopped()) {
277
1.31k
        if (config::enable_recycler) {
278
3
            std::vector<InstanceInfoPB> instances;
279
3
            get_all_instances(txn_kv_.get(), instances);
280
            // TODO(plat1ko): delete job recycle kv of non-existent instances
281
3
            LOG(INFO) << "Recycler get instances: " << [&instances] {
282
3
                std::stringstream ss;
283
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
284
3
                return ss.str();
285
3
            }();
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
Line
Count
Source
281
3
            LOG(INFO) << "Recycler get instances: " << [&instances] {
282
3
                std::stringstream ss;
283
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
284
3
                return ss.str();
285
3
            }();
286
3
            if (!instances.empty()) {
287
                // enqueue instances
288
3
                std::lock_guard lock(mtx_);
289
30
                for (auto& instance : instances) {
290
30
                    if (filter_out_instance(instance.instance_id())) continue;
291
30
                    auto [_, success] = pending_instance_set_.insert(instance.instance_id());
292
                    // skip instance already in pending queue
293
30
                    if (success) {
294
30
                        pending_instance_queue_.push_back(std::move(instance));
295
30
                    }
296
30
                }
297
3
                pending_instance_cond_.notify_all();
298
3
            }
299
1.30k
        } else {
300
1.30k
            LOG(WARNING) << "Skip recycler since enable_recycler is false";
301
1.30k
        }
302
1.31k
        {
303
1.31k
            std::unique_lock lock(mtx_);
304
1.31k
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
305
2.62k
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
305
2.62k
                               [&]() { return stopped(); });
306
1.31k
        }
307
1.31k
    }
308
5
}
309
310
9
void Recycler::recycle_callback() {
311
40
    while (!stopped()) {
312
38
        InstanceInfoPB instance;
313
38
        {
314
38
            std::unique_lock lock(mtx_);
315
38
            pending_instance_cond_.wait(
316
51
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
316
51
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
317
38
            if (stopped()) {
318
7
                return;
319
7
            }
320
31
            instance = std::move(pending_instance_queue_.front());
321
31
            pending_instance_queue_.pop_front();
322
31
            pending_instance_set_.erase(instance.instance_id());
323
31
        }
324
0
        auto& instance_id = instance.instance_id();
325
31
        {
326
31
            std::lock_guard lock(mtx_);
327
            // skip instance in recycling
328
31
            if (recycling_instance_map_.count(instance_id)) continue;
329
31
        }
330
31
        if (!config::enable_recycler) {
331
1
            LOG(WARNING) << "Skip recycle instance_id=" << instance_id
332
1
                         << " since enable_recycler is false";
333
1
            continue;
334
1
        }
335
30
        auto instance_recycler = std::make_shared<InstanceRecycler>(
336
30
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
337
338
30
        if (int r = instance_recycler->init(); r != 0) {
339
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
340
0
                         << " ret=" << r;
341
0
            continue;
342
0
        }
343
30
        std::string recycle_job_key;
344
30
        job_recycle_key({instance_id}, &recycle_job_key);
345
30
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
346
30
                                               ip_port_, config::recycle_interval_seconds * 1000);
347
30
        if (ret != 0) { // Prepare failed
348
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
349
20
                         << " ret=" << ret;
350
20
            continue;
351
20
        } else {
352
10
            std::lock_guard lock(mtx_);
353
10
            recycling_instance_map_.emplace(instance_id, instance_recycler);
354
10
        }
355
10
        if (stopped()) return;
356
10
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
357
10
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
358
10
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
359
10
        g_bvar_recycler_instance_recycle_task_status.put({"submitted"}, 1);
360
10
        ret = instance_recycler->do_recycle();
361
        // If instance recycler has been aborted, don't finish this job
362
363
10
        if (!instance_recycler->stopped()) {
364
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
365
10
                                        ret == 0, ctime_ms);
366
10
        }
367
10
        if (instance_recycler->stopped() || ret != 0) {
368
0
            g_bvar_recycler_instance_recycle_task_status.put({"error"}, 1);
369
0
        }
370
10
        {
371
10
            std::lock_guard lock(mtx_);
372
10
            recycling_instance_map_.erase(instance_id);
373
10
        }
374
375
10
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
376
10
        auto elpased_ms = now - ctime_ms;
377
10
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
378
10
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
379
10
        g_bvar_recycler_instance_next_ts.put({instance_id},
380
10
                                             now + config::recycle_interval_seconds * 1000);
381
10
        g_bvar_recycler_instance_recycle_task_status.put({"completed"}, 1);
382
10
        LOG(INFO) << "recycle instance done, "
383
10
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
384
10
                  << " now: " << now;
385
386
10
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
387
388
10
        LOG_WARNING("finish recycle instance")
389
10
                .tag("instance_id", instance_id)
390
10
                .tag("cost_ms", elpased_ms);
391
10
    }
392
9
}
393
394
4
void Recycler::lease_recycle_jobs() {
395
54
    while (!stopped()) {
396
50
        std::vector<std::string> instances;
397
50
        instances.reserve(recycling_instance_map_.size());
398
50
        {
399
50
            std::lock_guard lock(mtx_);
400
50
            for (auto& [id, _] : recycling_instance_map_) {
401
30
                instances.push_back(id);
402
30
            }
403
50
        }
404
50
        for (auto& i : instances) {
405
30
            std::string recycle_job_key;
406
30
            job_recycle_key({i}, &recycle_job_key);
407
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
408
30
            if (ret == 1) {
409
0
                std::lock_guard lock(mtx_);
410
0
                if (auto it = recycling_instance_map_.find(i);
411
0
                    it != recycling_instance_map_.end()) {
412
0
                    it->second->stop();
413
0
                }
414
0
            }
415
30
        }
416
50
        {
417
50
            std::unique_lock lock(mtx_);
418
50
            notifier_.wait_for(lock,
419
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
420
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
420
100
                               [&]() { return stopped(); });
421
50
        }
422
50
    }
423
4
}
424
425
4
void Recycler::check_recycle_tasks() {
426
7
    while (!stopped()) {
427
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
428
3
        {
429
3
            std::lock_guard lock(mtx_);
430
3
            recycling_instance_map = recycling_instance_map_;
431
3
        }
432
3
        for (auto& entry : recycling_instance_map) {
433
0
            entry.second->check_recycle_tasks();
434
0
        }
435
436
3
        std::unique_lock lock(mtx_);
437
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
438
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
438
6
                           [&]() { return stopped(); });
439
3
    }
440
4
}
441
442
4
int Recycler::start(brpc::Server* server) {
443
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
444
4
    S3Environment::getInstance();
445
446
4
    if (config::enable_checker) {
447
0
        checker_ = std::make_unique<Checker>(txn_kv_);
448
0
        int ret = checker_->start();
449
0
        std::string msg;
450
0
        if (ret != 0) {
451
0
            msg = "failed to start checker";
452
0
            LOG(ERROR) << msg;
453
0
            std::cerr << msg << std::endl;
454
0
            return ret;
455
0
        }
456
0
        msg = "checker started";
457
0
        LOG(INFO) << msg;
458
0
        std::cout << msg << std::endl;
459
0
    }
460
461
4
    if (server) {
462
        // Add service
463
1
        auto recycler_service =
464
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
465
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
466
1
    }
467
468
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
468
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
469
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
470
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
470
8
        workers_.emplace_back([this] { recycle_callback(); });
471
8
    }
472
473
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
474
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
475
476
4
    if (config::enable_snapshot_data_migrator) {
477
0
        snapshot_data_migrator_ = std::make_shared<SnapshotDataMigrator>(txn_kv_);
478
0
        int ret = snapshot_data_migrator_->start();
479
0
        if (ret != 0) {
480
0
            LOG(ERROR) << "failed to start snapshot data migrator";
481
0
            return ret;
482
0
        }
483
0
        LOG(INFO) << "snapshot data migrator started";
484
0
    }
485
486
4
    if (config::enable_snapshot_chain_compactor) {
487
0
        snapshot_chain_compactor_ = std::make_shared<SnapshotChainCompactor>(txn_kv_);
488
0
        int ret = snapshot_chain_compactor_->start();
489
0
        if (ret != 0) {
490
0
            LOG(ERROR) << "failed to start snapshot chain compactor";
491
0
            return ret;
492
0
        }
493
0
        LOG(INFO) << "snapshot chain compactor started";
494
0
    }
495
496
4
    return 0;
497
4
}
498
499
4
void Recycler::stop() {
500
4
    stopped_ = true;
501
4
    notifier_.notify_all();
502
4
    pending_instance_cond_.notify_all();
503
4
    {
504
4
        std::lock_guard lock(mtx_);
505
4
        for (auto& [_, recycler] : recycling_instance_map_) {
506
0
            recycler->stop();
507
0
        }
508
4
    }
509
20
    for (auto& w : workers_) {
510
20
        if (w.joinable()) w.join();
511
20
    }
512
4
    if (checker_) {
513
0
        checker_->stop();
514
0
    }
515
4
    if (snapshot_data_migrator_) {
516
0
        snapshot_data_migrator_->stop();
517
0
    }
518
4
    if (snapshot_chain_compactor_) {
519
0
        snapshot_chain_compactor_->stop();
520
0
    }
521
4
}
522
523
class InstanceRecycler::InvertedIndexIdCache {
524
public:
525
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
526
147
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
527
528
    // Return 0 if success, 1 if schema kv not found, negative for error
529
    // For the same index_id, schema_version, res, since `get` is not completely atomic
530
    // one thread has not finished inserting, and another thread has not get the index_id and schema_version,
531
    // resulting in repeated addition and inaccuracy.
532
    // however, this approach can reduce the lock range and sacrifice a bit of meta repeated get to improve concurrency performance.
533
    // repeated addition does not affect correctness.
534
28.4k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
535
28.4k
        {
536
28.4k
            std::lock_guard lock(mtx_);
537
28.4k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
538
3.80k
                return 0;
539
3.80k
            }
540
24.6k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
541
24.6k
                it != inverted_index_id_map_.end()) {
542
17.9k
                res = it->second;
543
17.9k
                return 0;
544
17.9k
            }
545
24.6k
        }
546
        // Get schema from kv
547
        // TODO(plat1ko): Single flight
548
6.66k
        std::unique_ptr<Transaction> txn;
549
6.66k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
550
6.66k
        if (err != TxnErrorCode::TXN_OK) {
551
0
            LOG(WARNING) << "failed to create txn, err=" << err;
552
0
            return -1;
553
0
        }
554
6.66k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
555
6.66k
        ValueBuf val_buf;
556
6.66k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
557
6.66k
        if (err != TxnErrorCode::TXN_OK) {
558
504
            LOG(WARNING) << "failed to get schema, err=" << err;
559
504
            return static_cast<int>(err);
560
504
        }
561
6.15k
        doris::TabletSchemaCloudPB schema;
562
6.15k
        if (!parse_schema_value(val_buf, &schema)) {
563
0
            LOG(WARNING) << "malformed schema value, key=" << hex(schema_key);
564
0
            return -1;
565
0
        }
566
6.15k
        if (schema.index_size() > 0) {
567
4.22k
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
568
4.22k
            if (schema.has_inverted_index_storage_format()) {
569
4.21k
                index_format = schema.inverted_index_storage_format();
570
4.21k
            }
571
4.22k
            res.first = index_format;
572
4.22k
            res.second.reserve(schema.index_size());
573
10.6k
            for (auto& i : schema.index()) {
574
10.6k
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
575
10.6k
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
576
10.6k
                }
577
10.6k
            }
578
4.22k
        }
579
6.15k
        insert(index_id, schema_version, res);
580
6.15k
        return 0;
581
6.15k
    }
582
583
    // Empty `ids` means this schema has no inverted index
584
6.15k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
585
6.15k
        if (index_info.second.empty()) {
586
1.93k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
587
1.93k
            std::lock_guard lock(mtx_);
588
1.93k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
589
4.22k
        } else {
590
4.22k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
591
4.22k
            std::lock_guard lock(mtx_);
592
4.22k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
593
4.22k
        }
594
6.15k
    }
595
596
private:
597
    std::string instance_id_;
598
    std::shared_ptr<TxnKv> txn_kv_;
599
600
    std::mutex mtx_;
601
    using Key = std::pair<int64_t, int32_t>; // <index_id, schema_version>
602
    struct HashOfKey {
603
59.2k
        size_t operator()(const Key& key) const {
604
59.2k
            size_t seed = 0;
605
59.2k
            seed = std::hash<int64_t> {}(key.first);
606
59.2k
            seed = std::hash<int32_t> {}(key.second);
607
59.2k
            return seed;
608
59.2k
        }
609
    };
610
    // <index_id, schema_version> -> inverted_index_ids
611
    std::unordered_map<Key, InvertedIndexInfo, HashOfKey> inverted_index_id_map_;
612
    // Store <index_id, schema_version> of schema which doesn't have inverted index
613
    std::unordered_set<Key, HashOfKey> schemas_without_inverted_index_;
614
};
615
616
InstanceRecycler::InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
617
                                   RecyclerThreadPoolGroup thread_pool_group,
618
                                   std::shared_ptr<TxnLazyCommitter> txn_lazy_committer)
619
        : txn_kv_(std::move(txn_kv)),
620
          instance_id_(instance.instance_id()),
621
          instance_info_(instance),
622
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
623
          _thread_pool_group(std::move(thread_pool_group)),
624
          txn_lazy_committer_(std::move(txn_lazy_committer)),
625
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
626
147
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
627
147
    delete_bitmap_lock_white_list_->init();
628
147
    resource_mgr_->init();
629
630
147
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
631
632
    // Since the recycler's resource manager could not be notified when instance info changes,
633
    // we need to refresh the instance info here to ensure the resource manager has the latest info.
634
147
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
635
147
};
636
637
147
InstanceRecycler::~InstanceRecycler() = default;
638
639
127
int InstanceRecycler::init_obj_store_accessors() {
640
127
    for (const auto& obj_info : instance_info_.obj_info()) {
641
84
#ifdef UNIT_TEST
642
84
        auto accessor = std::make_shared<MockAccessor>();
643
#else
644
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
645
        if (!s3_conf) {
646
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
647
            return -1;
648
        }
649
650
        std::shared_ptr<S3Accessor> accessor;
651
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
652
        if (ret != 0) {
653
            LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
654
                         << " resource_id=" << obj_info.id();
655
            return ret;
656
        }
657
#endif
658
84
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
659
84
    }
660
661
127
    return 0;
662
127
}
663
664
127
int InstanceRecycler::init_storage_vault_accessors() {
665
127
    if (instance_info_.resource_ids().empty()) {
666
120
        return 0;
667
120
    }
668
669
7
    FullRangeGetOptions opts(txn_kv_);
670
7
    opts.prefetch = true;
671
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
672
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
673
674
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
675
18
        auto [k, v] = *kv;
676
18
        StorageVaultPB vault;
677
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
678
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
679
0
            return -1;
680
0
        }
681
18
        std::string recycler_storage_vault_white_list = accumulate(
682
18
                config::recycler_storage_vault_white_list.begin(),
683
18
                config::recycler_storage_vault_white_list.end(), std::string(),
684
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
Line
Count
Source
684
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
685
18
        LOG_INFO("config::recycler_storage_vault_white_list")
686
18
                .tag("", recycler_storage_vault_white_list);
687
18
        if (!config::recycler_storage_vault_white_list.empty()) {
688
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
689
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
690
8
                it == config::recycler_storage_vault_white_list.end()) {
691
2
                LOG_WARNING(
692
2
                        "failed to init accessor for vault because this vault is not in "
693
2
                        "config::recycler_storage_vault_white_list. ")
694
2
                        .tag(" vault name:", vault.name())
695
2
                        .tag(" config::recycler_storage_vault_white_list:",
696
2
                             recycler_storage_vault_white_list);
697
2
                continue;
698
2
            }
699
8
        }
700
16
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
701
16
                                 &accessor_map_, &vault);
702
16
        if (vault.has_hdfs_info()) {
703
9
#ifdef ENABLE_HDFS_STORAGE_VAULT
704
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
705
9
            int ret = accessor->init();
706
9
            if (ret != 0) {
707
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
708
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
709
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
710
4
                continue;
711
4
            }
712
5
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
713
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
714
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
715
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
716
#else
717
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
718
                       << "but HDFS storage vaults were detected";
719
#endif
720
7
        } else if (vault.has_obj_info()) {
721
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
722
7
            if (!s3_conf) {
723
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
724
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
725
1
                continue;
726
1
            }
727
728
6
            std::shared_ptr<S3Accessor> accessor;
729
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
730
6
            if (ret != 0) {
731
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
732
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
733
0
                             << " ret=" << ret
734
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
735
0
                continue;
736
0
            }
737
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
738
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
739
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
740
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
741
6
        }
742
16
    }
743
744
7
    if (!it->is_valid()) {
745
0
        LOG_WARNING("failed to get storage vault kv");
746
0
        return -1;
747
0
    }
748
749
7
    if (accessor_map_.empty()) {
750
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
751
1
        return -2;
752
1
    }
753
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
754
6
             instance_id_);
755
756
6
    return 0;
757
7
}
758
759
127
int InstanceRecycler::init() {
760
127
    int ret = init_obj_store_accessors();
761
127
    if (ret != 0) {
762
0
        return ret;
763
0
    }
764
765
127
    return init_storage_vault_accessors();
766
127
}
767
768
template <typename... Func>
769
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
770
120
    return [funcs...]() {
771
120
        return [](std::initializer_list<int> ret_vals) {
772
120
            int i = 0;
773
140
            for (int ret : ret_vals) {
774
140
                if (ret != 0) {
775
0
                    i = ret;
776
0
                }
777
140
            }
778
120
            return i;
779
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
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
0
                    i = ret;
776
0
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
0
                    i = ret;
776
0
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
20
            for (int ret : ret_vals) {
774
20
                if (ret != 0) {
775
0
                    i = ret;
776
0
                }
777
20
            }
778
10
            return i;
779
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
0
                    i = ret;
776
0
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
0
                    i = ret;
776
0
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
0
                    i = ret;
776
0
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
20
            for (int ret : ret_vals) {
774
20
                if (ret != 0) {
775
0
                    i = ret;
776
0
                }
777
20
            }
778
10
            return i;
779
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
0
                    i = ret;
776
0
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
0
                    i = ret;
776
0
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
0
                    i = ret;
776
0
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
0
                    i = ret;
776
0
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
0
                    i = ret;
776
0
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
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
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
781
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
769
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
781
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
769
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
781
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
769
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
781
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
769
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
781
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
769
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
781
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
769
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
781
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
769
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
781
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
769
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
781
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
769
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
781
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
769
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
781
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
769
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
781
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
769
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
770
10
    return [funcs...]() {
771
10
        return [](std::initializer_list<int> ret_vals) {
772
10
            int i = 0;
773
10
            for (int ret : ret_vals) {
774
10
                if (ret != 0) {
775
10
                    i = ret;
776
10
                }
777
10
            }
778
10
            return i;
779
10
        }({funcs()...});
780
10
    };
781
10
}
782
783
10
int InstanceRecycler::do_recycle() {
784
10
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
785
10
    tablet_metrics_context_.reset();
786
10
    segment_metrics_context_.reset();
787
10
    DORIS_CLOUD_DEFER {
788
10
        tablet_metrics_context_.finish_report();
789
10
        segment_metrics_context_.finish_report();
790
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
787
10
    DORIS_CLOUD_DEFER {
788
10
        tablet_metrics_context_.finish_report();
789
10
        segment_metrics_context_.finish_report();
790
10
    };
791
10
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
792
0
        int res = recycle_cluster_snapshots();
793
0
        if (res != 0) {
794
0
            return -1;
795
0
        }
796
0
        return recycle_deleted_instance();
797
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
798
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
799
10
                                        fmt::format("instance id {}", instance_id_),
800
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
800
120
                                        [](int r) { return r != 0; });
801
10
        sync_executor
802
10
                .add(task_wrapper(
803
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
803
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
804
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
804
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
805
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
806
                                   // becase they may both recycle the same set of tablets
807
                        // recycle dropped table or idexes(mv, rollup)
808
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
808
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
809
                        // recycle dropped partitions
810
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
810
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
811
10
                .add(task_wrapper(
812
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
812
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
813
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
813
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
814
10
                .add(task_wrapper(
815
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
815
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
816
10
                .add(task_wrapper(
817
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
817
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
818
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
818
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
819
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
819
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
820
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
820
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
821
10
                .add(task_wrapper(
822
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
822
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
823
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
823
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
824
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
824
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
825
10
        bool finished = true;
826
10
        std::vector<int> rets = sync_executor.when_all(&finished);
827
120
        for (int ret : rets) {
828
120
            if (ret != 0) {
829
0
                return ret;
830
0
            }
831
120
        }
832
10
        return finished ? 0 : -1;
833
10
    } else {
834
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
835
0
                     << " instance_id=" << instance_id_;
836
0
        return -1;
837
0
    }
838
10
}
839
840
/**
841
* 1. delete all remote data
842
* 2. delete all kv
843
* 3. remove instance kv
844
*/
845
5
int InstanceRecycler::recycle_deleted_instance() {
846
5
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
847
848
5
    int ret = 0;
849
5
    auto start_time = steady_clock::now();
850
851
5
    DORIS_CLOUD_DEFER {
852
5
        auto cost = duration<float>(steady_clock::now() - start_time).count();
853
5
        LOG(WARNING) << (ret == 0 ? "successfully" : "failed to")
854
5
                     << " recycle deleted instance, cost=" << cost
855
5
                     << "s, instance_id=" << instance_id_;
856
5
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
851
5
    DORIS_CLOUD_DEFER {
852
5
        auto cost = duration<float>(steady_clock::now() - start_time).count();
853
5
        LOG(WARNING) << (ret == 0 ? "successfully" : "failed to")
854
5
                     << " recycle deleted instance, cost=" << cost
855
5
                     << "s, instance_id=" << instance_id_;
856
5
    };
857
858
    // Step 1: Recycle tmp rowsets (contains ref count but txn is not committed)
859
5
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
860
5
        int res = recycle_tmp_rowsets();
861
5
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
862
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
863
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
864
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
865
            // and cannot be recycled.
866
0
            res = recycle_tmp_rowsets();
867
0
        }
868
5
        return res;
869
5
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_1clEv
Line
Count
Source
859
5
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
860
5
        int res = recycle_tmp_rowsets();
861
5
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
862
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
863
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
864
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
865
            // and cannot be recycled.
866
0
            res = recycle_tmp_rowsets();
867
0
        }
868
5
        return res;
869
5
    };
870
5
    if (recycle_tmp_rowsets_with_mark_delete_enabled() != 0) {
871
0
        LOG_WARNING("failed to recycle tmp rowsets").tag("instance_id", instance_id_);
872
0
        ret = -1;
873
0
        return -1;
874
0
    }
875
876
    // Step 2: Recycle versioned rowsets in recycle space (already marked for deletion)
877
5
    if (recycle_versioned_rowsets() != 0) {
878
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
879
0
        ret = -1;
880
0
        return -1;
881
0
    }
882
883
    // Step 3: Recycle operation logs (can recycle logs not referenced by snapshots)
884
5
    if (recycle_operation_logs() != 0) {
885
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
886
0
        ret = -1;
887
0
        return -1;
888
0
    }
889
890
    // Step 4: Check if there are still cluster snapshots
891
5
    bool has_snapshots = false;
892
5
    if (has_cluster_snapshots(&has_snapshots) != 0) {
893
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
894
0
        ret = -1;
895
0
        return -1;
896
5
    } else if (has_snapshots) {
897
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
898
1
        return 0;
899
1
    }
900
901
4
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
902
4
                            instance_info().snapshot_switch_status() !=
903
1
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
904
4
    if (snapshot_enabled) {
905
1
        bool has_unrecycled_rowsets = false;
906
1
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
907
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
908
0
            ret = -1;
909
0
            return -1;
910
1
        } else if (has_unrecycled_rowsets) {
911
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
912
0
                    .tag("instance_id", instance_id_);
913
0
            return ret;
914
0
        }
915
3
    } else { // delete all remote data if snapshot is disabled
916
3
        for (auto& [_, accessor] : accessor_map_) {
917
3
            if (stopped()) {
918
0
                return ret;
919
0
            }
920
921
3
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
922
3
            int del_ret = accessor->delete_all();
923
3
            if (del_ret == 0) {
924
3
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
925
3
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
926
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
927
                // so the recycling has been successful.
928
0
                ret = -1;
929
0
            }
930
3
        }
931
932
3
        if (ret != 0) {
933
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
934
0
            return ret;
935
0
        }
936
3
    }
937
938
    // Check successor instance, if exists, skip deleting kv because successor instance may still need the data in kv
939
4
    if (instance_info_.has_successor_instance_id() &&
940
4
        !instance_info_.successor_instance_id().empty()) {
941
0
        std::string key = instance_key(instance_info_.successor_instance_id());
942
0
        std::unique_ptr<Transaction> txn;
943
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
944
0
        if (err != TxnErrorCode::TXN_OK) {
945
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_
946
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
947
0
                         << " err=" << err;
948
0
            ret = -1;
949
0
            return -1;
950
0
        }
951
952
0
        std::string value;
953
0
        err = txn->get(key, &value);
954
0
        if (err == TxnErrorCode::TXN_OK) {
955
0
            LOG(INFO) << "instance successor instance is still exist, skip deleting kv,"
956
0
                      << " instance_id=" << instance_id_
957
0
                      << " successor_instance_id=" << instance_info_.successor_instance_id();
958
0
            return 0;
959
0
        } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
960
0
            LOG(WARNING) << "failed to get successor instance, instance_id=" << instance_id_
961
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
962
0
                         << " err=" << err;
963
0
            ret = -1;
964
0
            return -1;
965
0
        }
966
0
    }
967
968
    // delete all kv
969
4
    std::unique_ptr<Transaction> txn;
970
4
    TxnErrorCode err = txn_kv_->create_txn(&txn);
971
4
    if (err != TxnErrorCode::TXN_OK) {
972
0
        LOG(WARNING) << "failed to create txn";
973
0
        ret = -1;
974
0
        return -1;
975
0
    }
976
4
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
977
    // delete kv before deleting objects to prevent the checker from misjudging data loss
978
4
    std::string start_txn_key = txn_key_prefix(instance_id_);
979
4
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
980
4
    txn->remove(start_txn_key, end_txn_key);
981
4
    std::string start_version_key = version_key_prefix(instance_id_);
982
4
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
983
4
    txn->remove(start_version_key, end_version_key);
984
4
    std::string start_meta_key = meta_key_prefix(instance_id_);
985
4
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
986
4
    txn->remove(start_meta_key, end_meta_key);
987
4
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
988
4
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
989
4
    txn->remove(start_recycle_key, end_recycle_key);
990
4
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
991
4
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
992
4
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
993
4
    std::string start_copy_key = copy_key_prefix(instance_id_);
994
4
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
995
4
    txn->remove(start_copy_key, end_copy_key);
996
    // should not remove job key range, because we need to reserve job recycle kv
997
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
998
4
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
999
4
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1000
4
    txn->remove(start_job_tablet_key, end_job_tablet_key);
1001
4
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
1002
4
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
1003
4
    std::string start_vault_key = storage_vault_key(key_info0);
1004
4
    std::string end_vault_key = storage_vault_key(key_info1);
1005
4
    txn->remove(start_vault_key, end_vault_key);
1006
4
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
1007
4
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
1008
4
    txn->remove(versioned_version_key_start, versioned_version_key_end);
1009
4
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
1010
4
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
1011
4
    txn->remove(versioned_index_key_start, versioned_index_key_end);
1012
4
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
1013
4
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
1014
4
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
1015
4
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
1016
4
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
1017
4
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
1018
4
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
1019
4
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
1020
4
    txn->remove(versioned_data_key_start, versioned_data_key_end);
1021
4
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
1022
4
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
1023
4
    txn->remove(versioned_log_key_start, versioned_log_key_end);
1024
4
    err = txn->commit();
1025
4
    if (err != TxnErrorCode::TXN_OK) {
1026
0
        LOG(WARNING) << "failed to delete all kv, instance_id=" << instance_id_ << ", err=" << err;
1027
0
        ret = -1;
1028
0
    }
1029
1030
4
    if (ret == 0) {
1031
        // remove instance kv
1032
        // ATTN: MUST ensure that cloud platform won't regenerate the same instance id
1033
4
        err = txn_kv_->create_txn(&txn);
1034
4
        if (err != TxnErrorCode::TXN_OK) {
1035
0
            LOG(WARNING) << "failed to create txn";
1036
0
            ret = -1;
1037
0
            return ret;
1038
0
        }
1039
4
        std::string key;
1040
4
        instance_key({instance_id_}, &key);
1041
4
        txn->atomic_add(system_meta_service_instance_update_key(), 1);
1042
4
        txn->remove(key);
1043
4
        err = txn->commit();
1044
4
        if (err != TxnErrorCode::TXN_OK) {
1045
0
            LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
1046
0
                         << " err=" << err;
1047
0
            ret = -1;
1048
0
        }
1049
4
    }
1050
4
    return ret;
1051
4
}
1052
1053
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
1054
9
                                          bool* exists, PackedFileRecycleStats* stats) {
1055
9
    if (exists == nullptr) {
1056
0
        return -1;
1057
0
    }
1058
9
    *exists = false;
1059
1060
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
1061
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1062
9
    std::string scan_begin = begin;
1063
1064
9
    while (true) {
1065
9
        std::unique_ptr<RangeGetIterator> it_range;
1066
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
1067
9
        if (get_ret < 0) {
1068
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1069
0
                    .tag("instance_id", instance_id_)
1070
0
                    .tag("tablet_id", tablet_id)
1071
0
                    .tag("ret", get_ret);
1072
0
            return -1;
1073
0
        }
1074
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1075
6
            return 0;
1076
6
        }
1077
1078
3
        std::string last_key;
1079
3
        while (it_range->has_next()) {
1080
3
            auto [k, v] = it_range->next();
1081
3
            last_key.assign(k.data(), k.size());
1082
3
            doris::RowsetMetaCloudPB rowset_meta;
1083
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1084
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1085
0
                        .tag("instance_id", instance_id_)
1086
0
                        .tag("tablet_id", tablet_id)
1087
0
                        .tag("key", hex(k));
1088
0
                continue;
1089
0
            }
1090
3
            if (stats) {
1091
3
                ++stats->rowset_scan_count;
1092
3
            }
1093
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1094
3
                *exists = true;
1095
3
                return 0;
1096
3
            }
1097
3
        }
1098
1099
0
        if (!it_range->more()) {
1100
0
            return 0;
1101
0
        }
1102
1103
        // Continue scanning from the next key to keep each transaction short.
1104
0
        scan_begin = std::move(last_key);
1105
0
        scan_begin.push_back('\x00');
1106
0
    }
1107
9
}
1108
1109
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1110
                                                          const std::string& rowset_id,
1111
                                                          int64_t txn_id, bool* recycle_exists,
1112
11
                                                          bool* tmp_exists) {
1113
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1114
0
        return -1;
1115
0
    }
1116
11
    *recycle_exists = false;
1117
11
    *tmp_exists = false;
1118
1119
11
    if (txn_id <= 0) {
1120
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1121
0
                .tag("instance_id", instance_id_)
1122
0
                .tag("tablet_id", tablet_id)
1123
0
                .tag("rowset_id", rowset_id)
1124
0
                .tag("txn_id", txn_id);
1125
0
        return -1;
1126
0
    }
1127
1128
11
    std::unique_ptr<Transaction> txn;
1129
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1130
11
    if (err != TxnErrorCode::TXN_OK) {
1131
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1132
0
                .tag("instance_id", instance_id_)
1133
0
                .tag("tablet_id", tablet_id)
1134
0
                .tag("rowset_id", rowset_id)
1135
0
                .tag("txn_id", txn_id)
1136
0
                .tag("err", err);
1137
0
        return -1;
1138
0
    }
1139
1140
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1141
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1142
11
    if (ret == TxnErrorCode::TXN_OK) {
1143
1
        *recycle_exists = true;
1144
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1145
0
        LOG_WARNING("failed to check recycle rowset existence")
1146
0
                .tag("instance_id", instance_id_)
1147
0
                .tag("tablet_id", tablet_id)
1148
0
                .tag("rowset_id", rowset_id)
1149
0
                .tag("key", hex(recycle_key))
1150
0
                .tag("err", ret);
1151
0
        return -1;
1152
0
    }
1153
1154
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1155
11
    ret = key_exists(txn.get(), tmp_key, true);
1156
11
    if (ret == TxnErrorCode::TXN_OK) {
1157
1
        *tmp_exists = true;
1158
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1159
0
        LOG_WARNING("failed to check tmp rowset existence")
1160
0
                .tag("instance_id", instance_id_)
1161
0
                .tag("tablet_id", tablet_id)
1162
0
                .tag("txn_id", txn_id)
1163
0
                .tag("key", hex(tmp_key))
1164
0
                .tag("err", ret);
1165
0
        return -1;
1166
0
    }
1167
1168
11
    return 0;
1169
11
}
1170
1171
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1172
8
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1173
8
    if (!hint.empty()) {
1174
8
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1175
8
            return {hint, it->second};
1176
8
        }
1177
8
    }
1178
1179
0
    return {"", nullptr};
1180
8
}
1181
1182
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1183
                                               const std::string& packed_file_path,
1184
3
                                               PackedFileRecycleStats* stats) {
1185
3
    bool local_changed = false;
1186
3
    int64_t left_num = 0;
1187
3
    int64_t left_bytes = 0;
1188
3
    bool all_small_files_confirmed = true;
1189
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1190
1191
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1192
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1193
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1194
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1195
14
        LOG_INFO("packed slice correction status")
1196
14
                .tag("instance_id", instance_id_)
1197
14
                .tag("packed_file_path", packed_file_path)
1198
14
                .tag("small_file_path", file.path())
1199
14
                .tag("tablet_id", tablet_id)
1200
14
                .tag("rowset_id", rowset_id)
1201
14
                .tag("txn_id", txn_id)
1202
14
                .tag("size", file.size())
1203
14
                .tag("deleted", file.deleted())
1204
14
                .tag("corrected", file.corrected())
1205
14
                .tag("confirmed_this_round", confirmed_this_round);
1206
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
1191
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1192
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1193
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1194
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1195
14
        LOG_INFO("packed slice correction status")
1196
14
                .tag("instance_id", instance_id_)
1197
14
                .tag("packed_file_path", packed_file_path)
1198
14
                .tag("small_file_path", file.path())
1199
14
                .tag("tablet_id", tablet_id)
1200
14
                .tag("rowset_id", rowset_id)
1201
14
                .tag("txn_id", txn_id)
1202
14
                .tag("size", file.size())
1203
14
                .tag("deleted", file.deleted())
1204
14
                .tag("corrected", file.corrected())
1205
14
                .tag("confirmed_this_round", confirmed_this_round);
1206
14
    };
1207
1208
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1209
14
        auto* small_file = packed_info->mutable_slices(i);
1210
14
        if (small_file->deleted()) {
1211
3
            log_small_file_status(*small_file, small_file->corrected());
1212
3
            continue;
1213
3
        }
1214
1215
11
        if (small_file->corrected()) {
1216
0
            left_num++;
1217
0
            left_bytes += small_file->size();
1218
0
            log_small_file_status(*small_file, true);
1219
0
            continue;
1220
0
        }
1221
1222
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1223
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1224
0
                    .tag("instance_id", instance_id_)
1225
0
                    .tag("small_file_path", small_file->path())
1226
0
                    .tag("index", i);
1227
0
            return -1;
1228
0
        }
1229
1230
11
        int64_t tablet_id = small_file->tablet_id();
1231
11
        const std::string& rowset_id = small_file->rowset_id();
1232
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1233
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1234
0
                    .tag("instance_id", instance_id_)
1235
0
                    .tag("small_file_path", small_file->path())
1236
0
                    .tag("index", i)
1237
0
                    .tag("tablet_id", tablet_id)
1238
0
                    .tag("rowset_id", rowset_id)
1239
0
                    .tag("has_txn_id", small_file->has_txn_id())
1240
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1241
0
            return -1;
1242
0
        }
1243
11
        int64_t txn_id = small_file->txn_id();
1244
11
        bool recycle_exists = false;
1245
11
        bool tmp_exists = false;
1246
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1247
11
                                                &tmp_exists) != 0) {
1248
0
            return -1;
1249
0
        }
1250
1251
11
        bool small_file_confirmed = false;
1252
11
        if (tmp_exists) {
1253
1
            left_num++;
1254
1
            left_bytes += small_file->size();
1255
1
            small_file_confirmed = true;
1256
10
        } else if (recycle_exists) {
1257
1
            left_num++;
1258
1
            left_bytes += small_file->size();
1259
            // keep small_file_confirmed=false so the packed file remains uncorrected
1260
9
        } else {
1261
9
            bool rowset_exists = false;
1262
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1263
0
                return -1;
1264
0
            }
1265
1266
9
            if (!rowset_exists) {
1267
6
                if (!small_file->deleted()) {
1268
6
                    small_file->set_deleted(true);
1269
6
                    local_changed = true;
1270
6
                }
1271
6
                if (!small_file->corrected()) {
1272
6
                    small_file->set_corrected(true);
1273
6
                    local_changed = true;
1274
6
                }
1275
6
                small_file_confirmed = true;
1276
6
            } else {
1277
3
                left_num++;
1278
3
                left_bytes += small_file->size();
1279
3
                small_file_confirmed = true;
1280
3
            }
1281
9
        }
1282
1283
11
        if (!small_file_confirmed) {
1284
1
            all_small_files_confirmed = false;
1285
1
        }
1286
1287
11
        if (small_file->corrected() != small_file_confirmed) {
1288
4
            small_file->set_corrected(small_file_confirmed);
1289
4
            local_changed = true;
1290
4
        }
1291
1292
11
        log_small_file_status(*small_file, small_file_confirmed);
1293
11
    }
1294
1295
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1296
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1297
3
        local_changed = true;
1298
3
    }
1299
3
    if (packed_info->ref_cnt() != left_num) {
1300
3
        auto old_ref_cnt = packed_info->ref_cnt();
1301
3
        packed_info->set_ref_cnt(left_num);
1302
3
        LOG_INFO("corrected packed file ref count")
1303
3
                .tag("instance_id", instance_id_)
1304
3
                .tag("resource_id", packed_info->resource_id())
1305
3
                .tag("packed_file_path", packed_file_path)
1306
3
                .tag("old_ref_cnt", old_ref_cnt)
1307
3
                .tag("new_ref_cnt", left_num);
1308
3
        local_changed = true;
1309
3
    }
1310
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1311
2
        packed_info->set_corrected(all_small_files_confirmed);
1312
2
        local_changed = true;
1313
2
    }
1314
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1315
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1316
1
        local_changed = true;
1317
1
    }
1318
1319
3
    if (changed != nullptr) {
1320
3
        *changed = local_changed;
1321
3
    }
1322
3
    return 0;
1323
3
}
1324
1325
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1326
                                                 const std::string& packed_file_path,
1327
3
                                                 PackedFileRecycleStats* stats) {
1328
3
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1329
3
    bool correction_ok = false;
1330
3
    cloud::PackedFileInfoPB packed_info;
1331
1332
3
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1333
3
        if (stopped()) {
1334
0
            LOG_WARNING("recycler stopped before processing packed file")
1335
0
                    .tag("instance_id", instance_id_)
1336
0
                    .tag("packed_file_path", packed_file_path)
1337
0
                    .tag("attempt", attempt);
1338
0
            return -1;
1339
0
        }
1340
1341
3
        std::unique_ptr<Transaction> txn;
1342
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1343
3
        if (err != TxnErrorCode::TXN_OK) {
1344
0
            LOG_WARNING("failed to create txn when processing packed file")
1345
0
                    .tag("instance_id", instance_id_)
1346
0
                    .tag("packed_file_path", packed_file_path)
1347
0
                    .tag("attempt", attempt)
1348
0
                    .tag("err", err);
1349
0
            return -1;
1350
0
        }
1351
1352
3
        std::string packed_val;
1353
3
        err = txn->get(packed_key, &packed_val);
1354
3
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1355
0
            return 0;
1356
0
        }
1357
3
        if (err != TxnErrorCode::TXN_OK) {
1358
0
            LOG_WARNING("failed to get packed file kv")
1359
0
                    .tag("instance_id", instance_id_)
1360
0
                    .tag("packed_file_path", packed_file_path)
1361
0
                    .tag("attempt", attempt)
1362
0
                    .tag("err", err);
1363
0
            return -1;
1364
0
        }
1365
1366
3
        if (!packed_info.ParseFromString(packed_val)) {
1367
0
            LOG_WARNING("failed to parse packed file info")
1368
0
                    .tag("instance_id", instance_id_)
1369
0
                    .tag("packed_file_path", packed_file_path)
1370
0
                    .tag("attempt", attempt);
1371
0
            return -1;
1372
0
        }
1373
1374
3
        int64_t now_sec = ::time(nullptr);
1375
3
        bool corrected = packed_info.corrected();
1376
3
        bool due = config::force_immediate_recycle ||
1377
3
                   now_sec - packed_info.created_at_sec() >=
1378
3
                           config::packed_file_correction_delay_seconds;
1379
1380
3
        if (!corrected && due) {
1381
3
            bool changed = false;
1382
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1383
0
                LOG_WARNING("correct_packed_file_info failed")
1384
0
                        .tag("instance_id", instance_id_)
1385
0
                        .tag("packed_file_path", packed_file_path)
1386
0
                        .tag("attempt", attempt);
1387
0
                return -1;
1388
0
            }
1389
3
            if (changed) {
1390
3
                std::string updated;
1391
3
                if (!packed_info.SerializeToString(&updated)) {
1392
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1393
0
                            .tag("instance_id", instance_id_)
1394
0
                            .tag("packed_file_path", packed_file_path)
1395
0
                            .tag("attempt", attempt);
1396
0
                    return -1;
1397
0
                }
1398
3
                txn->put(packed_key, updated);
1399
3
                err = txn->commit();
1400
3
                if (err == TxnErrorCode::TXN_OK) {
1401
3
                    if (stats) {
1402
3
                        ++stats->num_corrected;
1403
3
                    }
1404
3
                } else {
1405
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1406
0
                        LOG_WARNING(
1407
0
                                "failed to commit correction for packed file due to conflict, "
1408
0
                                "retrying")
1409
0
                                .tag("instance_id", instance_id_)
1410
0
                                .tag("packed_file_path", packed_file_path)
1411
0
                                .tag("attempt", attempt);
1412
0
                        sleep_for_packed_file_retry();
1413
0
                        packed_info.Clear();
1414
0
                        continue;
1415
0
                    }
1416
0
                    LOG_WARNING("failed to commit correction for packed file")
1417
0
                            .tag("instance_id", instance_id_)
1418
0
                            .tag("packed_file_path", packed_file_path)
1419
0
                            .tag("attempt", attempt)
1420
0
                            .tag("err", err);
1421
0
                    return -1;
1422
0
                }
1423
3
            }
1424
3
        }
1425
1426
3
        correction_ok = true;
1427
3
        break;
1428
3
    }
1429
1430
3
    if (!correction_ok) {
1431
0
        return -1;
1432
0
    }
1433
1434
3
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1435
3
          packed_info.ref_cnt() == 0)) {
1436
2
        return 0;
1437
2
    }
1438
1439
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1440
0
        LOG_WARNING("packed file missing resource id when recycling")
1441
0
                .tag("instance_id", instance_id_)
1442
0
                .tag("packed_file_path", packed_file_path);
1443
0
        return -1;
1444
0
    }
1445
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1446
1
    if (!accessor) {
1447
0
        LOG_WARNING("no accessor available to delete packed file")
1448
0
                .tag("instance_id", instance_id_)
1449
0
                .tag("packed_file_path", packed_file_path)
1450
0
                .tag("resource_id", packed_info.resource_id());
1451
0
        return -1;
1452
0
    }
1453
1
    int del_ret = accessor->delete_file(packed_file_path);
1454
1
    if (del_ret != 0 && del_ret != 1) {
1455
0
        LOG_WARNING("failed to delete packed file")
1456
0
                .tag("instance_id", instance_id_)
1457
0
                .tag("packed_file_path", packed_file_path)
1458
0
                .tag("resource_id", resource_id)
1459
0
                .tag("ret", del_ret);
1460
0
        return -1;
1461
0
    }
1462
1
    if (del_ret == 1) {
1463
0
        LOG_INFO("packed file already removed")
1464
0
                .tag("instance_id", instance_id_)
1465
0
                .tag("packed_file_path", packed_file_path)
1466
0
                .tag("resource_id", resource_id);
1467
1
    } else {
1468
1
        LOG_INFO("deleted packed file")
1469
1
                .tag("instance_id", instance_id_)
1470
1
                .tag("packed_file_path", packed_file_path)
1471
1
                .tag("resource_id", resource_id);
1472
1
    }
1473
1474
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1475
1
        std::unique_ptr<Transaction> del_txn;
1476
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1477
1
        if (err != TxnErrorCode::TXN_OK) {
1478
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1479
0
                    .tag("instance_id", instance_id_)
1480
0
                    .tag("packed_file_path", packed_file_path)
1481
0
                    .tag("del_attempt", del_attempt)
1482
0
                    .tag("err", err);
1483
0
            return -1;
1484
0
        }
1485
1486
1
        std::string latest_val;
1487
1
        err = del_txn->get(packed_key, &latest_val);
1488
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1489
0
            return 0;
1490
0
        }
1491
1
        if (err != TxnErrorCode::TXN_OK) {
1492
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1493
0
                    .tag("instance_id", instance_id_)
1494
0
                    .tag("packed_file_path", packed_file_path)
1495
0
                    .tag("del_attempt", del_attempt)
1496
0
                    .tag("err", err);
1497
0
            return -1;
1498
0
        }
1499
1500
1
        cloud::PackedFileInfoPB latest_info;
1501
1
        if (!latest_info.ParseFromString(latest_val)) {
1502
0
            LOG_WARNING("failed to parse packed file info before removal")
1503
0
                    .tag("instance_id", instance_id_)
1504
0
                    .tag("packed_file_path", packed_file_path)
1505
0
                    .tag("del_attempt", del_attempt);
1506
0
            return -1;
1507
0
        }
1508
1509
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1510
1
              latest_info.ref_cnt() == 0)) {
1511
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1512
0
                    .tag("instance_id", instance_id_)
1513
0
                    .tag("packed_file_path", packed_file_path)
1514
0
                    .tag("del_attempt", del_attempt);
1515
0
            return 0;
1516
0
        }
1517
1518
1
        del_txn->remove(packed_key);
1519
1
        err = del_txn->commit();
1520
1
        if (err == TxnErrorCode::TXN_OK) {
1521
1
            if (stats) {
1522
1
                ++stats->num_deleted;
1523
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1524
1
                                        static_cast<int64_t>(latest_val.size());
1525
1
                if (del_ret == 0 || del_ret == 1) {
1526
1
                    ++stats->num_object_deleted;
1527
1
                    int64_t object_size = latest_info.total_slice_bytes();
1528
1
                    if (object_size <= 0) {
1529
0
                        object_size = packed_info.total_slice_bytes();
1530
0
                    }
1531
1
                    stats->bytes_object_deleted += object_size;
1532
1
                }
1533
1
            }
1534
1
            LOG_INFO("removed packed file metadata")
1535
1
                    .tag("instance_id", instance_id_)
1536
1
                    .tag("packed_file_path", packed_file_path);
1537
1
            return 0;
1538
1
        }
1539
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1540
0
            if (del_attempt >= max_retry_times) {
1541
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1542
0
                        .tag("instance_id", instance_id_)
1543
0
                        .tag("packed_file_path", packed_file_path)
1544
0
                        .tag("del_attempt", del_attempt);
1545
0
                return -1;
1546
0
            }
1547
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1548
0
                    .tag("instance_id", instance_id_)
1549
0
                    .tag("packed_file_path", packed_file_path)
1550
0
                    .tag("del_attempt", del_attempt);
1551
0
            sleep_for_packed_file_retry();
1552
0
            continue;
1553
0
        }
1554
0
        LOG_WARNING("failed to remove packed file kv")
1555
0
                .tag("instance_id", instance_id_)
1556
0
                .tag("packed_file_path", packed_file_path)
1557
0
                .tag("del_attempt", del_attempt)
1558
0
                .tag("err", err);
1559
0
        return -1;
1560
0
    }
1561
1562
0
    return -1;
1563
1
}
1564
1565
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view value,
1566
4
                                            PackedFileRecycleStats* stats, int* ret) {
1567
4
    if (stats) {
1568
4
        ++stats->num_scanned;
1569
4
    }
1570
4
    std::string packed_file_path;
1571
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1572
0
        LOG_WARNING("failed to decode packed file key")
1573
0
                .tag("instance_id", instance_id_)
1574
0
                .tag("key", hex(key));
1575
0
        if (stats) {
1576
0
            ++stats->num_failed;
1577
0
        }
1578
0
        if (ret) {
1579
0
            *ret = -1;
1580
0
        }
1581
0
        return 0;
1582
0
    }
1583
1584
4
    cloud::PackedFileInfoPB packed_info;
1585
4
    if (!packed_info.ParseFromArray(value.data(), value.size())) {
1586
0
        LOG_WARNING("failed to parse packed file info from scan")
1587
0
                .tag("instance_id", instance_id_)
1588
0
                .tag("packed_file_path", packed_file_path);
1589
0
        if (stats) {
1590
0
            ++stats->num_failed;
1591
0
        }
1592
0
        if (ret) {
1593
0
            *ret = -1;
1594
0
        }
1595
0
        return 0;
1596
0
    }
1597
1598
4
    const int64_t now_sec = ::time(nullptr);
1599
4
    const bool due =
1600
4
            config::force_immediate_recycle ||
1601
4
            now_sec - packed_info.created_at_sec() >= config::packed_file_correction_delay_seconds;
1602
4
    const bool need_correction = !packed_info.corrected() && due;
1603
4
    const bool need_recycle =
1604
4
            packed_info.state() == cloud::PackedFileInfoPB::RECYCLING && packed_info.ref_cnt() == 0;
1605
4
    if (!need_correction && !need_recycle) {
1606
1
        return 0;
1607
1
    }
1608
1609
3
    std::string packed_key(key);
1610
3
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1611
3
    if (process_ret != 0) {
1612
0
        if (stats) {
1613
0
            ++stats->num_failed;
1614
0
        }
1615
0
        if (ret) {
1616
0
            *ret = -1;
1617
0
        }
1618
0
    }
1619
3
    return 0;
1620
4
}
1621
1622
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1623
6.06k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1624
6.06k
    if (config::force_immediate_recycle) {
1625
15
        return 0L;
1626
15
    }
1627
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1628
6.05k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1629
6.05k
    int64_t retention_seconds = config::retention_seconds;
1630
6.05k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1631
4.74k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1632
4.74k
    }
1633
6.05k
    int64_t final_expiration = expiration + retention_seconds;
1634
6.05k
    if (*earlest_ts > final_expiration) {
1635
16
        *earlest_ts = final_expiration;
1636
16
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1637
16
    }
1638
6.05k
    return final_expiration;
1639
6.06k
}
1640
1641
int64_t calculate_partition_expired_time(
1642
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1643
11
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1644
11
    if (config::force_immediate_recycle) {
1645
5
        return 0L;
1646
5
    }
1647
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1648
6
                                                            : partition_meta_pb.creation_time();
1649
6
    int64_t retention_seconds = config::retention_seconds;
1650
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1651
6
        retention_seconds =
1652
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1653
6
    }
1654
6
    int64_t final_expiration = expiration + retention_seconds;
1655
6
    if (*earlest_ts > final_expiration) {
1656
2
        *earlest_ts = final_expiration;
1657
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1658
2
    }
1659
6
    return final_expiration;
1660
11
}
1661
1662
int64_t calculate_index_expired_time(const std::string& instance_id_,
1663
                                     const RecycleIndexPB& index_meta_pb,
1664
14
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1665
14
    if (config::force_immediate_recycle) {
1666
8
        return 0L;
1667
8
    }
1668
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1669
6
                                                        : index_meta_pb.creation_time();
1670
6
    int64_t retention_seconds = config::retention_seconds;
1671
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1672
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1673
6
    }
1674
6
    int64_t final_expiration = expiration + retention_seconds;
1675
6
    if (*earlest_ts > final_expiration) {
1676
2
        *earlest_ts = final_expiration;
1677
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1678
2
    }
1679
6
    return final_expiration;
1680
14
}
1681
1682
int64_t calculate_tmp_rowset_expired_time(
1683
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1684
53.0k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1685
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1686
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1687
    //  duration or timeout always < `retention_time` in practice.
1688
53.0k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1689
53.0k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1690
53.0k
                                 : tmp_rowset_meta_pb.creation_time();
1691
53.0k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1692
53.0k
    int64_t final_expiration = expiration + config::retention_seconds;
1693
53.0k
    if (*earlest_ts > final_expiration) {
1694
18
        *earlest_ts = final_expiration;
1695
18
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1696
18
    }
1697
53.0k
    return final_expiration;
1698
53.0k
}
1699
1700
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1701
30.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1702
30.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1703
30.0k
    if (*earlest_ts > final_expiration / 1000) {
1704
8
        *earlest_ts = final_expiration / 1000;
1705
8
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1706
8
    }
1707
30.0k
    return final_expiration;
1708
30.0k
}
1709
1710
int64_t calculate_restore_job_expired_time(
1711
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1712
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1713
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1714
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1715
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1716
        // final state, recycle immediately
1717
41
        return 0L;
1718
41
    }
1719
    // not final state, wait much longer than the FE's timeout(1 day)
1720
0
    int64_t last_modified_s =
1721
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1722
0
    int64_t expiration = restore_job.expired_at_s() > 0
1723
0
                                 ? last_modified_s + restore_job.expired_at_s()
1724
0
                                 : last_modified_s;
1725
0
    int64_t final_expiration = expiration + config::retention_seconds;
1726
0
    if (*earlest_ts > final_expiration) {
1727
0
        *earlest_ts = final_expiration;
1728
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1729
0
    }
1730
0
    return final_expiration;
1731
41
}
1732
1733
2
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1734
2
    AbortTxnRequest req;
1735
2
    TxnInfoPB txn_info;
1736
2
    MetaServiceCode code = MetaServiceCode::OK;
1737
2
    std::string msg;
1738
2
    std::stringstream ss;
1739
2
    std::unique_ptr<Transaction> txn;
1740
2
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1741
2
    if (err != TxnErrorCode::TXN_OK) {
1742
0
        LOG_WARNING("failed to create txn").tag("err", err);
1743
0
        return -1;
1744
0
    }
1745
1746
    // get txn index
1747
2
    TxnIndexPB txn_idx_pb;
1748
2
    auto index_key = txn_index_key({instance_id_, txn_id});
1749
2
    std::string index_val;
1750
2
    err = txn->get(index_key, &index_val);
1751
2
    if (err != TxnErrorCode::TXN_OK) {
1752
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1753
            // maybe recycled
1754
0
            LOG_INFO("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1755
0
                    .tag("key", hex(index_key))
1756
0
                    .tag("txn_id", txn_id);
1757
0
            return 0;
1758
0
        }
1759
0
        LOG_WARNING("failed to get txn index")
1760
0
                .tag("err", err)
1761
0
                .tag("key", hex(index_key))
1762
0
                .tag("txn_id", txn_id);
1763
0
        return -1;
1764
0
    }
1765
2
    if (!txn_idx_pb.ParseFromString(index_val)) {
1766
0
        LOG_WARNING("failed to parse txn index")
1767
0
                .tag("err", err)
1768
0
                .tag("key", hex(index_key))
1769
0
                .tag("txn_id", txn_id);
1770
0
        return -1;
1771
0
    }
1772
1773
2
    auto info_key = txn_info_key({instance_id_, txn_idx_pb.tablet_index().db_id(), txn_id});
1774
2
    std::string info_val;
1775
2
    err = txn->get(info_key, &info_val);
1776
2
    if (err != TxnErrorCode::TXN_OK) {
1777
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1778
            // maybe recycled
1779
0
            LOG_INFO("txn info not found, txn_id={} instance_id={}", txn_id, instance_id_)
1780
0
                    .tag("key", hex(info_key))
1781
0
                    .tag("txn_id", txn_id);
1782
0
            return 0;
1783
0
        }
1784
0
        LOG_WARNING("failed to get txn info")
1785
0
                .tag("err", err)
1786
0
                .tag("key", hex(info_key))
1787
0
                .tag("txn_id", txn_id);
1788
0
        return -1;
1789
0
    }
1790
2
    if (!txn_info.ParseFromString(info_val)) {
1791
0
        LOG_WARNING("failed to parse txn info")
1792
0
                .tag("err", err)
1793
0
                .tag("key", hex(info_key))
1794
0
                .tag("txn_id", txn_id);
1795
0
        return -1;
1796
0
    }
1797
1798
2
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
1799
0
        LOG_INFO("txn is not prepared status, txn_id={} status={}", txn_id, txn_info.status())
1800
0
                .tag("key", hex(info_key))
1801
0
                .tag("txn_id", txn_id);
1802
0
        return 0;
1803
0
    }
1804
1805
2
    req.set_txn_id(txn_id);
1806
1807
2
    LOG(INFO) << "begin abort txn for related rowset, txn_id=" << txn_id
1808
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString();
1809
1810
2
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
1811
2
    err = txn->commit();
1812
2
    if (err != TxnErrorCode::TXN_OK) {
1813
0
        code = cast_as<ErrCategory::COMMIT>(err);
1814
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
1815
0
        msg = ss.str();
1816
0
        return -1;
1817
0
    }
1818
1819
2
    LOG(INFO) << "finish abort txn for related rowset, txn_id=" << txn_id
1820
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString()
1821
2
              << " code=" << code << " msg=" << msg;
1822
1823
2
    return 0;
1824
2
}
1825
1826
4
int InstanceRecycler::abort_job_for_related_rowset(const RowsetMetaCloudPB& rowset_meta) {
1827
4
    FinishTabletJobRequest req;
1828
4
    FinishTabletJobResponse res;
1829
4
    req.set_action(FinishTabletJobRequest::ABORT);
1830
4
    MetaServiceCode code = MetaServiceCode::OK;
1831
4
    std::string msg;
1832
4
    std::stringstream ss;
1833
1834
4
    TabletIndexPB tablet_idx;
1835
4
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, rowset_meta.tablet_id(), tablet_idx);
1836
4
    if (ret == 1) {
1837
        // tablet maybe recycled, directly return 0
1838
1
        return 0;
1839
3
    } else if (ret != 0) {
1840
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << rowset_meta.tablet_id()
1841
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
1842
0
        return ret;
1843
0
    }
1844
1845
3
    std::unique_ptr<Transaction> txn;
1846
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1847
3
    if (err != TxnErrorCode::TXN_OK) {
1848
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
1849
0
        return -1;
1850
0
    }
1851
1852
3
    std::string job_key =
1853
3
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
1854
3
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
1855
3
    std::string job_val;
1856
3
    err = txn->get(job_key, &job_val);
1857
3
    if (err != TxnErrorCode::TXN_OK) {
1858
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1859
0
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
1860
0
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
1861
0
            return 0;
1862
0
        }
1863
0
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
1864
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
1865
0
                     << " key=" << hex(job_key);
1866
0
        return -1;
1867
0
    }
1868
1869
3
    TabletJobInfoPB job_pb;
1870
3
    if (!job_pb.ParseFromString(job_val)) {
1871
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
1872
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
1873
0
        return -1;
1874
0
    }
1875
1876
3
    std::string job_id {};
1877
3
    if (!job_pb.compaction().empty()) {
1878
2
        for (const auto& c : job_pb.compaction()) {
1879
2
            if (c.id() == rowset_meta.job_id()) {
1880
2
                job_id = c.id();
1881
2
                break;
1882
2
            }
1883
2
        }
1884
2
    } else if (job_pb.has_schema_change()) {
1885
1
        job_id = job_pb.schema_change().id();
1886
1
    }
1887
1888
3
    if (!job_id.empty() && rowset_meta.job_id() == job_id) {
1889
3
        LOG(INFO) << "begin to abort job for related rowset, job_id=" << rowset_meta.job_id()
1890
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
1891
3
        req.mutable_job()->CopyFrom(job_pb);
1892
3
        req.set_action(FinishTabletJobRequest::ABORT);
1893
3
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
1894
3
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
1895
3
                           ss);
1896
3
        if (code != MetaServiceCode::OK) {
1897
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
1898
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
1899
0
                         << " msg=" << msg;
1900
0
            return -1;
1901
0
        }
1902
3
        LOG(INFO) << "finish abort job for related rowset, job_id=" << rowset_meta.job_id()
1903
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
1904
3
                  << " code=" << code << " msg=" << msg;
1905
3
    } else {
1906
        // clang-format off
1907
0
        LOG(INFO) << "there is no job for related rowset, directly recycle rowset data"
1908
0
                  << ", instance_id=" << instance_id_ 
1909
0
                  << ", tablet_id=" << tablet_idx.tablet_id() 
1910
0
                  << ", job_id=" << job_id
1911
0
                  << ", rowset_id=" << rowset_meta.rowset_id_v2();
1912
        // clang-format on
1913
0
    }
1914
1915
3
    return 0;
1916
3
}
1917
1918
template <typename T>
1919
13
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
1920
13
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1921
9
        return rowset_meta_pb.mutable_rowset_meta();
1922
9
    } else {
1923
9
        return &rowset_meta_pb;
1924
9
    }
1925
13
}
_ZN5doris5cloud19mutable_rowset_metaINS0_15RecycleRowsetPBEEEPNS_17RowsetMetaCloudPBERT_
Line
Count
Source
1919
4
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
1920
4
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1921
4
        return rowset_meta_pb.mutable_rowset_meta();
1922
4
    } else {
1923
4
        return &rowset_meta_pb;
1924
4
    }
1925
4
}
_ZN5doris5cloud19mutable_rowset_metaINS_17RowsetMetaCloudPBEEEPS2_RT_
Line
Count
Source
1919
9
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
1920
9
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1921
9
        return rowset_meta_pb.mutable_rowset_meta();
1922
9
    } else {
1923
9
        return &rowset_meta_pb;
1924
9
    }
1925
9
}
1926
1927
template <typename T>
1928
51
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
1929
51
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1930
35
        return rowset_meta_pb.rowset_meta();
1931
35
    } else {
1932
35
        return rowset_meta_pb;
1933
35
    }
1934
51
}
_ZN5doris5cloud11rowset_metaINS0_15RecycleRowsetPBEEERKNS_17RowsetMetaCloudPBERKT_
Line
Count
Source
1928
16
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
1929
16
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1930
16
        return rowset_meta_pb.rowset_meta();
1931
16
    } else {
1932
16
        return rowset_meta_pb;
1933
16
    }
1934
16
}
_ZN5doris5cloud11rowset_metaINS_17RowsetMetaCloudPBEEERKS2_RKT_
Line
Count
Source
1928
35
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
1929
35
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1930
35
        return rowset_meta_pb.rowset_meta();
1931
35
    } else {
1932
35
        return rowset_meta_pb;
1933
35
    }
1934
35
}
1935
1936
struct DeferredRecycleAbortTask {
1937
    enum class Type : uint8_t {
1938
        TXN,
1939
        JOB,
1940
    };
1941
1942
    Type type = Type::TXN;
1943
    int64_t txn_id = 0;
1944
    int64_t tablet_id = 0;
1945
    int64_t start_version = 0;
1946
    int64_t end_version = 0;
1947
    std::string rowset_id;
1948
    std::string job_id;
1949
};
1950
1951
struct DeferredRecyclePrepareDeleteTask {
1952
    std::string key;
1953
    std::string resource_id;
1954
    std::string rowset_id;
1955
    int64_t tablet_id = 0;
1956
};
1957
1958
template <typename T>
1959
14
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
1960
14
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1961
4
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
1962
0
            return std::nullopt;
1963
0
        }
1964
4
    }
1965
1966
4
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1967
4
    DeferredRecycleAbortTask task;
1968
4
    task.tablet_id = rs_meta.tablet_id();
1969
4
    task.start_version = rs_meta.start_version();
1970
4
    task.end_version = rs_meta.end_version();
1971
14
    if (rs_meta.has_load_id()) {
1972
4
        task.type = DeferredRecycleAbortTask::Type::TXN;
1973
4
        task.txn_id = rs_meta.txn_id();
1974
4
        return task;
1975
4
    }
1976
10
    if (rs_meta.has_job_id()) {
1977
6
        task.type = DeferredRecycleAbortTask::Type::JOB;
1978
6
        task.rowset_id = rs_meta.rowset_id_v2();
1979
6
        task.job_id = rs_meta.job_id();
1980
6
        return task;
1981
6
    }
1982
4
    return std::nullopt;
1983
10
}
_ZN5doris5cloud24make_deferred_abort_taskINS0_15RecycleRowsetPBEEESt8optionalINS0_24DeferredRecycleAbortTaskEERKT_
Line
Count
Source
1959
4
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
1960
4
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1961
4
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
1962
0
            return std::nullopt;
1963
0
        }
1964
4
    }
1965
1966
4
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1967
4
    DeferredRecycleAbortTask task;
1968
4
    task.tablet_id = rs_meta.tablet_id();
1969
4
    task.start_version = rs_meta.start_version();
1970
4
    task.end_version = rs_meta.end_version();
1971
4
    if (rs_meta.has_load_id()) {
1972
2
        task.type = DeferredRecycleAbortTask::Type::TXN;
1973
2
        task.txn_id = rs_meta.txn_id();
1974
2
        return task;
1975
2
    }
1976
2
    if (rs_meta.has_job_id()) {
1977
2
        task.type = DeferredRecycleAbortTask::Type::JOB;
1978
2
        task.rowset_id = rs_meta.rowset_id_v2();
1979
2
        task.job_id = rs_meta.job_id();
1980
2
        return task;
1981
2
    }
1982
0
    return std::nullopt;
1983
2
}
_ZN5doris5cloud24make_deferred_abort_taskINS_17RowsetMetaCloudPBEEESt8optionalINS0_24DeferredRecycleAbortTaskEERKT_
Line
Count
Source
1959
10
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
1960
10
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1961
10
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
1962
10
            return std::nullopt;
1963
10
        }
1964
10
    }
1965
1966
10
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1967
10
    DeferredRecycleAbortTask task;
1968
10
    task.tablet_id = rs_meta.tablet_id();
1969
10
    task.start_version = rs_meta.start_version();
1970
10
    task.end_version = rs_meta.end_version();
1971
10
    if (rs_meta.has_load_id()) {
1972
2
        task.type = DeferredRecycleAbortTask::Type::TXN;
1973
2
        task.txn_id = rs_meta.txn_id();
1974
2
        return task;
1975
2
    }
1976
8
    if (rs_meta.has_job_id()) {
1977
4
        task.type = DeferredRecycleAbortTask::Type::JOB;
1978
4
        task.rowset_id = rs_meta.rowset_id_v2();
1979
4
        task.job_id = rs_meta.job_id();
1980
4
        return task;
1981
4
    }
1982
4
    return std::nullopt;
1983
8
}
1984
1985
template <typename T>
1986
35
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
1987
35
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1988
35
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
1989
35
}
_ZN5doris5cloud28need_mark_rowset_as_recycledINS0_15RecycleRowsetPBEEEbRKT_
Line
Count
Source
1986
10
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
1987
10
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1988
10
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
1989
10
}
_ZN5doris5cloud28need_mark_rowset_as_recycledINS_17RowsetMetaCloudPBEEEbRKT_
Line
Count
Source
1986
25
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
1987
25
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1988
25
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
1989
25
}
1990
1991
template <typename T>
1992
int batch_mark_rowsets_as_recycled(TxnKv* txn_kv, const std::string& instance_id,
1993
11
                                   const std::vector<std::string>& keys) {
1994
11
    std::unique_ptr<Transaction> txn;
1995
11
    TxnErrorCode err = txn_kv->create_txn(&txn);
1996
11
    if (err != TxnErrorCode::TXN_OK) {
1997
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1998
0
        return -1;
1999
0
    }
2000
11
    std::vector<std::optional<std::string>> values;
2001
11
    err = txn->batch_get(&values, keys);
2002
11
    if (err != TxnErrorCode::TXN_OK) {
2003
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2004
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
2005
0
        return -1;
2006
0
    }
2007
11
    size_t total_keys = keys.size();
2008
24
    for (size_t i = 0; i < total_keys; i++) {
2009
13
        if (!values[i].has_value()) {
2010
            // has already been removed by commit_rowset
2011
0
            continue;
2012
0
        }
2013
13
        auto key = keys[i];
2014
13
        auto val = values[i].value();
2015
13
        T rowset_meta_pb;
2016
13
        if (!rowset_meta_pb.ParseFromString(val)) {
2017
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2018
0
                         << " key=" << hex(key);
2019
0
            return -1;
2020
0
        }
2021
13
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
2022
0
            continue;
2023
0
        }
2024
13
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2025
13
        val.clear();
2026
13
        rowset_meta_pb.SerializeToString(&val);
2027
13
        txn->put(key, val);
2028
13
    }
2029
11
    err = txn->commit();
2030
11
    if (err != TxnErrorCode::TXN_OK) {
2031
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2032
0
        return -1;
2033
0
    }
2034
2035
11
    return 0;
2036
11
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
1993
4
                                   const std::vector<std::string>& keys) {
1994
4
    std::unique_ptr<Transaction> txn;
1995
4
    TxnErrorCode err = txn_kv->create_txn(&txn);
1996
4
    if (err != TxnErrorCode::TXN_OK) {
1997
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1998
0
        return -1;
1999
0
    }
2000
4
    std::vector<std::optional<std::string>> values;
2001
4
    err = txn->batch_get(&values, keys);
2002
4
    if (err != TxnErrorCode::TXN_OK) {
2003
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2004
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
2005
0
        return -1;
2006
0
    }
2007
4
    size_t total_keys = keys.size();
2008
8
    for (size_t i = 0; i < total_keys; i++) {
2009
4
        if (!values[i].has_value()) {
2010
            // has already been removed by commit_rowset
2011
0
            continue;
2012
0
        }
2013
4
        auto key = keys[i];
2014
4
        auto val = values[i].value();
2015
4
        T rowset_meta_pb;
2016
4
        if (!rowset_meta_pb.ParseFromString(val)) {
2017
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2018
0
                         << " key=" << hex(key);
2019
0
            return -1;
2020
0
        }
2021
4
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
2022
0
            continue;
2023
0
        }
2024
4
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2025
4
        val.clear();
2026
4
        rowset_meta_pb.SerializeToString(&val);
2027
4
        txn->put(key, val);
2028
4
    }
2029
4
    err = txn->commit();
2030
4
    if (err != TxnErrorCode::TXN_OK) {
2031
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2032
0
        return -1;
2033
0
    }
2034
2035
4
    return 0;
2036
4
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
1993
7
                                   const std::vector<std::string>& keys) {
1994
7
    std::unique_ptr<Transaction> txn;
1995
7
    TxnErrorCode err = txn_kv->create_txn(&txn);
1996
7
    if (err != TxnErrorCode::TXN_OK) {
1997
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1998
0
        return -1;
1999
0
    }
2000
7
    std::vector<std::optional<std::string>> values;
2001
7
    err = txn->batch_get(&values, keys);
2002
7
    if (err != TxnErrorCode::TXN_OK) {
2003
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2004
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
2005
0
        return -1;
2006
0
    }
2007
7
    size_t total_keys = keys.size();
2008
16
    for (size_t i = 0; i < total_keys; i++) {
2009
9
        if (!values[i].has_value()) {
2010
            // has already been removed by commit_rowset
2011
0
            continue;
2012
0
        }
2013
9
        auto key = keys[i];
2014
9
        auto val = values[i].value();
2015
9
        T rowset_meta_pb;
2016
9
        if (!rowset_meta_pb.ParseFromString(val)) {
2017
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2018
0
                         << " key=" << hex(key);
2019
0
            return -1;
2020
0
        }
2021
9
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
2022
0
            continue;
2023
0
        }
2024
9
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2025
9
        val.clear();
2026
9
        rowset_meta_pb.SerializeToString(&val);
2027
9
        txn->put(key, val);
2028
9
    }
2029
7
    err = txn->commit();
2030
7
    if (err != TxnErrorCode::TXN_OK) {
2031
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2032
0
        return -1;
2033
0
    }
2034
2035
7
    return 0;
2036
7
}
2037
2038
template <typename T>
2039
int collect_deferred_abort_tasks(TxnKv* txn_kv, const std::string& instance_id,
2040
                                 const std::vector<std::string>& keys,
2041
                                 std::vector<DeferredRecycleAbortTask>* abort_tasks,
2042
5
                                 bool skip_base_version) {
2043
5
    constexpr size_t kAbortCheckBatchSize = 256;
2044
10
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2045
5
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2046
5
        std::unique_ptr<Transaction> txn;
2047
5
        TxnErrorCode err = txn_kv->create_txn(&txn);
2048
5
        if (err != TxnErrorCode::TXN_OK) {
2049
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2050
0
            return -1;
2051
0
        }
2052
10
        for (size_t idx = offset; idx < limit; ++idx) {
2053
5
            const std::string& key = keys[idx];
2054
5
            std::string val;
2055
5
            err = txn->get(key, &val);
2056
5
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2057
                // has already been removed
2058
0
                continue;
2059
0
            }
2060
5
            if (err != TxnErrorCode::TXN_OK) {
2061
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2062
0
                             << " key=" << hex(key);
2063
0
                return -1;
2064
0
            }
2065
5
            T rowset_meta_pb;
2066
5
            if (!rowset_meta_pb.ParseFromString(val)) {
2067
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2068
0
                             << " key=" << hex(key);
2069
0
                return -1;
2070
0
            }
2071
5
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2072
0
                continue;
2073
0
            }
2074
5
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2075
5
                abort_task.has_value()) {
2076
5
                abort_tasks->emplace_back(std::move(*abort_task));
2077
5
            }
2078
5
        }
2079
5
    }
2080
5
    return 0;
2081
5
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24DeferredRecycleAbortTaskESaISI_EEb
Line
Count
Source
2042
2
                                 bool skip_base_version) {
2043
2
    constexpr size_t kAbortCheckBatchSize = 256;
2044
4
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2045
2
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2046
2
        std::unique_ptr<Transaction> txn;
2047
2
        TxnErrorCode err = txn_kv->create_txn(&txn);
2048
2
        if (err != TxnErrorCode::TXN_OK) {
2049
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2050
0
            return -1;
2051
0
        }
2052
4
        for (size_t idx = offset; idx < limit; ++idx) {
2053
2
            const std::string& key = keys[idx];
2054
2
            std::string val;
2055
2
            err = txn->get(key, &val);
2056
2
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2057
                // has already been removed
2058
0
                continue;
2059
0
            }
2060
2
            if (err != TxnErrorCode::TXN_OK) {
2061
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2062
0
                             << " key=" << hex(key);
2063
0
                return -1;
2064
0
            }
2065
2
            T rowset_meta_pb;
2066
2
            if (!rowset_meta_pb.ParseFromString(val)) {
2067
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2068
0
                             << " key=" << hex(key);
2069
0
                return -1;
2070
0
            }
2071
2
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2072
0
                continue;
2073
0
            }
2074
2
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2075
2
                abort_task.has_value()) {
2076
2
                abort_tasks->emplace_back(std::move(*abort_task));
2077
2
            }
2078
2
        }
2079
2
    }
2080
2
    return 0;
2081
2
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24DeferredRecycleAbortTaskESaISI_EEb
Line
Count
Source
2042
3
                                 bool skip_base_version) {
2043
3
    constexpr size_t kAbortCheckBatchSize = 256;
2044
6
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2045
3
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2046
3
        std::unique_ptr<Transaction> txn;
2047
3
        TxnErrorCode err = txn_kv->create_txn(&txn);
2048
3
        if (err != TxnErrorCode::TXN_OK) {
2049
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2050
0
            return -1;
2051
0
        }
2052
6
        for (size_t idx = offset; idx < limit; ++idx) {
2053
3
            const std::string& key = keys[idx];
2054
3
            std::string val;
2055
3
            err = txn->get(key, &val);
2056
3
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2057
                // has already been removed
2058
0
                continue;
2059
0
            }
2060
3
            if (err != TxnErrorCode::TXN_OK) {
2061
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2062
0
                             << " key=" << hex(key);
2063
0
                return -1;
2064
0
            }
2065
3
            T rowset_meta_pb;
2066
3
            if (!rowset_meta_pb.ParseFromString(val)) {
2067
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2068
0
                             << " key=" << hex(key);
2069
0
                return -1;
2070
0
            }
2071
3
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2072
0
                continue;
2073
0
            }
2074
3
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2075
3
                abort_task.has_value()) {
2076
3
                abort_tasks->emplace_back(std::move(*abort_task));
2077
3
            }
2078
3
        }
2079
3
    }
2080
3
    return 0;
2081
3
}
2082
2083
template <typename T>
2084
int InstanceRecycler::batch_abort_txn_or_job_for_recycle(const std::vector<std::string>& keys,
2085
5
                                                         bool skip_base_version) {
2086
5
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2087
5
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2088
5
                                        skip_base_version) != 0) {
2089
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2090
0
        return -1;
2091
0
    }
2092
5
    for (const auto& abort_task : abort_tasks) {
2093
5
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2094
5
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2095
5
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2096
5
        int abort_ret = 0;
2097
5
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2098
2
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2099
3
        } else {
2100
3
            RowsetMetaCloudPB rowset_meta;
2101
3
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2102
3
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2103
3
            rowset_meta.set_job_id(abort_task.job_id);
2104
3
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2105
3
        }
2106
5
        if (abort_ret != 0) {
2107
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2108
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2109
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2110
0
            return abort_ret;
2111
0
        }
2112
5
    }
2113
5
    return 0;
2114
5
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEb
Line
Count
Source
2085
2
                                                         bool skip_base_version) {
2086
2
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2087
2
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2088
2
                                        skip_base_version) != 0) {
2089
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2090
0
        return -1;
2091
0
    }
2092
2
    for (const auto& abort_task : abort_tasks) {
2093
2
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2094
2
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2095
2
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2096
2
        int abort_ret = 0;
2097
2
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2098
1
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2099
1
        } else {
2100
1
            RowsetMetaCloudPB rowset_meta;
2101
1
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2102
1
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2103
1
            rowset_meta.set_job_id(abort_task.job_id);
2104
1
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2105
1
        }
2106
2
        if (abort_ret != 0) {
2107
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2108
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2109
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2110
0
            return abort_ret;
2111
0
        }
2112
2
    }
2113
2
    return 0;
2114
2
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEb
Line
Count
Source
2085
3
                                                         bool skip_base_version) {
2086
3
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2087
3
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2088
3
                                        skip_base_version) != 0) {
2089
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2090
0
        return -1;
2091
0
    }
2092
3
    for (const auto& abort_task : abort_tasks) {
2093
3
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2094
3
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2095
3
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2096
3
        int abort_ret = 0;
2097
3
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2098
1
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2099
2
        } else {
2100
2
            RowsetMetaCloudPB rowset_meta;
2101
2
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2102
2
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2103
2
            rowset_meta.set_job_id(abort_task.job_id);
2104
2
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2105
2
        }
2106
3
        if (abort_ret != 0) {
2107
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2108
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2109
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2110
0
            return abort_ret;
2111
0
        }
2112
3
    }
2113
3
    return 0;
2114
3
}
2115
2116
int collect_prepare_delete_tasks(TxnKv* txn_kv, const std::string& instance_id,
2117
                                 const std::vector<std::string>& keys,
2118
0
                                 std::vector<DeferredRecyclePrepareDeleteTask>* delete_tasks) {
2119
0
    constexpr size_t kPrepareCheckBatchSize = 256;
2120
0
    for (size_t offset = 0; offset < keys.size(); offset += kPrepareCheckBatchSize) {
2121
0
        size_t limit = std::min(keys.size(), offset + kPrepareCheckBatchSize);
2122
0
        std::unique_ptr<Transaction> txn;
2123
0
        TxnErrorCode err = txn_kv->create_txn(&txn);
2124
0
        if (err != TxnErrorCode::TXN_OK) {
2125
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2126
0
            return -1;
2127
0
        }
2128
0
        for (size_t idx = offset; idx < limit; ++idx) {
2129
0
            const std::string& key = keys[idx];
2130
0
            std::string val;
2131
0
            err = txn->get(key, &val);
2132
0
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2133
                // has already been removed
2134
0
                continue;
2135
0
            }
2136
0
            if (err != TxnErrorCode::TXN_OK) {
2137
0
                LOG(WARNING) << "failed to get recycle rowset, instance_id=" << instance_id
2138
0
                             << " key=" << hex(key);
2139
0
                return -1;
2140
0
            }
2141
0
            RecycleRowsetPB rowset;
2142
0
            if (!rowset.ParseFromString(val)) {
2143
0
                LOG(WARNING) << "failed to parse recycle rowset, instance_id=" << instance_id
2144
0
                             << " key=" << hex(key);
2145
0
                return -1;
2146
0
            }
2147
0
            if (rowset.type() != RecycleRowsetPB::PREPARE) {
2148
0
                continue;
2149
0
            }
2150
0
            const auto& rs_meta = rowset.rowset_meta();
2151
0
            delete_tasks->push_back(
2152
0
                    {key, rs_meta.resource_id(), rs_meta.rowset_id_v2(), rs_meta.tablet_id()});
2153
0
        }
2154
0
    }
2155
0
    return 0;
2156
0
}
2157
2158
1
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
2159
1
    const std::string task_name = "recycle_ref_rowsets";
2160
1
    *has_unrecycled_rowsets = false;
2161
2162
1
    std::string data_rowset_ref_count_key_start =
2163
1
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
2164
1
    std::string data_rowset_ref_count_key_end =
2165
1
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
2166
2167
1
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
2168
2169
1
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2170
1
    register_recycle_task(task_name, start_time);
2171
2172
1
    DORIS_CLOUD_DEFER {
2173
1
        unregister_recycle_task(task_name);
2174
1
        int64_t cost =
2175
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2176
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2177
1
                .tag("instance_id", instance_id_);
2178
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Line
Count
Source
2172
1
    DORIS_CLOUD_DEFER {
2173
1
        unregister_recycle_task(task_name);
2174
1
        int64_t cost =
2175
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2176
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2177
1
                .tag("instance_id", instance_id_);
2178
1
    };
2179
2180
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
2181
1
    std::set<int64_t> tablets_with_refs;
2182
1
    int64_t num_scanned = 0;
2183
2184
1
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
2185
0
        ++num_scanned;
2186
0
        int64_t tablet_id;
2187
0
        std::string rowset_id;
2188
0
        std::string_view key(k);
2189
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
2190
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
2191
0
            return 0; // Continue scanning
2192
0
        }
2193
2194
0
        tablets_with_refs.insert(tablet_id);
2195
0
        return 0;
2196
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
2197
2198
1
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
2199
1
                         std::move(scan_func)) != 0) {
2200
0
        LOG_WARNING("failed to scan data rowset ref count keys");
2201
0
        return -1;
2202
0
    }
2203
2204
1
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
2205
1
             tablets_with_refs.size(), num_scanned)
2206
1
            .tag("instance_id", instance_id_);
2207
2208
    // Phase 2: Recycle each tablet
2209
1
    int64_t num_recycled_tablets = 0;
2210
1
    for (int64_t tablet_id : tablets_with_refs) {
2211
0
        if (stopped()) {
2212
0
            LOG_INFO("recycler stopped, skip remaining tablets")
2213
0
                    .tag("instance_id", instance_id_)
2214
0
                    .tag("tablets_processed", num_recycled_tablets)
2215
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
2216
0
            break;
2217
0
        }
2218
2219
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
2220
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
2221
0
            LOG_WARNING("failed to recycle tablet")
2222
0
                    .tag("instance_id", instance_id_)
2223
0
                    .tag("tablet_id", tablet_id);
2224
0
            return -1;
2225
0
        }
2226
0
        ++num_recycled_tablets;
2227
0
    }
2228
2229
1
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
2230
1
            .tag("instance_id", instance_id_)
2231
1
            .tag("total_tablets", tablets_with_refs.size());
2232
2233
    // Phase 3: Scan again to check if any ref count keys still exist
2234
1
    std::unique_ptr<Transaction> txn;
2235
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2236
1
    if (err != TxnErrorCode::TXN_OK) {
2237
0
        LOG_WARNING("failed to create txn for final check")
2238
0
                .tag("instance_id", instance_id_)
2239
0
                .tag("err", err);
2240
0
        return -1;
2241
0
    }
2242
2243
1
    std::unique_ptr<RangeGetIterator> iter;
2244
1
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2245
1
    if (err != TxnErrorCode::TXN_OK) {
2246
0
        LOG_WARNING("failed to create range iterator for final check")
2247
0
                .tag("instance_id", instance_id_)
2248
0
                .tag("err", err);
2249
0
        return -1;
2250
0
    }
2251
2252
1
    *has_unrecycled_rowsets = iter->has_next();
2253
1
    if (*has_unrecycled_rowsets) {
2254
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2255
0
                .tag("instance_id", instance_id_);
2256
0
    }
2257
2258
1
    return 0;
2259
1
}
2260
2261
int InstanceRecycler::recycle_table_stream_offset_prefix(std::string prefix,
2262
6
                                                         RecyclerMetricsContext* metrics_context) {
2263
6
    std::string end = prefix;
2264
6
    end.push_back('\xff');
2265
6
    std::vector<std::string_view> keys;
2266
8
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2267
8
        keys.push_back(key);
2268
8
        return 0;
2269
8
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_1clESt17basic_string_viewIcS5_ESC_
Line
Count
Source
2266
2
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2267
2
        keys.push_back(key);
2268
2
        return 0;
2269
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_1clESt17basic_string_viewIcS5_ESC_
Line
Count
Source
2266
6
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2267
6
        keys.push_back(key);
2268
6
        return 0;
2269
6
    };
2270
6
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2271
4
        if (keys.empty()) {
2272
0
            return 0;
2273
0
        }
2274
4
        DORIS_CLOUD_DEFER {
2275
4
            keys.clear();
2276
4
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlvE_clEv
Line
Count
Source
2274
2
        DORIS_CLOUD_DEFER {
2275
2
            keys.clear();
2276
2
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlvE_clEv
Line
Count
Source
2274
2
        DORIS_CLOUD_DEFER {
2275
2
            keys.clear();
2276
2
        };
2277
4
        const size_t num_keys = keys.size();
2278
4
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2279
0
            LOG_WARNING("failed to delete table stream offsets")
2280
0
                    .tag("instance_id", instance_id_)
2281
0
                    .tag("num_keys", num_keys);
2282
0
            return -1;
2283
0
        }
2284
4
        metrics_context->total_recycled_num += num_keys;
2285
4
        metrics_context->report();
2286
4
        return 0;
2287
4
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2270
2
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2271
2
        if (keys.empty()) {
2272
0
            return 0;
2273
0
        }
2274
2
        DORIS_CLOUD_DEFER {
2275
2
            keys.clear();
2276
2
        };
2277
2
        const size_t num_keys = keys.size();
2278
2
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2279
0
            LOG_WARNING("failed to delete table stream offsets")
2280
0
                    .tag("instance_id", instance_id_)
2281
0
                    .tag("num_keys", num_keys);
2282
0
            return -1;
2283
0
        }
2284
2
        metrics_context->total_recycled_num += num_keys;
2285
2
        metrics_context->report();
2286
2
        return 0;
2287
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2270
2
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2271
2
        if (keys.empty()) {
2272
0
            return 0;
2273
0
        }
2274
2
        DORIS_CLOUD_DEFER {
2275
2
            keys.clear();
2276
2
        };
2277
2
        const size_t num_keys = keys.size();
2278
2
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2279
0
            LOG_WARNING("failed to delete table stream offsets")
2280
0
                    .tag("instance_id", instance_id_)
2281
0
                    .tag("num_keys", num_keys);
2282
0
            return -1;
2283
0
        }
2284
2
        metrics_context->total_recycled_num += num_keys;
2285
2
        metrics_context->report();
2286
2
        return 0;
2287
2
    };
2288
6
    return scan_and_recycle(std::move(prefix), end, std::move(collect_key), std::move(remove_keys));
2289
6
}
2290
2291
int InstanceRecycler::finalize_recycle_stream(int64_t stream_id,
2292
                                              const RecycleIndexPB& recycle_index,
2293
3
                                              std::string_view recycle_key) {
2294
3
    std::unique_ptr<Transaction> txn;
2295
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2296
3
    if (err != TxnErrorCode::TXN_OK) {
2297
0
        LOG_WARNING("failed to create transaction for final table stream cleanup")
2298
0
                .tag("instance_id", instance_id_)
2299
0
                .tag("stream_id", stream_id)
2300
0
                .tag("err", err);
2301
0
        return -1;
2302
0
    }
2303
2304
3
    std::string current_recycle_value;
2305
3
    err = txn->get(recycle_key, &current_recycle_value);
2306
3
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2307
0
        return 0;
2308
0
    }
2309
3
    if (err != TxnErrorCode::TXN_OK) {
2310
0
        LOG_WARNING("failed to read table stream recycle index")
2311
0
                .tag("instance_id", instance_id_)
2312
0
                .tag("stream_id", stream_id)
2313
0
                .tag("err", err);
2314
0
        return -1;
2315
0
    }
2316
3
    RecycleIndexPB current_recycle_index;
2317
3
    if (!current_recycle_index.ParseFromString(current_recycle_value) ||
2318
3
        current_recycle_index.state() != RecycleIndexPB::RECYCLING ||
2319
3
        current_recycle_index.object_type() != IndexObjectTypePB::TABLE_STREAM ||
2320
3
        current_recycle_index.db_id() != recycle_index.db_id() ||
2321
3
        current_recycle_index.table_id() != recycle_index.table_id() ||
2322
3
        current_recycle_index.stream_db_id() != recycle_index.stream_db_id()) {
2323
0
        LOG_WARNING("table stream recycle index changed during recycling")
2324
0
                .tag("instance_id", instance_id_)
2325
0
                .tag("stream_id", stream_id);
2326
0
        return -1;
2327
0
    }
2328
2329
3
    txn->remove(recycle_key);
2330
3
    err = txn->commit();
2331
3
    if (err != TxnErrorCode::TXN_OK) {
2332
0
        LOG_WARNING("failed to commit final table stream cleanup")
2333
0
                .tag("instance_id", instance_id_)
2334
0
                .tag("stream_id", stream_id)
2335
0
                .tag("err", err);
2336
0
        return -1;
2337
0
    }
2338
3
    return 0;
2339
3
}
2340
2341
int InstanceRecycler::recycle_stream(int64_t stream_id, const RecycleIndexPB& recycle_index,
2342
3
                                     std::string_view recycle_key) {
2343
3
    if (!recycle_index.has_db_id() || !recycle_index.has_stream_db_id()) {
2344
0
        LOG_WARNING("table stream recycle index is missing binding")
2345
0
                .tag("instance_id", instance_id_)
2346
0
                .tag("stream_id", stream_id);
2347
0
        return -1;
2348
0
    }
2349
2350
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stream");
2351
3
    DORIS_CLOUD_DEFER {
2352
3
        metrics_context.finish_report();
2353
3
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_streamElRKNS0_14RecycleIndexPBESt17basic_string_viewIcSt11char_traitsIcEEENK3$_0clEv
Line
Count
Source
2351
2
    DORIS_CLOUD_DEFER {
2352
2
        metrics_context.finish_report();
2353
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_streamElRKNS0_14RecycleIndexPBESt17basic_string_viewIcSt11char_traitsIcEEENK3$_0clEv
Line
Count
Source
2351
1
    DORIS_CLOUD_DEFER {
2352
1
        metrics_context.finish_report();
2353
1
    };
2354
3
    const std::string latest_offset_prefix = table_stream_offset_key_prefix(
2355
3
            instance_id_, recycle_index.db_id(), recycle_index.table_id(),
2356
3
            recycle_index.stream_db_id(), stream_id);
2357
3
    if (recycle_table_stream_offset_prefix(latest_offset_prefix, &metrics_context) != 0) {
2358
0
        return -1;
2359
0
    }
2360
3
    const std::string versioned_offset_prefix = versioned::table_stream_offset_key_prefix(
2361
3
            instance_id_, recycle_index.db_id(), recycle_index.table_id(),
2362
3
            recycle_index.stream_db_id(), stream_id);
2363
3
    if (recycle_table_stream_offset_prefix(versioned_offset_prefix, &metrics_context) != 0 ||
2364
3
        stopped()) {
2365
0
        return -1;
2366
0
    }
2367
3
    return finalize_recycle_stream(stream_id, recycle_index, recycle_key);
2368
3
}
2369
2370
int InstanceRecycler::recycle_partition_table_stream_offsets(
2371
        int64_t db_id, int64_t table_id, int64_t partition_id,
2372
10
        const google::protobuf::RepeatedPtrField<TableStreamIdentityPB>& table_streams) {
2373
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stream_partition_offsets");
2374
10
    DORIS_CLOUD_DEFER {
2375
10
        metrics_context.finish_report();
2376
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler38recycle_partition_table_stream_offsetsElllRKN6google8protobuf16RepeatedPtrFieldINS0_21TableStreamIdentityPBEEEENK3$_0clEv
Line
Count
Source
2374
1
    DORIS_CLOUD_DEFER {
2375
1
        metrics_context.finish_report();
2376
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler38recycle_partition_table_stream_offsetsElllRKN6google8protobuf16RepeatedPtrFieldINS0_21TableStreamIdentityPBEEEENK3$_0clEv
Line
Count
Source
2374
9
    DORIS_CLOUD_DEFER {
2375
9
        metrics_context.finish_report();
2376
9
    };
2377
10
    const size_t batch_size = std::max(1, config::recycler_max_tasks_per_batch);
2378
12
    for (size_t begin_index = 0; begin_index < table_streams.size(); begin_index += batch_size) {
2379
2
        const size_t end_index =
2380
2
                std::min(static_cast<size_t>(table_streams.size()), begin_index + batch_size);
2381
2
        std::unique_ptr<Transaction> txn;
2382
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2383
2
        if (err != TxnErrorCode::TXN_OK) {
2384
0
            LOG_WARNING("failed to create transaction for partition stream offset cleanup")
2385
0
                    .tag("instance_id", instance_id_)
2386
0
                    .tag("partition_id", partition_id)
2387
0
                    .tag("err", err);
2388
0
            return -1;
2389
0
        }
2390
4
        for (size_t i = begin_index; i < end_index; ++i) {
2391
2
            const TableStreamIdentityPB& stream = table_streams.Get(i);
2392
2
            if (stream.base_db_id() != db_id || stream.base_table_id() != table_id ||
2393
2
                stream.stream_db_id() <= 0 || stream.stream_id() <= 0) {
2394
0
                LOG_WARNING("invalid table stream binding in recycle partition")
2395
0
                        .tag("instance_id", instance_id_)
2396
0
                        .tag("partition_id", partition_id)
2397
0
                        .tag("stream_id", stream.stream_id());
2398
0
                return -1;
2399
0
            }
2400
2
            txn->remove(table_stream_offset_key({instance_id_, stream.base_db_id(),
2401
2
                                                 stream.base_table_id(), stream.stream_db_id(),
2402
2
                                                 stream.stream_id(), partition_id}));
2403
2
            versioned_remove_all(
2404
2
                    txn.get(), versioned::table_stream_offset_key(
2405
2
                                       {instance_id_, stream.base_db_id(), stream.base_table_id(),
2406
2
                                        stream.stream_db_id(), stream.stream_id(), partition_id}));
2407
2
        }
2408
2
        err = txn->commit();
2409
2
        if (err != TxnErrorCode::TXN_OK) {
2410
0
            LOG_WARNING("failed to commit partition stream offset cleanup")
2411
0
                    .tag("instance_id", instance_id_)
2412
0
                    .tag("partition_id", partition_id)
2413
0
                    .tag("err", err);
2414
0
            return -1;
2415
0
        }
2416
2
        metrics_context.total_recycled_num += end_index - begin_index;
2417
2
        metrics_context.report();
2418
2
    }
2419
10
    return 0;
2420
10
}
2421
2422
19
int InstanceRecycler::recycle_indexes() {
2423
19
    const std::string task_name = "recycle_indexes";
2424
19
    int64_t num_scanned = 0;
2425
19
    int64_t num_expired = 0;
2426
19
    int64_t num_recycled = 0;
2427
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2428
2429
19
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2430
19
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2431
19
    std::string index_key0;
2432
19
    std::string index_key1;
2433
19
    recycle_index_key(index_key_info0, &index_key0);
2434
19
    recycle_index_key(index_key_info1, &index_key1);
2435
2436
19
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2437
2438
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2439
19
    register_recycle_task(task_name, start_time);
2440
2441
19
    DORIS_CLOUD_DEFER {
2442
19
        unregister_recycle_task(task_name);
2443
19
        int64_t cost =
2444
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2445
19
        metrics_context.finish_report();
2446
19
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2447
19
                .tag("instance_id", instance_id_)
2448
19
                .tag("num_scanned", num_scanned)
2449
19
                .tag("num_expired", num_expired)
2450
19
                .tag("num_recycled", num_recycled);
2451
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2441
3
    DORIS_CLOUD_DEFER {
2442
3
        unregister_recycle_task(task_name);
2443
3
        int64_t cost =
2444
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2445
3
        metrics_context.finish_report();
2446
3
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2447
3
                .tag("instance_id", instance_id_)
2448
3
                .tag("num_scanned", num_scanned)
2449
3
                .tag("num_expired", num_expired)
2450
3
                .tag("num_recycled", num_recycled);
2451
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2441
16
    DORIS_CLOUD_DEFER {
2442
16
        unregister_recycle_task(task_name);
2443
16
        int64_t cost =
2444
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2445
16
        metrics_context.finish_report();
2446
16
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2447
16
                .tag("instance_id", instance_id_)
2448
16
                .tag("num_scanned", num_scanned)
2449
16
                .tag("num_expired", num_expired)
2450
16
                .tag("num_recycled", num_recycled);
2451
16
    };
2452
2453
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2454
2455
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2456
19
    std::vector<std::string_view> index_keys;
2457
19
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2458
13
        ++num_scanned;
2459
13
        RecycleIndexPB index_pb;
2460
13
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2461
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2462
0
            return -1;
2463
0
        }
2464
13
        int64_t current_time = ::time(nullptr);
2465
13
        if (current_time <
2466
13
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2467
0
            return 0;
2468
0
        }
2469
13
        ++num_expired;
2470
        // decode index_id
2471
13
        auto k1 = k;
2472
13
        k1.remove_prefix(1);
2473
13
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2474
13
        decode_key(&k1, &out);
2475
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2476
13
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2477
13
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2478
13
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2479
13
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2480
        // Change state to RECYCLING
2481
13
        std::unique_ptr<Transaction> txn;
2482
13
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2483
13
        if (err != TxnErrorCode::TXN_OK) {
2484
0
            LOG_WARNING("failed to create txn").tag("err", err);
2485
0
            return -1;
2486
0
        }
2487
13
        std::string val;
2488
13
        err = txn->get(k, &val);
2489
13
        if (err ==
2490
13
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2491
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2492
0
            return 0;
2493
0
        }
2494
13
        if (err != TxnErrorCode::TXN_OK) {
2495
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2496
0
            return -1;
2497
0
        }
2498
13
        index_pb.Clear();
2499
13
        if (!index_pb.ParseFromString(val)) {
2500
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2501
0
            return -1;
2502
0
        }
2503
13
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2504
12
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2505
12
            txn->put(k, index_pb.SerializeAsString());
2506
12
            err = txn->commit();
2507
12
            if (err != TxnErrorCode::TXN_OK) {
2508
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2509
0
                return -1;
2510
0
            }
2511
12
        }
2512
13
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
2513
3
            if (recycle_stream(index_id, index_pb, k) != 0) {
2514
0
                LOG_WARNING("failed to recycle table stream")
2515
0
                        .tag("instance_id", instance_id_)
2516
0
                        .tag("stream_id", index_id);
2517
0
                return -1;
2518
0
            }
2519
3
            metrics_context.total_recycled_num = ++num_recycled;
2520
3
            metrics_context.report();
2521
3
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2522
3
            return 0;
2523
3
        }
2524
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2525
1
            LOG_WARNING("failed to recycle tablets under index")
2526
1
                    .tag("table_id", index_pb.table_id())
2527
1
                    .tag("instance_id", instance_id_)
2528
1
                    .tag("index_id", index_id);
2529
1
            return -1;
2530
1
        }
2531
2532
9
        if (index_pb.has_db_id()) {
2533
            // Recycle the versioned keys
2534
3
            std::unique_ptr<Transaction> txn;
2535
3
            err = txn_kv_->create_txn(&txn);
2536
3
            if (err != TxnErrorCode::TXN_OK) {
2537
0
                LOG_WARNING("failed to create txn").tag("err", err);
2538
0
                return -1;
2539
0
            }
2540
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2541
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2542
3
            std::string index_inverted_key = versioned::index_inverted_key(
2543
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2544
3
            versioned_remove_all(txn.get(), meta_key);
2545
3
            txn->remove(index_key);
2546
3
            txn->remove(index_inverted_key);
2547
3
            err = txn->commit();
2548
3
            if (err != TxnErrorCode::TXN_OK) {
2549
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2550
0
                return -1;
2551
0
            }
2552
3
        }
2553
2554
9
        metrics_context.total_recycled_num = ++num_recycled;
2555
9
        metrics_context.report();
2556
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2557
9
        index_keys.push_back(k);
2558
9
        return 0;
2559
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2457
4
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2458
4
        ++num_scanned;
2459
4
        RecycleIndexPB index_pb;
2460
4
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2461
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2462
0
            return -1;
2463
0
        }
2464
4
        int64_t current_time = ::time(nullptr);
2465
4
        if (current_time <
2466
4
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2467
0
            return 0;
2468
0
        }
2469
4
        ++num_expired;
2470
        // decode index_id
2471
4
        auto k1 = k;
2472
4
        k1.remove_prefix(1);
2473
4
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2474
4
        decode_key(&k1, &out);
2475
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2476
4
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2477
4
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2478
4
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2479
4
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2480
        // Change state to RECYCLING
2481
4
        std::unique_ptr<Transaction> txn;
2482
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2483
4
        if (err != TxnErrorCode::TXN_OK) {
2484
0
            LOG_WARNING("failed to create txn").tag("err", err);
2485
0
            return -1;
2486
0
        }
2487
4
        std::string val;
2488
4
        err = txn->get(k, &val);
2489
4
        if (err ==
2490
4
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2491
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2492
0
            return 0;
2493
0
        }
2494
4
        if (err != TxnErrorCode::TXN_OK) {
2495
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2496
0
            return -1;
2497
0
        }
2498
4
        index_pb.Clear();
2499
4
        if (!index_pb.ParseFromString(val)) {
2500
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2501
0
            return -1;
2502
0
        }
2503
4
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2504
3
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2505
3
            txn->put(k, index_pb.SerializeAsString());
2506
3
            err = txn->commit();
2507
3
            if (err != TxnErrorCode::TXN_OK) {
2508
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2509
0
                return -1;
2510
0
            }
2511
3
        }
2512
4
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
2513
2
            if (recycle_stream(index_id, index_pb, k) != 0) {
2514
0
                LOG_WARNING("failed to recycle table stream")
2515
0
                        .tag("instance_id", instance_id_)
2516
0
                        .tag("stream_id", index_id);
2517
0
                return -1;
2518
0
            }
2519
2
            metrics_context.total_recycled_num = ++num_recycled;
2520
2
            metrics_context.report();
2521
2
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2522
2
            return 0;
2523
2
        }
2524
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2525
1
            LOG_WARNING("failed to recycle tablets under index")
2526
1
                    .tag("table_id", index_pb.table_id())
2527
1
                    .tag("instance_id", instance_id_)
2528
1
                    .tag("index_id", index_id);
2529
1
            return -1;
2530
1
        }
2531
2532
1
        if (index_pb.has_db_id()) {
2533
            // Recycle the versioned keys
2534
1
            std::unique_ptr<Transaction> txn;
2535
1
            err = txn_kv_->create_txn(&txn);
2536
1
            if (err != TxnErrorCode::TXN_OK) {
2537
0
                LOG_WARNING("failed to create txn").tag("err", err);
2538
0
                return -1;
2539
0
            }
2540
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2541
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2542
1
            std::string index_inverted_key = versioned::index_inverted_key(
2543
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2544
1
            versioned_remove_all(txn.get(), meta_key);
2545
1
            txn->remove(index_key);
2546
1
            txn->remove(index_inverted_key);
2547
1
            err = txn->commit();
2548
1
            if (err != TxnErrorCode::TXN_OK) {
2549
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2550
0
                return -1;
2551
0
            }
2552
1
        }
2553
2554
1
        metrics_context.total_recycled_num = ++num_recycled;
2555
1
        metrics_context.report();
2556
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2557
1
        index_keys.push_back(k);
2558
1
        return 0;
2559
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2457
9
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2458
9
        ++num_scanned;
2459
9
        RecycleIndexPB index_pb;
2460
9
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2461
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2462
0
            return -1;
2463
0
        }
2464
9
        int64_t current_time = ::time(nullptr);
2465
9
        if (current_time <
2466
9
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2467
0
            return 0;
2468
0
        }
2469
9
        ++num_expired;
2470
        // decode index_id
2471
9
        auto k1 = k;
2472
9
        k1.remove_prefix(1);
2473
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2474
9
        decode_key(&k1, &out);
2475
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2476
9
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2477
9
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2478
9
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2479
9
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2480
        // Change state to RECYCLING
2481
9
        std::unique_ptr<Transaction> txn;
2482
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2483
9
        if (err != TxnErrorCode::TXN_OK) {
2484
0
            LOG_WARNING("failed to create txn").tag("err", err);
2485
0
            return -1;
2486
0
        }
2487
9
        std::string val;
2488
9
        err = txn->get(k, &val);
2489
9
        if (err ==
2490
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2491
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2492
0
            return 0;
2493
0
        }
2494
9
        if (err != TxnErrorCode::TXN_OK) {
2495
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2496
0
            return -1;
2497
0
        }
2498
9
        index_pb.Clear();
2499
9
        if (!index_pb.ParseFromString(val)) {
2500
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2501
0
            return -1;
2502
0
        }
2503
9
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2504
9
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2505
9
            txn->put(k, index_pb.SerializeAsString());
2506
9
            err = txn->commit();
2507
9
            if (err != TxnErrorCode::TXN_OK) {
2508
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2509
0
                return -1;
2510
0
            }
2511
9
        }
2512
9
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
2513
1
            if (recycle_stream(index_id, index_pb, k) != 0) {
2514
0
                LOG_WARNING("failed to recycle table stream")
2515
0
                        .tag("instance_id", instance_id_)
2516
0
                        .tag("stream_id", index_id);
2517
0
                return -1;
2518
0
            }
2519
1
            metrics_context.total_recycled_num = ++num_recycled;
2520
1
            metrics_context.report();
2521
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2522
1
            return 0;
2523
1
        }
2524
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2525
0
            LOG_WARNING("failed to recycle tablets under index")
2526
0
                    .tag("table_id", index_pb.table_id())
2527
0
                    .tag("instance_id", instance_id_)
2528
0
                    .tag("index_id", index_id);
2529
0
            return -1;
2530
0
        }
2531
2532
8
        if (index_pb.has_db_id()) {
2533
            // Recycle the versioned keys
2534
2
            std::unique_ptr<Transaction> txn;
2535
2
            err = txn_kv_->create_txn(&txn);
2536
2
            if (err != TxnErrorCode::TXN_OK) {
2537
0
                LOG_WARNING("failed to create txn").tag("err", err);
2538
0
                return -1;
2539
0
            }
2540
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2541
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2542
2
            std::string index_inverted_key = versioned::index_inverted_key(
2543
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2544
2
            versioned_remove_all(txn.get(), meta_key);
2545
2
            txn->remove(index_key);
2546
2
            txn->remove(index_inverted_key);
2547
2
            err = txn->commit();
2548
2
            if (err != TxnErrorCode::TXN_OK) {
2549
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2550
0
                return -1;
2551
0
            }
2552
2
        }
2553
2554
8
        metrics_context.total_recycled_num = ++num_recycled;
2555
8
        metrics_context.report();
2556
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2557
8
        index_keys.push_back(k);
2558
8
        return 0;
2559
8
    };
2560
2561
19
    auto loop_done = [&index_keys, this]() -> int {
2562
8
        if (index_keys.empty()) return 0;
2563
5
        DORIS_CLOUD_DEFER {
2564
5
            index_keys.clear();
2565
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2563
1
        DORIS_CLOUD_DEFER {
2564
1
            index_keys.clear();
2565
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2563
4
        DORIS_CLOUD_DEFER {
2564
4
            index_keys.clear();
2565
4
        };
2566
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2567
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2568
0
            return -1;
2569
0
        }
2570
5
        return 0;
2571
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2561
3
    auto loop_done = [&index_keys, this]() -> int {
2562
3
        if (index_keys.empty()) return 0;
2563
1
        DORIS_CLOUD_DEFER {
2564
1
            index_keys.clear();
2565
1
        };
2566
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2567
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2568
0
            return -1;
2569
0
        }
2570
1
        return 0;
2571
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2561
5
    auto loop_done = [&index_keys, this]() -> int {
2562
5
        if (index_keys.empty()) return 0;
2563
4
        DORIS_CLOUD_DEFER {
2564
4
            index_keys.clear();
2565
4
        };
2566
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2567
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2568
0
            return -1;
2569
0
        }
2570
4
        return 0;
2571
4
    };
2572
2573
19
    if (config::enable_recycler_stats_metrics) {
2574
0
        scan_and_statistics_indexes();
2575
0
    }
2576
    // recycle_func and loop_done for scan and recycle
2577
19
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
2578
19
}
2579
2580
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
2581
8.25k
                             int64_t tablet_id) {
2582
8.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
2583
2584
8.25k
    std::unique_ptr<Transaction> txn;
2585
8.25k
    TxnErrorCode err = txn_kv->create_txn(&txn);
2586
8.25k
    if (err != TxnErrorCode::TXN_OK) {
2587
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
2588
0
                     << " tablet_id=" << tablet_id << " err=" << err;
2589
0
        return false;
2590
0
    }
2591
2592
8.25k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
2593
8.25k
    std::string tablet_idx_val;
2594
8.25k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
2595
8.25k
    if (TxnErrorCode::TXN_OK != err) {
2596
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
2597
0
                     << " tablet_id=" << tablet_id << " err=" << err
2598
0
                     << " key=" << hex(tablet_idx_key);
2599
0
        return false;
2600
0
    }
2601
2602
8.25k
    TabletIndexPB tablet_idx_pb;
2603
8.25k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
2604
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
2605
0
                     << " tablet_id=" << tablet_id;
2606
0
        return false;
2607
0
    }
2608
2609
8.25k
    if (!tablet_idx_pb.has_db_id()) {
2610
        // In the previous version, the db_id was not set in the index_pb.
2611
        // If updating to the version which enable txn lazy commit, the db_id will be set.
2612
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
2613
0
                  << " instance_id=" << instance_id
2614
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
2615
0
        return true;
2616
0
    }
2617
2618
8.25k
    std::string ver_val;
2619
8.25k
    std::string ver_key =
2620
8.25k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
2621
8.25k
                                   tablet_idx_pb.partition_id()});
2622
8.25k
    err = txn->get(ver_key, &ver_val);
2623
2624
8.25k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
2625
214
        LOG(INFO) << ""
2626
214
                     "partition version not found, instance_id="
2627
214
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
2628
214
                  << " table_id=" << tablet_idx_pb.table_id()
2629
214
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
2630
214
                  << " key=" << hex(ver_key);
2631
214
        return true;
2632
214
    }
2633
2634
8.03k
    if (TxnErrorCode::TXN_OK != err) {
2635
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
2636
0
                     << " db_id=" << tablet_idx_pb.db_id()
2637
0
                     << " table_id=" << tablet_idx_pb.table_id()
2638
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2639
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
2640
0
        return false;
2641
0
    }
2642
2643
8.03k
    VersionPB version_pb;
2644
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
2645
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
2646
0
                     << " db_id=" << tablet_idx_pb.db_id()
2647
0
                     << " table_id=" << tablet_idx_pb.table_id()
2648
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2649
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
2650
0
        return false;
2651
0
    }
2652
2653
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
2654
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
2655
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
2656
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
2657
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
2658
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
2659
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
2660
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
2661
4.00k
                     << " key=" << hex(ver_key);
2662
4.00k
        return false;
2663
4.00k
    }
2664
4.03k
    return true;
2665
8.03k
}
2666
2667
17
int InstanceRecycler::recycle_partitions() {
2668
17
    const std::string task_name = "recycle_partitions";
2669
17
    int64_t num_scanned = 0;
2670
17
    int64_t num_expired = 0;
2671
17
    int64_t num_recycled = 0;
2672
17
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2673
2674
17
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
2675
17
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
2676
17
    std::string part_key0;
2677
17
    std::string part_key1;
2678
17
    recycle_partition_key(part_key_info0, &part_key0);
2679
17
    recycle_partition_key(part_key_info1, &part_key1);
2680
2681
17
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
2682
2683
17
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2684
17
    register_recycle_task(task_name, start_time);
2685
2686
17
    DORIS_CLOUD_DEFER {
2687
17
        unregister_recycle_task(task_name);
2688
17
        int64_t cost =
2689
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2690
17
        metrics_context.finish_report();
2691
17
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2692
17
                .tag("instance_id", instance_id_)
2693
17
                .tag("num_scanned", num_scanned)
2694
17
                .tag("num_expired", num_expired)
2695
17
                .tag("num_recycled", num_recycled);
2696
17
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2686
2
    DORIS_CLOUD_DEFER {
2687
2
        unregister_recycle_task(task_name);
2688
2
        int64_t cost =
2689
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2690
2
        metrics_context.finish_report();
2691
2
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2692
2
                .tag("instance_id", instance_id_)
2693
2
                .tag("num_scanned", num_scanned)
2694
2
                .tag("num_expired", num_expired)
2695
2
                .tag("num_recycled", num_recycled);
2696
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2686
15
    DORIS_CLOUD_DEFER {
2687
15
        unregister_recycle_task(task_name);
2688
15
        int64_t cost =
2689
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2690
15
        metrics_context.finish_report();
2691
15
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2692
15
                .tag("instance_id", instance_id_)
2693
15
                .tag("num_scanned", num_scanned)
2694
15
                .tag("num_expired", num_expired)
2695
15
                .tag("num_recycled", num_recycled);
2696
15
    };
2697
2698
17
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2699
2700
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
2701
17
    std::vector<std::string_view> partition_keys;
2702
17
    std::vector<std::string> partition_version_keys;
2703
17
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2704
11
        ++num_scanned;
2705
11
        RecyclePartitionPB part_pb;
2706
11
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2707
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2708
0
            return -1;
2709
0
        }
2710
11
        int64_t current_time = ::time(nullptr);
2711
11
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2712
11
                                                            &earlest_ts)) { // not expired
2713
0
            return 0;
2714
0
        }
2715
11
        ++num_expired;
2716
        // decode partition_id
2717
11
        auto k1 = k;
2718
11
        k1.remove_prefix(1);
2719
11
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2720
11
        decode_key(&k1, &out);
2721
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2722
11
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2723
11
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2724
11
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2725
11
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2726
        // Change state to RECYCLING
2727
11
        std::unique_ptr<Transaction> txn;
2728
11
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2729
11
        if (err != TxnErrorCode::TXN_OK) {
2730
0
            LOG_WARNING("failed to create txn").tag("err", err);
2731
0
            return -1;
2732
0
        }
2733
11
        std::string val;
2734
11
        err = txn->get(k, &val);
2735
11
        if (err ==
2736
11
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2737
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2738
0
            return 0;
2739
0
        }
2740
11
        if (err != TxnErrorCode::TXN_OK) {
2741
0
            LOG_WARNING("failed to get kv");
2742
0
            return -1;
2743
0
        }
2744
11
        part_pb.Clear();
2745
11
        if (!part_pb.ParseFromString(val)) {
2746
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2747
0
            return -1;
2748
0
        }
2749
        // Partitions with PREPARED state MUST have no data
2750
11
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2751
10
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2752
10
            txn->put(k, part_pb.SerializeAsString());
2753
10
            err = txn->commit();
2754
10
            if (err != TxnErrorCode::TXN_OK) {
2755
0
                LOG_WARNING("failed to commit txn: {}", err);
2756
0
                return -1;
2757
0
            }
2758
10
        }
2759
2760
11
        int ret = 0;
2761
35
        for (int64_t index_id : part_pb.index_id()) {
2762
35
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2763
1
                LOG_WARNING("failed to recycle tablets under partition")
2764
1
                        .tag("table_id", part_pb.table_id())
2765
1
                        .tag("instance_id", instance_id_)
2766
1
                        .tag("index_id", index_id)
2767
1
                        .tag("partition_id", partition_id);
2768
1
                ret = -1;
2769
1
            }
2770
35
        }
2771
11
        if (ret == 0 && part_pb.has_db_id() &&
2772
11
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
2773
10
                                                   partition_id, part_pb.table_streams()) != 0) {
2774
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
2775
0
                    .tag("instance_id", instance_id_)
2776
0
                    .tag("table_id", part_pb.table_id())
2777
0
                    .tag("partition_id", partition_id);
2778
0
            ret = -1;
2779
0
        }
2780
11
        if (ret == 0 && part_pb.has_db_id()) {
2781
            // Recycle the versioned keys
2782
10
            std::unique_ptr<Transaction> txn;
2783
10
            err = txn_kv_->create_txn(&txn);
2784
10
            if (err != TxnErrorCode::TXN_OK) {
2785
0
                LOG_WARNING("failed to create txn").tag("err", err);
2786
0
                return -1;
2787
0
            }
2788
10
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2789
10
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2790
10
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2791
10
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2792
10
            std::string partition_version_key =
2793
10
                    versioned::partition_version_key({instance_id_, partition_id});
2794
10
            versioned_remove_all(txn.get(), meta_key);
2795
10
            txn->remove(index_key);
2796
10
            txn->remove(inverted_index_key);
2797
10
            versioned_remove_all(txn.get(), partition_version_key);
2798
10
            err = txn->commit();
2799
10
            if (err != TxnErrorCode::TXN_OK) {
2800
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2801
0
                return -1;
2802
0
            }
2803
10
        }
2804
2805
11
        if (ret == 0) {
2806
10
            ++num_recycled;
2807
10
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2808
10
            partition_keys.push_back(k);
2809
10
            if (part_pb.db_id() > 0) {
2810
10
                partition_version_keys.push_back(partition_version_key(
2811
10
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2812
10
            }
2813
10
            metrics_context.total_recycled_num = num_recycled;
2814
10
            metrics_context.report();
2815
10
        }
2816
11
        return ret;
2817
11
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2703
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2704
2
        ++num_scanned;
2705
2
        RecyclePartitionPB part_pb;
2706
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2707
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2708
0
            return -1;
2709
0
        }
2710
2
        int64_t current_time = ::time(nullptr);
2711
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2712
2
                                                            &earlest_ts)) { // not expired
2713
0
            return 0;
2714
0
        }
2715
2
        ++num_expired;
2716
        // decode partition_id
2717
2
        auto k1 = k;
2718
2
        k1.remove_prefix(1);
2719
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2720
2
        decode_key(&k1, &out);
2721
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2722
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2723
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2724
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2725
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2726
        // Change state to RECYCLING
2727
2
        std::unique_ptr<Transaction> txn;
2728
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2729
2
        if (err != TxnErrorCode::TXN_OK) {
2730
0
            LOG_WARNING("failed to create txn").tag("err", err);
2731
0
            return -1;
2732
0
        }
2733
2
        std::string val;
2734
2
        err = txn->get(k, &val);
2735
2
        if (err ==
2736
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2737
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2738
0
            return 0;
2739
0
        }
2740
2
        if (err != TxnErrorCode::TXN_OK) {
2741
0
            LOG_WARNING("failed to get kv");
2742
0
            return -1;
2743
0
        }
2744
2
        part_pb.Clear();
2745
2
        if (!part_pb.ParseFromString(val)) {
2746
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2747
0
            return -1;
2748
0
        }
2749
        // Partitions with PREPARED state MUST have no data
2750
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2751
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2752
1
            txn->put(k, part_pb.SerializeAsString());
2753
1
            err = txn->commit();
2754
1
            if (err != TxnErrorCode::TXN_OK) {
2755
0
                LOG_WARNING("failed to commit txn: {}", err);
2756
0
                return -1;
2757
0
            }
2758
1
        }
2759
2760
2
        int ret = 0;
2761
2
        for (int64_t index_id : part_pb.index_id()) {
2762
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2763
1
                LOG_WARNING("failed to recycle tablets under partition")
2764
1
                        .tag("table_id", part_pb.table_id())
2765
1
                        .tag("instance_id", instance_id_)
2766
1
                        .tag("index_id", index_id)
2767
1
                        .tag("partition_id", partition_id);
2768
1
                ret = -1;
2769
1
            }
2770
2
        }
2771
2
        if (ret == 0 && part_pb.has_db_id() &&
2772
2
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
2773
1
                                                   partition_id, part_pb.table_streams()) != 0) {
2774
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
2775
0
                    .tag("instance_id", instance_id_)
2776
0
                    .tag("table_id", part_pb.table_id())
2777
0
                    .tag("partition_id", partition_id);
2778
0
            ret = -1;
2779
0
        }
2780
2
        if (ret == 0 && part_pb.has_db_id()) {
2781
            // Recycle the versioned keys
2782
1
            std::unique_ptr<Transaction> txn;
2783
1
            err = txn_kv_->create_txn(&txn);
2784
1
            if (err != TxnErrorCode::TXN_OK) {
2785
0
                LOG_WARNING("failed to create txn").tag("err", err);
2786
0
                return -1;
2787
0
            }
2788
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2789
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2790
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2791
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2792
1
            std::string partition_version_key =
2793
1
                    versioned::partition_version_key({instance_id_, partition_id});
2794
1
            versioned_remove_all(txn.get(), meta_key);
2795
1
            txn->remove(index_key);
2796
1
            txn->remove(inverted_index_key);
2797
1
            versioned_remove_all(txn.get(), partition_version_key);
2798
1
            err = txn->commit();
2799
1
            if (err != TxnErrorCode::TXN_OK) {
2800
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2801
0
                return -1;
2802
0
            }
2803
1
        }
2804
2805
2
        if (ret == 0) {
2806
1
            ++num_recycled;
2807
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2808
1
            partition_keys.push_back(k);
2809
1
            if (part_pb.db_id() > 0) {
2810
1
                partition_version_keys.push_back(partition_version_key(
2811
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2812
1
            }
2813
1
            metrics_context.total_recycled_num = num_recycled;
2814
1
            metrics_context.report();
2815
1
        }
2816
2
        return ret;
2817
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2703
9
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2704
9
        ++num_scanned;
2705
9
        RecyclePartitionPB part_pb;
2706
9
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2707
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2708
0
            return -1;
2709
0
        }
2710
9
        int64_t current_time = ::time(nullptr);
2711
9
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2712
9
                                                            &earlest_ts)) { // not expired
2713
0
            return 0;
2714
0
        }
2715
9
        ++num_expired;
2716
        // decode partition_id
2717
9
        auto k1 = k;
2718
9
        k1.remove_prefix(1);
2719
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2720
9
        decode_key(&k1, &out);
2721
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2722
9
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2723
9
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2724
9
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2725
9
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2726
        // Change state to RECYCLING
2727
9
        std::unique_ptr<Transaction> txn;
2728
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2729
9
        if (err != TxnErrorCode::TXN_OK) {
2730
0
            LOG_WARNING("failed to create txn").tag("err", err);
2731
0
            return -1;
2732
0
        }
2733
9
        std::string val;
2734
9
        err = txn->get(k, &val);
2735
9
        if (err ==
2736
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2737
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2738
0
            return 0;
2739
0
        }
2740
9
        if (err != TxnErrorCode::TXN_OK) {
2741
0
            LOG_WARNING("failed to get kv");
2742
0
            return -1;
2743
0
        }
2744
9
        part_pb.Clear();
2745
9
        if (!part_pb.ParseFromString(val)) {
2746
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2747
0
            return -1;
2748
0
        }
2749
        // Partitions with PREPARED state MUST have no data
2750
9
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2751
9
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2752
9
            txn->put(k, part_pb.SerializeAsString());
2753
9
            err = txn->commit();
2754
9
            if (err != TxnErrorCode::TXN_OK) {
2755
0
                LOG_WARNING("failed to commit txn: {}", err);
2756
0
                return -1;
2757
0
            }
2758
9
        }
2759
2760
9
        int ret = 0;
2761
33
        for (int64_t index_id : part_pb.index_id()) {
2762
33
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2763
0
                LOG_WARNING("failed to recycle tablets under partition")
2764
0
                        .tag("table_id", part_pb.table_id())
2765
0
                        .tag("instance_id", instance_id_)
2766
0
                        .tag("index_id", index_id)
2767
0
                        .tag("partition_id", partition_id);
2768
0
                ret = -1;
2769
0
            }
2770
33
        }
2771
9
        if (ret == 0 && part_pb.has_db_id() &&
2772
9
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
2773
9
                                                   partition_id, part_pb.table_streams()) != 0) {
2774
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
2775
0
                    .tag("instance_id", instance_id_)
2776
0
                    .tag("table_id", part_pb.table_id())
2777
0
                    .tag("partition_id", partition_id);
2778
0
            ret = -1;
2779
0
        }
2780
9
        if (ret == 0 && part_pb.has_db_id()) {
2781
            // Recycle the versioned keys
2782
9
            std::unique_ptr<Transaction> txn;
2783
9
            err = txn_kv_->create_txn(&txn);
2784
9
            if (err != TxnErrorCode::TXN_OK) {
2785
0
                LOG_WARNING("failed to create txn").tag("err", err);
2786
0
                return -1;
2787
0
            }
2788
9
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2789
9
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2790
9
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2791
9
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2792
9
            std::string partition_version_key =
2793
9
                    versioned::partition_version_key({instance_id_, partition_id});
2794
9
            versioned_remove_all(txn.get(), meta_key);
2795
9
            txn->remove(index_key);
2796
9
            txn->remove(inverted_index_key);
2797
9
            versioned_remove_all(txn.get(), partition_version_key);
2798
9
            err = txn->commit();
2799
9
            if (err != TxnErrorCode::TXN_OK) {
2800
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2801
0
                return -1;
2802
0
            }
2803
9
        }
2804
2805
9
        if (ret == 0) {
2806
9
            ++num_recycled;
2807
9
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2808
9
            partition_keys.push_back(k);
2809
9
            if (part_pb.db_id() > 0) {
2810
9
                partition_version_keys.push_back(partition_version_key(
2811
9
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2812
9
            }
2813
9
            metrics_context.total_recycled_num = num_recycled;
2814
9
            metrics_context.report();
2815
9
        }
2816
9
        return ret;
2817
9
    };
2818
2819
17
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2820
7
        if (partition_keys.empty()) return 0;
2821
6
        DORIS_CLOUD_DEFER {
2822
6
            partition_keys.clear();
2823
6
            partition_version_keys.clear();
2824
6
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2821
1
        DORIS_CLOUD_DEFER {
2822
1
            partition_keys.clear();
2823
1
            partition_version_keys.clear();
2824
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2821
5
        DORIS_CLOUD_DEFER {
2822
5
            partition_keys.clear();
2823
5
            partition_version_keys.clear();
2824
5
        };
2825
6
        std::unique_ptr<Transaction> txn;
2826
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2827
6
        if (err != TxnErrorCode::TXN_OK) {
2828
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2829
0
            return -1;
2830
0
        }
2831
10
        for (auto& k : partition_keys) {
2832
10
            txn->remove(k);
2833
10
        }
2834
10
        for (auto& k : partition_version_keys) {
2835
10
            txn->remove(k);
2836
10
        }
2837
6
        err = txn->commit();
2838
6
        if (err != TxnErrorCode::TXN_OK) {
2839
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2840
0
                         << " err=" << err;
2841
0
            return -1;
2842
0
        }
2843
6
        return 0;
2844
6
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2819
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2820
2
        if (partition_keys.empty()) return 0;
2821
1
        DORIS_CLOUD_DEFER {
2822
1
            partition_keys.clear();
2823
1
            partition_version_keys.clear();
2824
1
        };
2825
1
        std::unique_ptr<Transaction> txn;
2826
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2827
1
        if (err != TxnErrorCode::TXN_OK) {
2828
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2829
0
            return -1;
2830
0
        }
2831
1
        for (auto& k : partition_keys) {
2832
1
            txn->remove(k);
2833
1
        }
2834
1
        for (auto& k : partition_version_keys) {
2835
1
            txn->remove(k);
2836
1
        }
2837
1
        err = txn->commit();
2838
1
        if (err != TxnErrorCode::TXN_OK) {
2839
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2840
0
                         << " err=" << err;
2841
0
            return -1;
2842
0
        }
2843
1
        return 0;
2844
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2819
5
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2820
5
        if (partition_keys.empty()) return 0;
2821
5
        DORIS_CLOUD_DEFER {
2822
5
            partition_keys.clear();
2823
5
            partition_version_keys.clear();
2824
5
        };
2825
5
        std::unique_ptr<Transaction> txn;
2826
5
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2827
5
        if (err != TxnErrorCode::TXN_OK) {
2828
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2829
0
            return -1;
2830
0
        }
2831
9
        for (auto& k : partition_keys) {
2832
9
            txn->remove(k);
2833
9
        }
2834
9
        for (auto& k : partition_version_keys) {
2835
9
            txn->remove(k);
2836
9
        }
2837
5
        err = txn->commit();
2838
5
        if (err != TxnErrorCode::TXN_OK) {
2839
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2840
0
                         << " err=" << err;
2841
0
            return -1;
2842
0
        }
2843
5
        return 0;
2844
5
    };
2845
2846
17
    if (config::enable_recycler_stats_metrics) {
2847
0
        scan_and_statistics_partitions();
2848
0
    }
2849
    // recycle_func and loop_done for scan and recycle
2850
17
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
2851
17
}
2852
2853
14
int InstanceRecycler::recycle_versions() {
2854
14
    if (should_recycle_versioned_keys()) {
2855
2
        return recycle_orphan_partitions();
2856
2
    }
2857
2858
12
    int64_t num_scanned = 0;
2859
12
    int64_t num_recycled = 0;
2860
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
2861
2862
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
2863
2864
12
    auto start_time = steady_clock::now();
2865
2866
12
    DORIS_CLOUD_DEFER {
2867
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2868
12
        metrics_context.finish_report();
2869
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
2870
12
                .tag("instance_id", instance_id_)
2871
12
                .tag("num_scanned", num_scanned)
2872
12
                .tag("num_recycled", num_recycled);
2873
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
2866
12
    DORIS_CLOUD_DEFER {
2867
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2868
12
        metrics_context.finish_report();
2869
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
2870
12
                .tag("instance_id", instance_id_)
2871
12
                .tag("num_scanned", num_scanned)
2872
12
                .tag("num_recycled", num_recycled);
2873
12
    };
2874
2875
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
2876
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
2877
12
    int64_t last_scanned_table_id = 0;
2878
12
    bool is_recycled = false; // Is last scanned kv recycled
2879
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
2880
12
                         &metrics_context, this](std::string_view k, std::string_view) {
2881
2
        ++num_scanned;
2882
2
        auto k1 = k;
2883
2
        k1.remove_prefix(1);
2884
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
2885
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2886
2
        decode_key(&k1, &out);
2887
2
        DCHECK_EQ(out.size(), 6) << k;
2888
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
2889
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
2890
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
2891
0
            return 0;
2892
0
        }
2893
2
        last_scanned_table_id = table_id;
2894
2
        is_recycled = false;
2895
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
2896
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
2897
2
        std::unique_ptr<Transaction> txn;
2898
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2899
2
        if (err != TxnErrorCode::TXN_OK) {
2900
0
            return -1;
2901
0
        }
2902
2
        std::unique_ptr<RangeGetIterator> iter;
2903
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
2904
2
        if (err != TxnErrorCode::TXN_OK) {
2905
0
            return -1;
2906
0
        }
2907
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
2908
1
            return 0;
2909
1
        }
2910
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2911
        // 1. Remove all partition version kvs of this table
2912
1
        auto partition_version_key_begin =
2913
1
                partition_version_key({instance_id_, db_id, table_id, 0});
2914
1
        auto partition_version_key_end =
2915
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
2916
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
2917
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
2918
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
2919
1
                     << " table_id=" << table_id;
2920
        // 2. Remove the table version kv of this table
2921
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
2922
1
        txn->remove(tbl_version_key);
2923
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
2924
        // 3. Remove mow delete bitmap update lock and tablet job lock
2925
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2926
1
        txn->remove(lock_key);
2927
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2928
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2929
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2930
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
2931
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2932
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2933
1
                     << " table_id=" << table_id;
2934
1
        err = txn->commit();
2935
1
        if (err != TxnErrorCode::TXN_OK) {
2936
0
            return -1;
2937
0
        }
2938
1
        metrics_context.total_recycled_num = ++num_recycled;
2939
1
        metrics_context.report();
2940
1
        is_recycled = true;
2941
1
        return 0;
2942
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2880
2
                         &metrics_context, this](std::string_view k, std::string_view) {
2881
2
        ++num_scanned;
2882
2
        auto k1 = k;
2883
2
        k1.remove_prefix(1);
2884
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
2885
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2886
2
        decode_key(&k1, &out);
2887
2
        DCHECK_EQ(out.size(), 6) << k;
2888
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
2889
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
2890
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
2891
0
            return 0;
2892
0
        }
2893
2
        last_scanned_table_id = table_id;
2894
2
        is_recycled = false;
2895
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
2896
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
2897
2
        std::unique_ptr<Transaction> txn;
2898
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2899
2
        if (err != TxnErrorCode::TXN_OK) {
2900
0
            return -1;
2901
0
        }
2902
2
        std::unique_ptr<RangeGetIterator> iter;
2903
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
2904
2
        if (err != TxnErrorCode::TXN_OK) {
2905
0
            return -1;
2906
0
        }
2907
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
2908
1
            return 0;
2909
1
        }
2910
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2911
        // 1. Remove all partition version kvs of this table
2912
1
        auto partition_version_key_begin =
2913
1
                partition_version_key({instance_id_, db_id, table_id, 0});
2914
1
        auto partition_version_key_end =
2915
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
2916
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
2917
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
2918
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
2919
1
                     << " table_id=" << table_id;
2920
        // 2. Remove the table version kv of this table
2921
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
2922
1
        txn->remove(tbl_version_key);
2923
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
2924
        // 3. Remove mow delete bitmap update lock and tablet job lock
2925
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2926
1
        txn->remove(lock_key);
2927
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2928
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2929
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2930
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
2931
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2932
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2933
1
                     << " table_id=" << table_id;
2934
1
        err = txn->commit();
2935
1
        if (err != TxnErrorCode::TXN_OK) {
2936
0
            return -1;
2937
0
        }
2938
1
        metrics_context.total_recycled_num = ++num_recycled;
2939
1
        metrics_context.report();
2940
1
        is_recycled = true;
2941
1
        return 0;
2942
1
    };
2943
2944
12
    if (config::enable_recycler_stats_metrics) {
2945
0
        scan_and_statistics_versions();
2946
0
    }
2947
    // recycle_func and loop_done for scan and recycle
2948
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
2949
14
}
2950
2951
3
int InstanceRecycler::recycle_orphan_partitions() {
2952
3
    int64_t num_scanned = 0;
2953
3
    int64_t num_recycled = 0;
2954
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
2955
2956
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
2957
3
            .tag("instance_id", instance_id_);
2958
2959
3
    auto start_time = steady_clock::now();
2960
2961
3
    DORIS_CLOUD_DEFER {
2962
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2963
3
        metrics_context.finish_report();
2964
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
2965
3
                .tag("instance_id", instance_id_)
2966
3
                .tag("num_scanned", num_scanned)
2967
3
                .tag("num_recycled", num_recycled);
2968
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
2961
3
    DORIS_CLOUD_DEFER {
2962
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2963
3
        metrics_context.finish_report();
2964
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
2965
3
                .tag("instance_id", instance_id_)
2966
3
                .tag("num_scanned", num_scanned)
2967
3
                .tag("num_recycled", num_recycled);
2968
3
    };
2969
2970
3
    bool is_empty_table = false;        // whether the table has no indexes
2971
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
2972
3
    int64_t current_table_id = 0;       // current scanning table id
2973
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
2974
3
                         &current_table_id, &is_table_kvs_recycled,
2975
3
                         this](std::string_view k, std::string_view) {
2976
2
        ++num_scanned;
2977
2978
2
        std::string_view k1(k);
2979
2
        int64_t db_id, table_id, partition_id;
2980
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
2981
2
                                                            &partition_id)) {
2982
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
2983
0
            return -1;
2984
2
        } else if (table_id != current_table_id) {
2985
2
            current_table_id = table_id;
2986
2
            is_table_kvs_recycled = false;
2987
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
2988
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
2989
2
            if (err != TxnErrorCode::TXN_OK) {
2990
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
2991
0
                             << " table_id=" << table_id << " err=" << err;
2992
0
                return -1;
2993
0
            }
2994
2
        }
2995
2996
2
        if (!is_empty_table) {
2997
            // table is not empty, skip recycle
2998
1
            return 0;
2999
1
        }
3000
3001
1
        std::unique_ptr<Transaction> txn;
3002
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3003
1
        if (err != TxnErrorCode::TXN_OK) {
3004
0
            return -1;
3005
0
        }
3006
3007
        // 1. Remove all partition related kvs
3008
1
        std::string partition_meta_key =
3009
1
                versioned::meta_partition_key({instance_id_, partition_id});
3010
1
        std::string partition_index_key =
3011
1
                versioned::partition_index_key({instance_id_, partition_id});
3012
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3013
1
                {instance_id_, db_id, table_id, partition_id});
3014
1
        std::string partition_version_key =
3015
1
                versioned::partition_version_key({instance_id_, partition_id});
3016
1
        txn->remove(partition_index_key);
3017
1
        txn->remove(partition_inverted_key);
3018
1
        versioned_remove_all(txn.get(), partition_meta_key);
3019
1
        versioned_remove_all(txn.get(), partition_version_key);
3020
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3021
1
                     << " table_id=" << table_id << " db_id=" << db_id
3022
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3023
1
                     << " partition_version_key=" << hex(partition_version_key);
3024
3025
1
        if (!is_table_kvs_recycled) {
3026
1
            is_table_kvs_recycled = true;
3027
3028
            // 2. Remove the table version kv of this table
3029
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3030
1
            versioned_remove_all(txn.get(), table_version_key);
3031
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3032
            // 3. Remove mow delete bitmap update lock and tablet job lock
3033
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3034
1
            txn->remove(lock_key);
3035
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3036
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3037
1
            std::string tablet_job_key_end =
3038
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3039
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3040
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3041
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3042
1
                         << " table_id=" << table_id;
3043
1
        }
3044
3045
1
        err = txn->commit();
3046
1
        if (err != TxnErrorCode::TXN_OK) {
3047
0
            return -1;
3048
0
        }
3049
1
        metrics_context.total_recycled_num = ++num_recycled;
3050
1
        metrics_context.report();
3051
1
        return 0;
3052
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
2975
2
                         this](std::string_view k, std::string_view) {
2976
2
        ++num_scanned;
2977
2978
2
        std::string_view k1(k);
2979
2
        int64_t db_id, table_id, partition_id;
2980
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
2981
2
                                                            &partition_id)) {
2982
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
2983
0
            return -1;
2984
2
        } else if (table_id != current_table_id) {
2985
2
            current_table_id = table_id;
2986
2
            is_table_kvs_recycled = false;
2987
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
2988
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
2989
2
            if (err != TxnErrorCode::TXN_OK) {
2990
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
2991
0
                             << " table_id=" << table_id << " err=" << err;
2992
0
                return -1;
2993
0
            }
2994
2
        }
2995
2996
2
        if (!is_empty_table) {
2997
            // table is not empty, skip recycle
2998
1
            return 0;
2999
1
        }
3000
3001
1
        std::unique_ptr<Transaction> txn;
3002
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3003
1
        if (err != TxnErrorCode::TXN_OK) {
3004
0
            return -1;
3005
0
        }
3006
3007
        // 1. Remove all partition related kvs
3008
1
        std::string partition_meta_key =
3009
1
                versioned::meta_partition_key({instance_id_, partition_id});
3010
1
        std::string partition_index_key =
3011
1
                versioned::partition_index_key({instance_id_, partition_id});
3012
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3013
1
                {instance_id_, db_id, table_id, partition_id});
3014
1
        std::string partition_version_key =
3015
1
                versioned::partition_version_key({instance_id_, partition_id});
3016
1
        txn->remove(partition_index_key);
3017
1
        txn->remove(partition_inverted_key);
3018
1
        versioned_remove_all(txn.get(), partition_meta_key);
3019
1
        versioned_remove_all(txn.get(), partition_version_key);
3020
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3021
1
                     << " table_id=" << table_id << " db_id=" << db_id
3022
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3023
1
                     << " partition_version_key=" << hex(partition_version_key);
3024
3025
1
        if (!is_table_kvs_recycled) {
3026
1
            is_table_kvs_recycled = true;
3027
3028
            // 2. Remove the table version kv of this table
3029
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3030
1
            versioned_remove_all(txn.get(), table_version_key);
3031
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3032
            // 3. Remove mow delete bitmap update lock and tablet job lock
3033
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3034
1
            txn->remove(lock_key);
3035
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3036
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3037
1
            std::string tablet_job_key_end =
3038
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3039
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3040
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3041
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3042
1
                         << " table_id=" << table_id;
3043
1
        }
3044
3045
1
        err = txn->commit();
3046
1
        if (err != TxnErrorCode::TXN_OK) {
3047
0
            return -1;
3048
0
        }
3049
1
        metrics_context.total_recycled_num = ++num_recycled;
3050
1
        metrics_context.report();
3051
1
        return 0;
3052
1
    };
3053
3054
    // recycle_func and loop_done for scan and recycle
3055
3
    return scan_and_recycle(
3056
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
3057
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
3058
3
            std::move(recycle_func));
3059
3
}
3060
3061
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
3062
                                      RecyclerMetricsContext& metrics_context,
3063
54
                                      int64_t partition_id) {
3064
54
    bool is_multi_version =
3065
54
            instance_info_.has_multi_version_status() &&
3066
54
            instance_info_.multi_version_status() != MultiVersionStatus::MULTI_VERSION_DISABLED;
3067
54
    int64_t num_scanned = 0;
3068
54
    std::atomic_long num_recycled = 0;
3069
3070
54
    std::string tablet_key_begin, tablet_key_end;
3071
54
    std::string stats_key_begin, stats_key_end;
3072
54
    std::string job_key_begin, job_key_end;
3073
3074
54
    std::string tablet_belongs;
3075
54
    if (partition_id > 0) {
3076
        // recycle tablets in a partition belonging to the index
3077
35
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
3078
35
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
3079
35
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
3080
35
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
3081
35
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
3082
35
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
3083
35
        tablet_belongs = "partition";
3084
35
    } else {
3085
        // recycle tablets in the index
3086
19
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
3087
19
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
3088
19
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
3089
19
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
3090
19
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
3091
19
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
3092
19
        tablet_belongs = "index";
3093
19
    }
3094
3095
54
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
3096
54
            .tag("table_id", table_id)
3097
54
            .tag("index_id", index_id)
3098
54
            .tag("partition_id", partition_id);
3099
3100
54
    auto start_time = steady_clock::now();
3101
3102
54
    DORIS_CLOUD_DEFER {
3103
54
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3104
54
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3105
54
                .tag("instance_id", instance_id_)
3106
54
                .tag("table_id", table_id)
3107
54
                .tag("index_id", index_id)
3108
54
                .tag("partition_id", partition_id)
3109
54
                .tag("num_scanned", num_scanned)
3110
54
                .tag("num_recycled", num_recycled);
3111
54
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3102
4
    DORIS_CLOUD_DEFER {
3103
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3104
4
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3105
4
                .tag("instance_id", instance_id_)
3106
4
                .tag("table_id", table_id)
3107
4
                .tag("index_id", index_id)
3108
4
                .tag("partition_id", partition_id)
3109
4
                .tag("num_scanned", num_scanned)
3110
4
                .tag("num_recycled", num_recycled);
3111
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3102
50
    DORIS_CLOUD_DEFER {
3103
50
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3104
50
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3105
50
                .tag("instance_id", instance_id_)
3106
50
                .tag("table_id", table_id)
3107
50
                .tag("index_id", index_id)
3108
50
                .tag("partition_id", partition_id)
3109
50
                .tag("num_scanned", num_scanned)
3110
50
                .tag("num_recycled", num_recycled);
3111
50
    };
3112
3113
    // The tablet key and id which have been recycled.
3114
54
    struct TabletInfo {
3115
54
        std::string_view tablet_meta_key;
3116
54
        int64_t tablet_id;
3117
54
    };
3118
54
    SyncExecutor<TabletInfo> sync_executor(
3119
54
            _thread_pool_group.recycle_tablet_pool,
3120
54
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
3121
54
                        index_id, partition_id),
3122
4.24k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3122
4.00k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3122
241
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
3123
3124
    // Elements in `tablets_info` has the same lifetime as `it` in `scan_and_recycle`
3125
54
    std::vector<std::string> init_rs_keys;
3126
54
    bool has_failure = false;
3127
8.25k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3128
8.25k
        ++num_scanned;
3129
8.25k
        doris::TabletMetaCloudPB tablet_meta_pb;
3130
8.25k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3131
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3132
0
            has_failure = true;
3133
0
            return -1;
3134
0
        }
3135
8.25k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3136
3137
8.25k
        if (config::enable_recycler_check_lazy_txn_finished &&
3138
8.25k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3139
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3140
4.00k
            has_failure = true;
3141
4.00k
            return -1;
3142
4.00k
        }
3143
3144
4.25k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3145
4.25k
        sync_executor.add(
3146
4.25k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3147
4.25k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3148
2
                        LOG_WARNING("failed to recycle tablet")
3149
2
                                .tag("instance_id", instance_id_)
3150
2
                                .tag("tablet_id", tid);
3151
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3152
2
                    }
3153
4.25k
                    ++num_recycled;
3154
4.25k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3155
4.25k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3156
4.25k
                });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3146
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3147
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3148
0
                        LOG_WARNING("failed to recycle tablet")
3149
0
                                .tag("instance_id", instance_id_)
3150
0
                                .tag("tablet_id", tid);
3151
0
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3152
0
                    }
3153
4.00k
                    ++num_recycled;
3154
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3155
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3156
4.00k
                });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3146
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3147
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3148
2
                        LOG_WARNING("failed to recycle tablet")
3149
2
                                .tag("instance_id", instance_id_)
3150
2
                                .tag("tablet_id", tid);
3151
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3152
2
                    }
3153
248
                    ++num_recycled;
3154
248
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3155
248
                    return {.tablet_meta_key = k, .tablet_id = tid};
3156
250
                });
3157
4.25k
        return 0;
3158
4.25k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3127
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3128
8.00k
        ++num_scanned;
3129
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
3130
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3131
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3132
0
            has_failure = true;
3133
0
            return -1;
3134
0
        }
3135
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3136
3137
8.00k
        if (config::enable_recycler_check_lazy_txn_finished &&
3138
8.00k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3139
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3140
4.00k
            has_failure = true;
3141
4.00k
            return -1;
3142
4.00k
        }
3143
3144
4.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3145
4.00k
        sync_executor.add(
3146
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3147
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3148
4.00k
                        LOG_WARNING("failed to recycle tablet")
3149
4.00k
                                .tag("instance_id", instance_id_)
3150
4.00k
                                .tag("tablet_id", tid);
3151
4.00k
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3152
4.00k
                    }
3153
4.00k
                    ++num_recycled;
3154
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3155
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3156
4.00k
                });
3157
4.00k
        return 0;
3158
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3127
251
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3128
251
        ++num_scanned;
3129
251
        doris::TabletMetaCloudPB tablet_meta_pb;
3130
251
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3131
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3132
0
            has_failure = true;
3133
0
            return -1;
3134
0
        }
3135
251
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3136
3137
251
        if (config::enable_recycler_check_lazy_txn_finished &&
3138
251
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3139
1
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3140
1
            has_failure = true;
3141
1
            return -1;
3142
1
        }
3143
3144
250
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3145
250
        sync_executor.add(
3146
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3147
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3148
250
                        LOG_WARNING("failed to recycle tablet")
3149
250
                                .tag("instance_id", instance_id_)
3150
250
                                .tag("tablet_id", tid);
3151
250
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3152
250
                    }
3153
250
                    ++num_recycled;
3154
250
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3155
250
                    return {.tablet_meta_key = k, .tablet_id = tid};
3156
250
                });
3157
250
        return 0;
3158
250
    };
3159
3160
54
    auto loop_done = [&, this]() -> int {
3161
52
        int ret = 0;
3162
52
        bool finished = true;
3163
52
        bool has_empty_key = false;
3164
52
        DORIS_CLOUD_DEFER {
3165
52
            init_rs_keys.clear();
3166
52
            has_failure = false;
3167
52
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3164
4
        DORIS_CLOUD_DEFER {
3165
4
            init_rs_keys.clear();
3166
4
            has_failure = false;
3167
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3164
48
        DORIS_CLOUD_DEFER {
3165
48
            init_rs_keys.clear();
3166
48
            has_failure = false;
3167
48
        };
3168
52
        auto tablets_info = sync_executor.when_all(&finished);
3169
52
        if (!finished) {
3170
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3171
1
            return -1;
3172
1
        }
3173
3174
51
        size_t size_before_erase = tablets_info.size();
3175
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
3175
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
3175
249
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3176
51
        if (tablets_info.empty()) {
3177
2
            return size_before_erase == 0 ? 0 : -1;
3178
49
        } else if (size_before_erase != tablets_info.size()) {
3179
1
            has_empty_key = true;
3180
1
        }
3181
3182
49
        ret = has_empty_key ? -1 : 0;
3183
        // sort the vector using key's order
3184
49.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3185
49.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3186
49.4k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3184
48.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3185
48.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3186
48.4k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3184
958
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3185
958
            return prev.tablet_meta_key < last.tablet_meta_key;
3186
958
        });
3187
49
        std::unique_ptr<Transaction> txn;
3188
49
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3189
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3190
0
            return -1;
3191
0
        }
3192
49
        std::string tablet_key_end;
3193
49
        if (!tablets_info.empty()) {
3194
49
            if (!has_empty_key && !has_failure) {
3195
47
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3196
47
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3197
47
            } else {
3198
8
                for (auto& tablet_info : tablets_info) {
3199
8
                    txn->remove(tablet_info.tablet_meta_key);
3200
8
                }
3201
2
            }
3202
49
        }
3203
49
        if (is_multi_version) {
3204
6
            for (auto& tablet_info : tablets_info) {
3205
                // Remove all versions of tablet compact stats for recycled tablet
3206
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3207
6
                LOG_INFO("remove versioned tablet compact stats key")
3208
6
                        .tag("compact_stats_key", hex(k));
3209
6
                versioned_remove_all(txn.get(), k);
3210
6
            }
3211
6
            for (auto& tablet_info : tablets_info) {
3212
                // Remove all versions of tablet load stats for recycled tablet
3213
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3214
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3215
6
                versioned_remove_all(txn.get(), k);
3216
6
            }
3217
6
            for (auto& tablet_info : tablets_info) {
3218
                // Remove all versions of meta tablet for recycled tablet
3219
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3220
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3221
6
                versioned_remove_all(txn.get(), k);
3222
6
            }
3223
5
        }
3224
4.25k
        for (auto& tablet_info : tablets_info) {
3225
4.25k
            std::string k;
3226
4.25k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3227
4.25k
            txn->remove(k);
3228
4.25k
        }
3229
4.25k
        for (auto& tablet_info : tablets_info) {
3230
4.25k
            std::string k;
3231
4.25k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3232
4.25k
            txn->remove(k);
3233
4.25k
        }
3234
49
        for (auto& k : init_rs_keys) {
3235
0
            txn->remove(k);
3236
0
        }
3237
49
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3238
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3239
0
                         << ", err=" << err;
3240
0
            return -1;
3241
0
        }
3242
49
        return ret;
3243
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
3160
4
    auto loop_done = [&, this]() -> int {
3161
4
        int ret = 0;
3162
4
        bool finished = true;
3163
4
        bool has_empty_key = false;
3164
4
        DORIS_CLOUD_DEFER {
3165
4
            init_rs_keys.clear();
3166
4
            has_failure = false;
3167
4
        };
3168
4
        auto tablets_info = sync_executor.when_all(&finished);
3169
4
        if (!finished) {
3170
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3171
0
            return -1;
3172
0
        }
3173
3174
4
        size_t size_before_erase = tablets_info.size();
3175
4
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3176
4
        if (tablets_info.empty()) {
3177
2
            return size_before_erase == 0 ? 0 : -1;
3178
2
        } else if (size_before_erase != tablets_info.size()) {
3179
0
            has_empty_key = true;
3180
0
        }
3181
3182
2
        ret = has_empty_key ? -1 : 0;
3183
        // sort the vector using key's order
3184
2
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3185
2
            return prev.tablet_meta_key < last.tablet_meta_key;
3186
2
        });
3187
2
        std::unique_ptr<Transaction> txn;
3188
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3189
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3190
0
            return -1;
3191
0
        }
3192
2
        std::string tablet_key_end;
3193
2
        if (!tablets_info.empty()) {
3194
2
            if (!has_empty_key && !has_failure) {
3195
2
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3196
2
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3197
2
            } else {
3198
0
                for (auto& tablet_info : tablets_info) {
3199
0
                    txn->remove(tablet_info.tablet_meta_key);
3200
0
                }
3201
0
            }
3202
2
        }
3203
2
        if (is_multi_version) {
3204
0
            for (auto& tablet_info : tablets_info) {
3205
                // Remove all versions of tablet compact stats for recycled tablet
3206
0
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3207
0
                LOG_INFO("remove versioned tablet compact stats key")
3208
0
                        .tag("compact_stats_key", hex(k));
3209
0
                versioned_remove_all(txn.get(), k);
3210
0
            }
3211
0
            for (auto& tablet_info : tablets_info) {
3212
                // Remove all versions of tablet load stats for recycled tablet
3213
0
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3214
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3215
0
                versioned_remove_all(txn.get(), k);
3216
0
            }
3217
0
            for (auto& tablet_info : tablets_info) {
3218
                // Remove all versions of meta tablet for recycled tablet
3219
0
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3220
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3221
0
                versioned_remove_all(txn.get(), k);
3222
0
            }
3223
0
        }
3224
4.00k
        for (auto& tablet_info : tablets_info) {
3225
4.00k
            std::string k;
3226
4.00k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3227
4.00k
            txn->remove(k);
3228
4.00k
        }
3229
4.00k
        for (auto& tablet_info : tablets_info) {
3230
4.00k
            std::string k;
3231
4.00k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3232
4.00k
            txn->remove(k);
3233
4.00k
        }
3234
2
        for (auto& k : init_rs_keys) {
3235
0
            txn->remove(k);
3236
0
        }
3237
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3238
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3239
0
                         << ", err=" << err;
3240
0
            return -1;
3241
0
        }
3242
2
        return ret;
3243
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
3160
48
    auto loop_done = [&, this]() -> int {
3161
48
        int ret = 0;
3162
48
        bool finished = true;
3163
48
        bool has_empty_key = false;
3164
48
        DORIS_CLOUD_DEFER {
3165
48
            init_rs_keys.clear();
3166
48
            has_failure = false;
3167
48
        };
3168
48
        auto tablets_info = sync_executor.when_all(&finished);
3169
48
        if (!finished) {
3170
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3171
1
            return -1;
3172
1
        }
3173
3174
47
        size_t size_before_erase = tablets_info.size();
3175
47
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3176
47
        if (tablets_info.empty()) {
3177
0
            return size_before_erase == 0 ? 0 : -1;
3178
47
        } else if (size_before_erase != tablets_info.size()) {
3179
1
            has_empty_key = true;
3180
1
        }
3181
3182
47
        ret = has_empty_key ? -1 : 0;
3183
        // sort the vector using key's order
3184
47
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3185
47
            return prev.tablet_meta_key < last.tablet_meta_key;
3186
47
        });
3187
47
        std::unique_ptr<Transaction> txn;
3188
47
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3189
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3190
0
            return -1;
3191
0
        }
3192
47
        std::string tablet_key_end;
3193
47
        if (!tablets_info.empty()) {
3194
47
            if (!has_empty_key && !has_failure) {
3195
45
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3196
45
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3197
45
            } else {
3198
8
                for (auto& tablet_info : tablets_info) {
3199
8
                    txn->remove(tablet_info.tablet_meta_key);
3200
8
                }
3201
2
            }
3202
47
        }
3203
47
        if (is_multi_version) {
3204
6
            for (auto& tablet_info : tablets_info) {
3205
                // Remove all versions of tablet compact stats for recycled tablet
3206
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3207
6
                LOG_INFO("remove versioned tablet compact stats key")
3208
6
                        .tag("compact_stats_key", hex(k));
3209
6
                versioned_remove_all(txn.get(), k);
3210
6
            }
3211
6
            for (auto& tablet_info : tablets_info) {
3212
                // Remove all versions of tablet load stats for recycled tablet
3213
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3214
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3215
6
                versioned_remove_all(txn.get(), k);
3216
6
            }
3217
6
            for (auto& tablet_info : tablets_info) {
3218
                // Remove all versions of meta tablet for recycled tablet
3219
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3220
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3221
6
                versioned_remove_all(txn.get(), k);
3222
6
            }
3223
5
        }
3224
248
        for (auto& tablet_info : tablets_info) {
3225
248
            std::string k;
3226
248
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3227
248
            txn->remove(k);
3228
248
        }
3229
248
        for (auto& tablet_info : tablets_info) {
3230
248
            std::string k;
3231
248
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3232
248
            txn->remove(k);
3233
248
        }
3234
47
        for (auto& k : init_rs_keys) {
3235
0
            txn->remove(k);
3236
0
        }
3237
47
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3238
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3239
0
                         << ", err=" << err;
3240
0
            return -1;
3241
0
        }
3242
47
        return ret;
3243
47
    };
3244
3245
54
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
3246
54
                               std::move(loop_done));
3247
54
    if (ret != 0) {
3248
5
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
3249
5
        return ret;
3250
5
    }
3251
3252
    // directly remove tablet stats and tablet jobs of these dropped index or partition
3253
49
    std::unique_ptr<Transaction> txn;
3254
49
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3255
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
3256
0
        return -1;
3257
0
    }
3258
49
    txn->remove(stats_key_begin, stats_key_end);
3259
49
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
3260
49
                 << " end=" << hex(stats_key_end);
3261
49
    txn->remove(job_key_begin, job_key_end);
3262
49
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
3263
49
    std::string schema_key_begin, schema_key_end;
3264
49
    std::string schema_dict_key;
3265
49
    std::string versioned_schema_key_begin, versioned_schema_key_end;
3266
49
    if (partition_id <= 0) {
3267
        // Delete schema kv of this index
3268
15
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
3269
15
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
3270
15
        txn->remove(schema_key_begin, schema_key_end);
3271
15
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
3272
15
                     << " end=" << hex(schema_key_end);
3273
15
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
3274
15
        txn->remove(schema_dict_key);
3275
15
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
3276
15
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
3277
15
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
3278
15
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
3279
15
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
3280
15
                     << " end=" << hex(versioned_schema_key_end);
3281
15
    }
3282
3283
49
    TxnErrorCode err = txn->commit();
3284
49
    if (err != TxnErrorCode::TXN_OK) {
3285
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
3286
0
                     << " err=" << err;
3287
0
        return -1;
3288
0
    }
3289
3290
49
    return ret;
3291
49
}
3292
3293
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
3294
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
3295
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
3296
5.61k
    if (num_segments <= 0) return 0;
3297
3298
5.61k
    std::vector<std::string> file_paths;
3299
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
3300
0
        return -1;
3301
0
    }
3302
3303
    // Process inverted indexes
3304
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
3305
    // default format as v1.
3306
5.61k
    InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
3307
5.61k
    bool delete_rowset_data_by_prefix = false;
3308
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3309
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3310
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3311
0
        delete_rowset_data_by_prefix = true;
3312
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
3313
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
3314
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3315
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3316
10.0k
            }
3317
10.0k
        }
3318
4.80k
        if (rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
3319
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
3320
2.00k
        }
3321
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
3322
        // schema version and index id are not found, delete rowset data by prefix directly.
3323
0
        delete_rowset_data_by_prefix = true;
3324
809
    } else {
3325
        // otherwise, try to get schema kv
3326
809
        InvertedIndexInfo index_info;
3327
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
3328
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
3329
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3330
809
                                 &inverted_index_get_ret);
3331
809
        if (inverted_index_get_ret == 0) {
3332
809
            index_format = index_info.first;
3333
809
            index_ids = index_info.second;
3334
809
        } else if (inverted_index_get_ret == 1) {
3335
            // 1. Schema kv not found means tablet has been recycled
3336
            // Maybe some tablet recycle failed by some bugs
3337
            // We need to delete again to double check
3338
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3339
            // because we are uncertain about the inverted index information.
3340
            // If there are inverted indexes, some data might not be deleted,
3341
            // but this is acceptable as we have made our best effort to delete the data.
3342
0
            LOG_INFO(
3343
0
                    "delete rowset data schema kv not found, need to delete again to double "
3344
0
                    "check")
3345
0
                    .tag("instance_id", instance_id_)
3346
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3347
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
3348
            // Currently index_ids is guaranteed to be empty,
3349
            // but we clear it again here as a safeguard against future code changes
3350
            // that might cause index_ids to no longer be empty
3351
0
            index_format = InvertedIndexStorageFormatPB::V2;
3352
0
            index_ids.clear();
3353
0
        } else {
3354
            // failed to get schema kv, delete rowset data by prefix directly.
3355
0
            delete_rowset_data_by_prefix = true;
3356
0
        }
3357
809
    }
3358
3359
5.61k
    if (delete_rowset_data_by_prefix) {
3360
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
3361
0
                                  rs_meta_pb.rowset_id_v2());
3362
0
    }
3363
3364
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
3365
5.61k
    if (it == accessor_map_.end()) {
3366
1.59k
        LOG_WARNING("instance has no such resource id")
3367
1.59k
                .tag("instance_id", instance_id_)
3368
1.59k
                .tag("resource_id", rs_meta_pb.resource_id());
3369
1.59k
        return -1;
3370
1.59k
    }
3371
4.01k
    auto& accessor = it->second;
3372
3373
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
3374
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
3375
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
3376
20.0k
        add_file_to_delete_if_not_packed(rs_meta_pb, segment_path(tablet_id, rowset_id, i),
3377
20.0k
                                         &file_paths);
3378
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
3379
40.0k
            for (const auto& index_id : index_ids) {
3380
40.0k
                add_file_to_delete_if_not_packed(
3381
40.0k
                        rs_meta_pb,
3382
40.0k
                        inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
3383
40.0k
                                               index_id.second),
3384
40.0k
                        &file_paths);
3385
40.0k
            }
3386
20.0k
        } else if (!index_ids.empty()) {
3387
0
            add_file_to_delete_if_not_packed(
3388
0
                    rs_meta_pb, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
3389
0
        }
3390
20.0k
    }
3391
3392
    // Process delete bitmap - check where it's stored.
3393
4.01k
    DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3394
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3395
4.01k
                                                       &delete_bitmap_storage_type) != 0) {
3396
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3397
0
                .tag("instance_id", instance_id_)
3398
0
                .tag("tablet_id", tablet_id)
3399
0
                .tag("rowset_id", rowset_id);
3400
0
        return -1;
3401
0
    }
3402
4.01k
    if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3403
2.00k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3404
2.00k
    }
3405
    // TODO(AlexYue): seems could do do batch
3406
4.01k
    return accessor->delete_files(file_paths);
3407
4.01k
}
3408
3409
62.3k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3410
62.3k
    LOG_INFO("begin process_packed_file_location_index")
3411
62.3k
            .tag("instance_id", instance_id_)
3412
62.3k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3413
62.3k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3414
62.3k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3415
62.3k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3416
62.3k
    if (index_map.empty()) {
3417
62.3k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3418
62.3k
                .tag("instance_id", instance_id_)
3419
62.3k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3420
62.3k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3421
62.3k
        return 0;
3422
62.3k
    }
3423
3424
16
    struct PackedSmallFileInfo {
3425
16
        std::string small_file_path;
3426
16
    };
3427
16
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3428
16
    packed_file_updates.reserve(index_map.size());
3429
27
    for (const auto& [small_path, index_pb] : index_map) {
3430
27
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3431
0
            continue;
3432
0
        }
3433
27
        packed_file_updates[index_pb.packed_file_path()].push_back(
3434
27
                PackedSmallFileInfo {small_path});
3435
27
    }
3436
16
    if (packed_file_updates.empty()) {
3437
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3438
0
                .tag("instance_id", instance_id_)
3439
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3440
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3441
0
                .tag("index_map_size", index_map.size());
3442
0
        return 0;
3443
0
    }
3444
3445
16
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3446
16
    int ret = 0;
3447
24
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3448
24
        if (small_files.empty()) {
3449
0
            continue;
3450
0
        }
3451
3452
24
        bool success = false;
3453
24
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3454
24
            std::unique_ptr<Transaction> txn;
3455
24
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3456
24
            if (err != TxnErrorCode::TXN_OK) {
3457
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3458
0
                        .tag("instance_id", instance_id_)
3459
0
                        .tag("packed_file_path", packed_file_path)
3460
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3461
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3462
0
                        .tag("err", err);
3463
0
                ret = -1;
3464
0
                break;
3465
0
            }
3466
3467
24
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3468
24
            std::string packed_val;
3469
24
            err = txn->get(packed_key, &packed_val);
3470
24
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3471
0
                LOG_WARNING("packed file info not found when recycling rowset")
3472
0
                        .tag("instance_id", instance_id_)
3473
0
                        .tag("packed_file_path", packed_file_path)
3474
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3475
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3476
0
                        .tag("key", hex(packed_key))
3477
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3478
                // Skip this packed file entry and continue with others
3479
0
                success = true;
3480
0
                break;
3481
0
            }
3482
24
            if (err != TxnErrorCode::TXN_OK) {
3483
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
3484
0
                        .tag("instance_id", instance_id_)
3485
0
                        .tag("packed_file_path", packed_file_path)
3486
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3487
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3488
0
                        .tag("err", err);
3489
0
                ret = -1;
3490
0
                break;
3491
0
            }
3492
3493
24
            cloud::PackedFileInfoPB packed_info;
3494
24
            if (!packed_info.ParseFromString(packed_val)) {
3495
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
3496
0
                        .tag("instance_id", instance_id_)
3497
0
                        .tag("packed_file_path", packed_file_path)
3498
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3499
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3500
0
                ret = -1;
3501
0
                break;
3502
0
            }
3503
3504
24
            LOG_INFO("packed file update check")
3505
24
                    .tag("instance_id", instance_id_)
3506
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3507
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3508
24
                    .tag("merged_file_path", packed_file_path)
3509
24
                    .tag("requested_small_files", small_files.size())
3510
24
                    .tag("merge_entries", packed_info.slices_size());
3511
3512
24
            auto* small_file_entries = packed_info.mutable_slices();
3513
24
            int64_t changed_files = 0;
3514
24
            int64_t missing_entries = 0;
3515
24
            int64_t already_deleted = 0;
3516
27
            for (const auto& small_file_info : small_files) {
3517
27
                bool found = false;
3518
87
                for (auto& small_file_entry : *small_file_entries) {
3519
87
                    if (small_file_entry.path() == small_file_info.small_file_path) {
3520
27
                        if (!small_file_entry.deleted()) {
3521
27
                            small_file_entry.set_deleted(true);
3522
27
                            if (!small_file_entry.corrected()) {
3523
27
                                small_file_entry.set_corrected(true);
3524
27
                            }
3525
27
                            ++changed_files;
3526
27
                        } else {
3527
0
                            ++already_deleted;
3528
0
                        }
3529
27
                        found = true;
3530
27
                        break;
3531
27
                    }
3532
87
                }
3533
27
                if (!found) {
3534
0
                    ++missing_entries;
3535
0
                    LOG_WARNING("packed file info missing small file entry")
3536
0
                            .tag("instance_id", instance_id_)
3537
0
                            .tag("packed_file_path", packed_file_path)
3538
0
                            .tag("small_file_path", small_file_info.small_file_path)
3539
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3540
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
3541
0
                }
3542
27
            }
3543
3544
24
            if (changed_files == 0) {
3545
0
                LOG_INFO("skip merge file update: no merge entries changed")
3546
0
                        .tag("instance_id", instance_id_)
3547
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3548
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3549
0
                        .tag("merged_file_path", packed_file_path)
3550
0
                        .tag("missing_entries", missing_entries)
3551
0
                        .tag("already_deleted", already_deleted)
3552
0
                        .tag("requested_small_files", small_files.size())
3553
0
                        .tag("merge_entries", packed_info.slices_size());
3554
0
                success = true;
3555
0
                break;
3556
0
            }
3557
3558
            // Calculate remaining files
3559
24
            int64_t left_file_count = 0;
3560
24
            int64_t left_file_bytes = 0;
3561
141
            for (const auto& small_file_entry : packed_info.slices()) {
3562
141
                if (!small_file_entry.deleted()) {
3563
57
                    ++left_file_count;
3564
57
                    left_file_bytes += small_file_entry.size();
3565
57
                }
3566
141
            }
3567
24
            packed_info.set_remaining_slice_bytes(left_file_bytes);
3568
24
            packed_info.set_ref_cnt(left_file_count);
3569
24
            LOG_INFO("updated packed file reference info")
3570
24
                    .tag("instance_id", instance_id_)
3571
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3572
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3573
24
                    .tag("packed_file_path", packed_file_path)
3574
24
                    .tag("ref_cnt", left_file_count)
3575
24
                    .tag("left_file_bytes", left_file_bytes);
3576
3577
24
            if (left_file_count == 0) {
3578
7
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3579
7
            }
3580
3581
24
            std::string updated_val;
3582
24
            if (!packed_info.SerializeToString(&updated_val)) {
3583
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
3584
0
                        .tag("instance_id", instance_id_)
3585
0
                        .tag("packed_file_path", packed_file_path)
3586
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3587
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3588
0
                ret = -1;
3589
0
                break;
3590
0
            }
3591
3592
24
            txn->put(packed_key, updated_val);
3593
24
            err = txn->commit();
3594
24
            if (err == TxnErrorCode::TXN_OK) {
3595
24
                success = true;
3596
24
                if (left_file_count == 0) {
3597
7
                    LOG_INFO("packed file ready to delete, deleting immediately")
3598
7
                            .tag("instance_id", instance_id_)
3599
7
                            .tag("packed_file_path", packed_file_path);
3600
7
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3601
0
                        ret = -1;
3602
0
                    }
3603
7
                }
3604
24
                break;
3605
24
            }
3606
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
3607
0
                if (attempt >= max_retry_times) {
3608
0
                    LOG_WARNING("packed file info update conflict after max retry")
3609
0
                            .tag("instance_id", instance_id_)
3610
0
                            .tag("packed_file_path", packed_file_path)
3611
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3612
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
3613
0
                            .tag("changed_files", changed_files)
3614
0
                            .tag("attempt", attempt);
3615
0
                    ret = -1;
3616
0
                    break;
3617
0
                }
3618
0
                LOG_WARNING("packed file info update conflict, retrying")
3619
0
                        .tag("instance_id", instance_id_)
3620
0
                        .tag("packed_file_path", packed_file_path)
3621
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3622
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3623
0
                        .tag("changed_files", changed_files)
3624
0
                        .tag("attempt", attempt);
3625
0
                sleep_for_packed_file_retry();
3626
0
                continue;
3627
0
            }
3628
3629
0
            LOG_WARNING("failed to commit packed file info update")
3630
0
                    .tag("instance_id", instance_id_)
3631
0
                    .tag("packed_file_path", packed_file_path)
3632
0
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3633
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3634
0
                    .tag("err", err)
3635
0
                    .tag("changed_files", changed_files);
3636
0
            ret = -1;
3637
0
            break;
3638
0
        }
3639
3640
24
        if (!success) {
3641
0
            ret = -1;
3642
0
        }
3643
24
    }
3644
3645
16
    return ret;
3646
16
}
3647
3648
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(
3649
        int64_t tablet_id, const std::string& rowset_id,
3650
58.2k
        DeleteBitmapStorageType* out_storage_type) {
3651
58.2k
    if (out_storage_type) {
3652
58.2k
        *out_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3653
58.2k
    }
3654
3655
    // Get delete bitmap storage info from FDB
3656
58.2k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
3657
58.2k
    std::unique_ptr<Transaction> txn;
3658
58.2k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
3659
58.2k
    if (err != TxnErrorCode::TXN_OK) {
3660
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
3661
0
                .tag("instance_id", instance_id_)
3662
0
                .tag("tablet_id", tablet_id)
3663
0
                .tag("rowset_id", rowset_id)
3664
0
                .tag("err", err);
3665
0
        return -1;
3666
0
    }
3667
3668
58.2k
    std::string dbm_val;
3669
58.2k
    err = txn->get(dbm_key, &dbm_val);
3670
58.2k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3671
        // No delete bitmap for this rowset, nothing to do
3672
4.66k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
3673
4.66k
                .tag("instance_id", instance_id_)
3674
4.66k
                .tag("tablet_id", tablet_id)
3675
4.66k
                .tag("rowset_id", rowset_id);
3676
4.66k
        return 0;
3677
4.66k
    }
3678
53.5k
    if (err != TxnErrorCode::TXN_OK) {
3679
0
        LOG_WARNING("failed to get delete bitmap storage")
3680
0
                .tag("instance_id", instance_id_)
3681
0
                .tag("tablet_id", tablet_id)
3682
0
                .tag("rowset_id", rowset_id)
3683
0
                .tag("err", err);
3684
0
        return -1;
3685
0
    }
3686
3687
53.5k
    DeleteBitmapStoragePB storage;
3688
53.5k
    if (!storage.ParseFromString(dbm_val)) {
3689
0
        LOG_WARNING("failed to parse delete bitmap storage")
3690
0
                .tag("instance_id", instance_id_)
3691
0
                .tag("tablet_id", tablet_id)
3692
0
                .tag("rowset_id", rowset_id);
3693
0
        return -1;
3694
0
    }
3695
3696
53.5k
    if (storage.store_in_fdb()) {
3697
0
        if (out_storage_type) {
3698
0
            *out_storage_type = DeleteBitmapStorageType::IN_FDB;
3699
0
        }
3700
0
        return 0;
3701
0
    }
3702
3703
    // Check if delete bitmap is stored in standalone file.
3704
53.5k
    if (!storage.has_packed_slice_location() ||
3705
53.5k
        storage.packed_slice_location().packed_file_path().empty()) {
3706
53.5k
        if (out_storage_type) {
3707
53.5k
            *out_storage_type = DeleteBitmapStorageType::STANDALONE_FILE;
3708
53.5k
        }
3709
53.5k
        return 0;
3710
53.5k
    }
3711
3712
18.4E
    if (out_storage_type) {
3713
0
        *out_storage_type = DeleteBitmapStorageType::PACKED_FILE;
3714
0
    }
3715
3716
18.4E
    const auto& packed_loc = storage.packed_slice_location();
3717
18.4E
    const std::string& packed_file_path = packed_loc.packed_file_path();
3718
3719
18.4E
    LOG_INFO("decrementing delete bitmap packed file ref count")
3720
18.4E
            .tag("instance_id", instance_id_)
3721
18.4E
            .tag("tablet_id", tablet_id)
3722
18.4E
            .tag("rowset_id", rowset_id)
3723
18.4E
            .tag("packed_file_path", packed_file_path);
3724
3725
18.4E
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3726
18.4E
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3727
0
        std::unique_ptr<Transaction> update_txn;
3728
0
        err = txn_kv_->create_txn(&update_txn);
3729
0
        if (err != TxnErrorCode::TXN_OK) {
3730
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
3731
0
                    .tag("instance_id", instance_id_)
3732
0
                    .tag("tablet_id", tablet_id)
3733
0
                    .tag("rowset_id", rowset_id)
3734
0
                    .tag("err", err);
3735
0
            return -1;
3736
0
        }
3737
3738
0
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3739
0
        std::string packed_val;
3740
0
        err = update_txn->get(packed_key, &packed_val);
3741
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3742
0
            LOG_WARNING("packed file info not found for delete bitmap")
3743
0
                    .tag("instance_id", instance_id_)
3744
0
                    .tag("tablet_id", tablet_id)
3745
0
                    .tag("rowset_id", rowset_id)
3746
0
                    .tag("packed_file_path", packed_file_path);
3747
0
            return 0;
3748
0
        }
3749
0
        if (err != TxnErrorCode::TXN_OK) {
3750
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
3751
0
                    .tag("instance_id", instance_id_)
3752
0
                    .tag("tablet_id", tablet_id)
3753
0
                    .tag("rowset_id", rowset_id)
3754
0
                    .tag("packed_file_path", packed_file_path)
3755
0
                    .tag("err", err);
3756
0
            return -1;
3757
0
        }
3758
3759
0
        cloud::PackedFileInfoPB packed_info;
3760
0
        if (!packed_info.ParseFromString(packed_val)) {
3761
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
3762
0
                    .tag("instance_id", instance_id_)
3763
0
                    .tag("tablet_id", tablet_id)
3764
0
                    .tag("rowset_id", rowset_id)
3765
0
                    .tag("packed_file_path", packed_file_path);
3766
0
            return -1;
3767
0
        }
3768
3769
        // Find and mark the small file entry as deleted
3770
        // Use tablet_id and rowset_id to match entry instead of path,
3771
        // because path format may vary with path_version (with or without shard prefix)
3772
0
        auto* entries = packed_info.mutable_slices();
3773
0
        bool found = false;
3774
0
        bool already_deleted = false;
3775
0
        for (auto& entry : *entries) {
3776
0
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
3777
0
                if (!entry.deleted()) {
3778
0
                    entry.set_deleted(true);
3779
0
                    if (!entry.corrected()) {
3780
0
                        entry.set_corrected(true);
3781
0
                    }
3782
0
                } else {
3783
0
                    already_deleted = true;
3784
0
                }
3785
0
                found = true;
3786
0
                break;
3787
0
            }
3788
0
        }
3789
3790
0
        if (!found) {
3791
0
            LOG_WARNING("delete bitmap entry not found in packed file")
3792
0
                    .tag("instance_id", instance_id_)
3793
0
                    .tag("tablet_id", tablet_id)
3794
0
                    .tag("rowset_id", rowset_id)
3795
0
                    .tag("packed_file_path", packed_file_path);
3796
0
            return 0;
3797
0
        }
3798
3799
0
        if (already_deleted) {
3800
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
3801
0
                    .tag("instance_id", instance_id_)
3802
0
                    .tag("tablet_id", tablet_id)
3803
0
                    .tag("rowset_id", rowset_id)
3804
0
                    .tag("packed_file_path", packed_file_path);
3805
0
            return 0;
3806
0
        }
3807
3808
        // Calculate remaining files
3809
0
        int64_t left_file_count = 0;
3810
0
        int64_t left_file_bytes = 0;
3811
0
        for (const auto& entry : packed_info.slices()) {
3812
0
            if (!entry.deleted()) {
3813
0
                ++left_file_count;
3814
0
                left_file_bytes += entry.size();
3815
0
            }
3816
0
        }
3817
0
        packed_info.set_remaining_slice_bytes(left_file_bytes);
3818
0
        packed_info.set_ref_cnt(left_file_count);
3819
3820
0
        if (left_file_count == 0) {
3821
0
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3822
0
        }
3823
3824
0
        std::string updated_val;
3825
0
        if (!packed_info.SerializeToString(&updated_val)) {
3826
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
3827
0
                    .tag("instance_id", instance_id_)
3828
0
                    .tag("tablet_id", tablet_id)
3829
0
                    .tag("rowset_id", rowset_id)
3830
0
                    .tag("packed_file_path", packed_file_path);
3831
0
            return -1;
3832
0
        }
3833
3834
0
        update_txn->put(packed_key, updated_val);
3835
0
        err = update_txn->commit();
3836
0
        if (err == TxnErrorCode::TXN_OK) {
3837
0
            LOG_INFO("delete bitmap packed file ref count decremented")
3838
0
                    .tag("instance_id", instance_id_)
3839
0
                    .tag("tablet_id", tablet_id)
3840
0
                    .tag("rowset_id", rowset_id)
3841
0
                    .tag("packed_file_path", packed_file_path)
3842
0
                    .tag("left_file_count", left_file_count);
3843
0
            if (left_file_count == 0) {
3844
0
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3845
0
                    return -1;
3846
0
                }
3847
0
            }
3848
0
            return 0;
3849
0
        }
3850
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
3851
0
            if (attempt >= max_retry_times) {
3852
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
3853
0
                        .tag("instance_id", instance_id_)
3854
0
                        .tag("tablet_id", tablet_id)
3855
0
                        .tag("rowset_id", rowset_id)
3856
0
                        .tag("packed_file_path", packed_file_path)
3857
0
                        .tag("attempt", attempt);
3858
0
                return -1;
3859
0
            }
3860
0
            sleep_for_packed_file_retry();
3861
0
            continue;
3862
0
        }
3863
3864
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
3865
0
                .tag("instance_id", instance_id_)
3866
0
                .tag("tablet_id", tablet_id)
3867
0
                .tag("rowset_id", rowset_id)
3868
0
                .tag("packed_file_path", packed_file_path)
3869
0
                .tag("err", err);
3870
0
        return -1;
3871
0
    }
3872
3873
18.4E
    return -1;
3874
18.4E
}
3875
3876
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
3877
                                                const std::string& packed_key,
3878
7
                                                const cloud::PackedFileInfoPB& packed_info) {
3879
7
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
3880
0
        LOG_WARNING("packed file missing resource id when recycling")
3881
0
                .tag("instance_id", instance_id_)
3882
0
                .tag("packed_file_path", packed_file_path);
3883
0
        return -1;
3884
0
    }
3885
3886
7
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
3887
7
    if (!accessor) {
3888
0
        LOG_WARNING("no accessor available to delete packed file")
3889
0
                .tag("instance_id", instance_id_)
3890
0
                .tag("packed_file_path", packed_file_path)
3891
0
                .tag("resource_id", packed_info.resource_id());
3892
0
        return -1;
3893
0
    }
3894
3895
7
    int del_ret = accessor->delete_file(packed_file_path);
3896
7
    if (del_ret != 0 && del_ret != 1) {
3897
0
        LOG_WARNING("failed to delete packed file")
3898
0
                .tag("instance_id", instance_id_)
3899
0
                .tag("packed_file_path", packed_file_path)
3900
0
                .tag("resource_id", resource_id)
3901
0
                .tag("ret", del_ret);
3902
0
        return -1;
3903
0
    }
3904
7
    if (del_ret == 1) {
3905
0
        LOG_INFO("packed file already removed")
3906
0
                .tag("instance_id", instance_id_)
3907
0
                .tag("packed_file_path", packed_file_path)
3908
0
                .tag("resource_id", resource_id);
3909
7
    } else {
3910
7
        LOG_INFO("deleted packed file")
3911
7
                .tag("instance_id", instance_id_)
3912
7
                .tag("packed_file_path", packed_file_path)
3913
7
                .tag("resource_id", resource_id);
3914
7
    }
3915
3916
7
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
3917
7
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3918
7
        std::unique_ptr<Transaction> del_txn;
3919
7
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
3920
7
        if (err != TxnErrorCode::TXN_OK) {
3921
0
            LOG_WARNING("failed to create txn when removing packed file kv")
3922
0
                    .tag("instance_id", instance_id_)
3923
0
                    .tag("packed_file_path", packed_file_path)
3924
0
                    .tag("attempt", attempt)
3925
0
                    .tag("err", err);
3926
0
            return -1;
3927
0
        }
3928
3929
7
        std::string latest_val;
3930
7
        err = del_txn->get(packed_key, &latest_val);
3931
7
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3932
0
            return 0;
3933
0
        }
3934
7
        if (err != TxnErrorCode::TXN_OK) {
3935
0
            LOG_WARNING("failed to re-read packed file kv before removal")
3936
0
                    .tag("instance_id", instance_id_)
3937
0
                    .tag("packed_file_path", packed_file_path)
3938
0
                    .tag("attempt", attempt)
3939
0
                    .tag("err", err);
3940
0
            return -1;
3941
0
        }
3942
3943
7
        cloud::PackedFileInfoPB latest_info;
3944
7
        if (!latest_info.ParseFromString(latest_val)) {
3945
0
            LOG_WARNING("failed to parse packed file info before removal")
3946
0
                    .tag("instance_id", instance_id_)
3947
0
                    .tag("packed_file_path", packed_file_path)
3948
0
                    .tag("attempt", attempt);
3949
0
            return -1;
3950
0
        }
3951
3952
7
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
3953
7
              latest_info.ref_cnt() == 0)) {
3954
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
3955
0
                    .tag("instance_id", instance_id_)
3956
0
                    .tag("packed_file_path", packed_file_path)
3957
0
                    .tag("attempt", attempt);
3958
0
            return 0;
3959
0
        }
3960
3961
7
        del_txn->remove(packed_key);
3962
7
        err = del_txn->commit();
3963
7
        if (err == TxnErrorCode::TXN_OK) {
3964
7
            LOG_INFO("removed packed file metadata")
3965
7
                    .tag("instance_id", instance_id_)
3966
7
                    .tag("packed_file_path", packed_file_path);
3967
7
            return 0;
3968
7
        }
3969
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
3970
0
            if (attempt >= max_retry_times) {
3971
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
3972
0
                        .tag("instance_id", instance_id_)
3973
0
                        .tag("packed_file_path", packed_file_path)
3974
0
                        .tag("attempt", attempt);
3975
0
                return -1;
3976
0
            }
3977
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
3978
0
                    .tag("instance_id", instance_id_)
3979
0
                    .tag("packed_file_path", packed_file_path)
3980
0
                    .tag("attempt", attempt);
3981
0
            sleep_for_packed_file_retry();
3982
0
            continue;
3983
0
        }
3984
0
        LOG_WARNING("failed to remove packed file kv")
3985
0
                .tag("instance_id", instance_id_)
3986
0
                .tag("packed_file_path", packed_file_path)
3987
0
                .tag("attempt", attempt)
3988
0
                .tag("err", err);
3989
0
        return -1;
3990
0
    }
3991
0
    return -1;
3992
7
}
3993
3994
int InstanceRecycler::delete_rowset_data(
3995
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
3996
56
        RecyclerMetricsContext& metrics_context) {
3997
56
    int ret = 0;
3998
    // resource_id -> file_paths
3999
56
    std::map<std::string, std::vector<std::string>> resource_file_paths;
4000
    // (resource_id, tablet_id, rowset_id)
4001
56
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
4002
56
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
4003
4004
56.2k
    for (const auto& [_, rs] : rowsets) {
4005
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
4006
        // due to aborted schema change.
4007
56.2k
        if (is_formal_rowset) {
4008
3.19k
            std::lock_guard lock(recycled_tablets_mtx_);
4009
3.19k
            if (recycled_tablets_.count(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
4010
                // Tablet has been recycled and this rowset has no packed slices, so file data
4011
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
4012
                // slice info must still run to decrement packed file ref counts.
4013
0
                continue;
4014
0
            }
4015
3.19k
        }
4016
4017
56.2k
        int64_t num_segments = rs.num_segments();
4018
        // Check num_segments before accessor lookup, because empty rowsets
4019
        // (e.g. base compaction output of empty rowsets) may have no resource_id
4020
        // set. Skipping them early avoids a spurious "no such resource id" error
4021
        // that marks the entire batch as failed and prevents txn_remove from
4022
        // cleaning up recycle KV keys.
4023
56.2k
        if (num_segments <= 0) {
4024
0
            metrics_context.total_recycled_num++;
4025
0
            metrics_context.total_recycled_data_size += rs.total_disk_size();
4026
0
            continue;
4027
0
        }
4028
4029
56.2k
        auto it = accessor_map_.find(rs.resource_id());
4030
        // possible if the accessor is not initilized correctly
4031
56.2k
        if (it == accessor_map_.end()) [[unlikely]] {
4032
2.00k
            LOG_WARNING("instance has no such resource id")
4033
2.00k
                    .tag("instance_id", instance_id_)
4034
2.00k
                    .tag("resource_id", rs.resource_id());
4035
2.00k
            ret = -1;
4036
2.00k
            continue;
4037
2.00k
        }
4038
4039
54.2k
        auto& file_paths = resource_file_paths[rs.resource_id()];
4040
54.2k
        const auto& rowset_id = rs.rowset_id_v2();
4041
54.2k
        int64_t tablet_id = rs.tablet_id();
4042
54.2k
        LOG_INFO("recycle rowset merge index size")
4043
54.2k
                .tag("instance_id", instance_id_)
4044
54.2k
                .tag("tablet_id", tablet_id)
4045
54.2k
                .tag("rowset_id", rowset_id)
4046
54.2k
                .tag("merge_index_size", rs.packed_slice_locations_size());
4047
54.2k
        if (decrement_packed_file_ref_counts(rs) != 0) {
4048
0
            ret = -1;
4049
0
            continue;
4050
0
        }
4051
4052
        // Process delete bitmap - check where it's stored.
4053
54.2k
        DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4054
54.2k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
4055
54.2k
                                                           &delete_bitmap_storage_type) != 0) {
4056
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
4057
0
                    .tag("instance_id", instance_id_)
4058
0
                    .tag("tablet_id", tablet_id)
4059
0
                    .tag("rowset_id", rowset_id);
4060
0
            ret = -1;
4061
0
            continue;
4062
0
        }
4063
54.2k
        if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
4064
51.5k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
4065
51.5k
        }
4066
4067
        // Process inverted indexes
4068
54.2k
        std::vector<std::pair<int64_t, std::string>> index_ids;
4069
        // default format as v1.
4070
54.2k
        InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
4071
54.2k
        int inverted_index_get_ret = 0;
4072
54.2k
        if (rs.has_tablet_schema()) {
4073
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
4074
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
4075
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
4076
53.5k
                }
4077
53.5k
            }
4078
26.6k
            if (rs.tablet_schema().has_inverted_index_storage_format()) {
4079
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
4080
26.5k
            }
4081
27.6k
        } else {
4082
27.6k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
4083
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
4084
0
                                "instance_id="
4085
0
                             << instance_id_ << " tablet_id=" << tablet_id
4086
0
                             << " rowset_id=" << rowset_id;
4087
0
                ret = -1;
4088
0
                continue;
4089
0
            }
4090
27.6k
            InvertedIndexInfo index_info;
4091
27.6k
            inverted_index_get_ret =
4092
27.6k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
4093
27.6k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
4094
27.6k
                                     &inverted_index_get_ret);
4095
27.6k
            if (inverted_index_get_ret == 0) {
4096
27.1k
                index_format = index_info.first;
4097
27.1k
                index_ids = index_info.second;
4098
27.1k
            } else if (inverted_index_get_ret == 1) {
4099
                // 1. Schema kv not found means tablet has been recycled
4100
                // Maybe some tablet recycle failed by some bugs
4101
                // We need to delete again to double check
4102
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
4103
                // because we are uncertain about the inverted index information.
4104
                // If there are inverted indexes, some data might not be deleted,
4105
                // but this is acceptable as we have made our best effort to delete the data.
4106
507
                LOG_INFO(
4107
507
                        "delete rowset data schema kv not found, need to delete again to "
4108
507
                        "double "
4109
507
                        "check")
4110
507
                        .tag("instance_id", instance_id_)
4111
507
                        .tag("tablet_id", tablet_id)
4112
507
                        .tag("rowset", rs.ShortDebugString());
4113
                // Currently index_ids is guaranteed to be empty,
4114
                // but we clear it again here as a safeguard against future code changes
4115
                // that might cause index_ids to no longer be empty
4116
507
                index_format = InvertedIndexStorageFormatPB::V2;
4117
507
                index_ids.clear();
4118
18.4E
            } else {
4119
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
4120
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4121
18.4E
                ret = -1;
4122
18.4E
                continue;
4123
18.4E
            }
4124
27.6k
        }
4125
54.2k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
4126
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
4127
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
4128
10
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
4129
10
            continue;
4130
10
        }
4131
324k
        for (int64_t i = 0; i < num_segments; ++i) {
4132
269k
            add_file_to_delete_if_not_packed(rs, segment_path(tablet_id, rowset_id, i),
4133
269k
                                             &file_paths);
4134
269k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
4135
535k
                for (const auto& index_id : index_ids) {
4136
535k
                    add_file_to_delete_if_not_packed(
4137
535k
                            rs,
4138
535k
                            inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
4139
535k
                                                   index_id.second),
4140
535k
                            &file_paths);
4141
535k
                }
4142
268k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
4143
                // try to recycle inverted index v2 when get_ret == 1
4144
                // we treat schema not found as if it has a v2 format inverted index
4145
                // to reduce chance of data leakage
4146
2.50k
                if (inverted_index_get_ret == 1) {
4147
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
4148
2.50k
                            .tag("instance_id", instance_id_)
4149
2.50k
                            .tag("inverted index v2 path",
4150
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, i));
4151
2.50k
                }
4152
2.50k
                add_file_to_delete_if_not_packed(
4153
2.50k
                        rs, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
4154
2.50k
            }
4155
269k
        }
4156
54.2k
    }
4157
4158
56
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
4159
56
                                                 "delete_rowset_data",
4160
57
                                                 [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clERKi
Line
Count
Source
4160
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
4160
52
                                                 [](const int& ret) { return ret != 0; });
4161
56
    for (auto& [resource_id, file_paths] : resource_file_paths) {
4162
47
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4163
47
            DCHECK(accessor_map_.count(*rid))
4164
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4165
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4166
47
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4167
47
                                     &accessor_map_);
4168
47
            if (!accessor_map_.contains(*rid)) {
4169
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4170
0
                        .tag("resource_id", resource_id)
4171
0
                        .tag("instance_id", instance_id_);
4172
0
                return -1;
4173
0
            }
4174
47
            auto& accessor = accessor_map_[*rid];
4175
47
            int ret = accessor->delete_files(*paths);
4176
47
            if (!ret) {
4177
                // deduplication of different files with the same rowset id
4178
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4179
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4180
47
                std::set<std::string> deleted_rowset_id;
4181
4182
47
                std::for_each(paths->begin(), paths->end(),
4183
47
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4184
855k
                               this](const std::string& path) {
4185
855k
                                  std::vector<std::string> str;
4186
855k
                                  butil::SplitString(path, '/', &str);
4187
855k
                                  std::string rowset_id;
4188
855k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4189
850k
                                      rowset_id = str.back().substr(0, pos);
4190
850k
                                  } else {
4191
4.89k
                                      if (path.find("packed_file/") != std::string::npos) {
4192
0
                                          return; // packed files do not have rowset_id encoded
4193
0
                                      }
4194
4.89k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4195
4.89k
                                      return;
4196
4.89k
                                  }
4197
850k
                                  auto rs_meta = rowsets.find(rowset_id);
4198
850k
                                  if (rs_meta != rowsets.end() &&
4199
856k
                                      !deleted_rowset_id.contains(rowset_id)) {
4200
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
4201
54.1k
                                      metrics_context.total_recycled_data_size +=
4202
54.1k
                                              rs_meta->second.total_disk_size();
4203
54.1k
                                      segment_metrics_context_.total_recycled_num +=
4204
54.1k
                                              rs_meta->second.num_segments();
4205
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
4206
54.1k
                                              rs_meta->second.total_disk_size();
4207
54.1k
                                      metrics_context.total_recycled_num++;
4208
54.1k
                                  }
4209
850k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
4184
7
                               this](const std::string& path) {
4185
7
                                  std::vector<std::string> str;
4186
7
                                  butil::SplitString(path, '/', &str);
4187
7
                                  std::string rowset_id;
4188
7
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4189
7
                                      rowset_id = str.back().substr(0, pos);
4190
7
                                  } else {
4191
0
                                      if (path.find("packed_file/") != std::string::npos) {
4192
0
                                          return; // packed files do not have rowset_id encoded
4193
0
                                      }
4194
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4195
0
                                      return;
4196
0
                                  }
4197
7
                                  auto rs_meta = rowsets.find(rowset_id);
4198
7
                                  if (rs_meta != rowsets.end() &&
4199
7
                                      !deleted_rowset_id.contains(rowset_id)) {
4200
7
                                      deleted_rowset_id.emplace(rowset_id);
4201
7
                                      metrics_context.total_recycled_data_size +=
4202
7
                                              rs_meta->second.total_disk_size();
4203
7
                                      segment_metrics_context_.total_recycled_num +=
4204
7
                                              rs_meta->second.num_segments();
4205
7
                                      segment_metrics_context_.total_recycled_data_size +=
4206
7
                                              rs_meta->second.total_disk_size();
4207
7
                                      metrics_context.total_recycled_num++;
4208
7
                                  }
4209
7
                              });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
4184
855k
                               this](const std::string& path) {
4185
855k
                                  std::vector<std::string> str;
4186
855k
                                  butil::SplitString(path, '/', &str);
4187
855k
                                  std::string rowset_id;
4188
855k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4189
850k
                                      rowset_id = str.back().substr(0, pos);
4190
850k
                                  } else {
4191
4.89k
                                      if (path.find("packed_file/") != std::string::npos) {
4192
0
                                          return; // packed files do not have rowset_id encoded
4193
0
                                      }
4194
4.89k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4195
4.89k
                                      return;
4196
4.89k
                                  }
4197
850k
                                  auto rs_meta = rowsets.find(rowset_id);
4198
850k
                                  if (rs_meta != rowsets.end() &&
4199
855k
                                      !deleted_rowset_id.contains(rowset_id)) {
4200
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
4201
54.1k
                                      metrics_context.total_recycled_data_size +=
4202
54.1k
                                              rs_meta->second.total_disk_size();
4203
54.1k
                                      segment_metrics_context_.total_recycled_num +=
4204
54.1k
                                              rs_meta->second.num_segments();
4205
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
4206
54.1k
                                              rs_meta->second.total_disk_size();
4207
54.1k
                                      metrics_context.total_recycled_num++;
4208
54.1k
                                  }
4209
850k
                              });
4210
47
            }
4211
47
            return ret;
4212
47
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4162
5
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4163
5
            DCHECK(accessor_map_.count(*rid))
4164
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4165
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4166
5
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4167
5
                                     &accessor_map_);
4168
5
            if (!accessor_map_.contains(*rid)) {
4169
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4170
0
                        .tag("resource_id", resource_id)
4171
0
                        .tag("instance_id", instance_id_);
4172
0
                return -1;
4173
0
            }
4174
5
            auto& accessor = accessor_map_[*rid];
4175
5
            int ret = accessor->delete_files(*paths);
4176
5
            if (!ret) {
4177
                // deduplication of different files with the same rowset id
4178
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4179
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4180
5
                std::set<std::string> deleted_rowset_id;
4181
4182
5
                std::for_each(paths->begin(), paths->end(),
4183
5
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4184
5
                               this](const std::string& path) {
4185
5
                                  std::vector<std::string> str;
4186
5
                                  butil::SplitString(path, '/', &str);
4187
5
                                  std::string rowset_id;
4188
5
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4189
5
                                      rowset_id = str.back().substr(0, pos);
4190
5
                                  } else {
4191
5
                                      if (path.find("packed_file/") != std::string::npos) {
4192
5
                                          return; // packed files do not have rowset_id encoded
4193
5
                                      }
4194
5
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4195
5
                                      return;
4196
5
                                  }
4197
5
                                  auto rs_meta = rowsets.find(rowset_id);
4198
5
                                  if (rs_meta != rowsets.end() &&
4199
5
                                      !deleted_rowset_id.contains(rowset_id)) {
4200
5
                                      deleted_rowset_id.emplace(rowset_id);
4201
5
                                      metrics_context.total_recycled_data_size +=
4202
5
                                              rs_meta->second.total_disk_size();
4203
5
                                      segment_metrics_context_.total_recycled_num +=
4204
5
                                              rs_meta->second.num_segments();
4205
5
                                      segment_metrics_context_.total_recycled_data_size +=
4206
5
                                              rs_meta->second.total_disk_size();
4207
5
                                      metrics_context.total_recycled_num++;
4208
5
                                  }
4209
5
                              });
4210
5
            }
4211
5
            return ret;
4212
5
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4162
42
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4163
42
            DCHECK(accessor_map_.count(*rid))
4164
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4165
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4166
42
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4167
42
                                     &accessor_map_);
4168
42
            if (!accessor_map_.contains(*rid)) {
4169
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4170
0
                        .tag("resource_id", resource_id)
4171
0
                        .tag("instance_id", instance_id_);
4172
0
                return -1;
4173
0
            }
4174
42
            auto& accessor = accessor_map_[*rid];
4175
42
            int ret = accessor->delete_files(*paths);
4176
42
            if (!ret) {
4177
                // deduplication of different files with the same rowset id
4178
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4179
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4180
42
                std::set<std::string> deleted_rowset_id;
4181
4182
42
                std::for_each(paths->begin(), paths->end(),
4183
42
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4184
42
                               this](const std::string& path) {
4185
42
                                  std::vector<std::string> str;
4186
42
                                  butil::SplitString(path, '/', &str);
4187
42
                                  std::string rowset_id;
4188
42
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4189
42
                                      rowset_id = str.back().substr(0, pos);
4190
42
                                  } else {
4191
42
                                      if (path.find("packed_file/") != std::string::npos) {
4192
42
                                          return; // packed files do not have rowset_id encoded
4193
42
                                      }
4194
42
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4195
42
                                      return;
4196
42
                                  }
4197
42
                                  auto rs_meta = rowsets.find(rowset_id);
4198
42
                                  if (rs_meta != rowsets.end() &&
4199
42
                                      !deleted_rowset_id.contains(rowset_id)) {
4200
42
                                      deleted_rowset_id.emplace(rowset_id);
4201
42
                                      metrics_context.total_recycled_data_size +=
4202
42
                                              rs_meta->second.total_disk_size();
4203
42
                                      segment_metrics_context_.total_recycled_num +=
4204
42
                                              rs_meta->second.num_segments();
4205
42
                                      segment_metrics_context_.total_recycled_data_size +=
4206
42
                                              rs_meta->second.total_disk_size();
4207
42
                                      metrics_context.total_recycled_num++;
4208
42
                                  }
4209
42
                              });
4210
42
            }
4211
42
            return ret;
4212
42
        });
4213
47
    }
4214
56
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
4215
10
        LOG_INFO(
4216
10
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
4217
10
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
4218
10
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
4219
10
        concurrent_delete_executor.add([&]() -> int {
4220
10
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4221
10
            if (!ret) {
4222
10
                auto rs = rowsets.at(rowset_id);
4223
10
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4224
10
                metrics_context.total_recycled_num++;
4225
10
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4226
10
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4227
10
            }
4228
10
            return ret;
4229
10
        });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_2clEv
Line
Count
Source
4219
10
        concurrent_delete_executor.add([&]() -> int {
4220
10
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4221
10
            if (!ret) {
4222
10
                auto rs = rowsets.at(rowset_id);
4223
10
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4224
10
                metrics_context.total_recycled_num++;
4225
10
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4226
10
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4227
10
            }
4228
10
            return ret;
4229
10
        });
4230
10
    }
4231
4232
56
    bool finished = true;
4233
56
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4234
57
    for (int r : rets) {
4235
57
        if (r != 0) {
4236
0
            ret = -1;
4237
0
            break;
4238
0
        }
4239
57
    }
4240
56
    ret = finished ? ret : -1;
4241
56
    return ret;
4242
56
}
4243
4244
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
4245
3.31k
                                         const std::string& rowset_id) {
4246
3.31k
    auto it = accessor_map_.find(resource_id);
4247
3.31k
    if (it == accessor_map_.end()) {
4248
400
        LOG_WARNING("instance has no such resource id")
4249
400
                .tag("instance_id", instance_id_)
4250
400
                .tag("resource_id", resource_id)
4251
400
                .tag("tablet_id", tablet_id)
4252
400
                .tag("rowset_id", rowset_id);
4253
400
        return -1;
4254
400
    }
4255
2.91k
    auto& accessor = it->second;
4256
2.91k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
4257
3.31k
}
4258
4259
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
4260
4
    if (key.empty()) {
4261
0
        return false;
4262
0
    }
4263
4
    std::string_view key_view = key;
4264
4
    key_view.remove_prefix(1); // remove keyspace prefix
4265
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
4266
4
    if (decode_key(&key_view, &decoded) != 0) {
4267
0
        return false;
4268
0
    }
4269
4
    if (decoded.size() < 4) {
4270
0
        return false;
4271
0
    }
4272
4
    try {
4273
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
4274
4
    } catch (const std::bad_variant_access&) {
4275
0
        return false;
4276
0
    }
4277
4
    return true;
4278
4
}
4279
4280
14
int InstanceRecycler::recycle_packed_files() {
4281
14
    const std::string task_name = "recycle_packed_files";
4282
14
    auto start_tp = steady_clock::now();
4283
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
4284
14
    int ret = 0;
4285
14
    PackedFileRecycleStats stats;
4286
4287
14
    register_recycle_task(task_name, start_time);
4288
14
    DORIS_CLOUD_DEFER {
4289
14
        unregister_recycle_task(task_name);
4290
14
        int64_t cost =
4291
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4292
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4293
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4294
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4295
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4296
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4297
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4298
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4299
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4300
14
                                                             stats.bytes_object_deleted);
4301
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4302
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4303
14
                .tag("instance_id", instance_id_)
4304
14
                .tag("num_scanned", stats.num_scanned)
4305
14
                .tag("num_corrected", stats.num_corrected)
4306
14
                .tag("num_deleted", stats.num_deleted)
4307
14
                .tag("num_failed", stats.num_failed)
4308
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4309
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4310
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4311
14
                .tag("bytes_deleted", stats.bytes_deleted)
4312
14
                .tag("ret", ret);
4313
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
4288
14
    DORIS_CLOUD_DEFER {
4289
14
        unregister_recycle_task(task_name);
4290
14
        int64_t cost =
4291
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4292
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4293
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4294
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4295
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4296
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4297
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4298
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4299
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4300
14
                                                             stats.bytes_object_deleted);
4301
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4302
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4303
14
                .tag("instance_id", instance_id_)
4304
14
                .tag("num_scanned", stats.num_scanned)
4305
14
                .tag("num_corrected", stats.num_corrected)
4306
14
                .tag("num_deleted", stats.num_deleted)
4307
14
                .tag("num_failed", stats.num_failed)
4308
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4309
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4310
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4311
14
                .tag("bytes_deleted", stats.bytes_deleted)
4312
14
                .tag("ret", ret);
4313
14
    };
4314
4315
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4316
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4317
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4318
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
4315
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4316
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4317
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4318
4
    };
4319
4320
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
4321
4322
14
    std::string begin = packed_file_key({instance_id_, ""});
4323
14
    std::string end = packed_file_key({instance_id_, "\xff"});
4324
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
4325
0
        ret = -1;
4326
0
    }
4327
4328
14
    return ret;
4329
14
}
4330
4331
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
4332
                                                  RecyclerMetricsContext& metrics_context,
4333
0
                                                  int64_t partition_id, bool is_empty_tablet) {
4334
0
    std::string tablet_key_begin, tablet_key_end;
4335
4336
0
    if (partition_id > 0) {
4337
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
4338
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
4339
0
    } else {
4340
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
4341
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
4342
0
    }
4343
    // for calculate the total num or bytes of recyled objects
4344
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
4345
0
                                                          std::string_view v) -> int {
4346
0
        doris::TabletMetaCloudPB tablet_meta_pb;
4347
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
4348
0
            return 0;
4349
0
        }
4350
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
4351
4352
0
        if (config::enable_recycler_check_lazy_txn_finished &&
4353
0
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
4354
0
            return 0;
4355
0
        }
4356
4357
0
        if (!is_empty_tablet) {
4358
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
4359
0
                return 0;
4360
0
            }
4361
0
            tablet_metrics_context_.total_need_recycle_num++;
4362
0
        }
4363
0
        return 0;
4364
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_
4365
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
4366
0
    metrics_context.report(true);
4367
0
    tablet_metrics_context_.report(true);
4368
0
    segment_metrics_context_.report(true);
4369
0
    return ret;
4370
0
}
4371
4372
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
4373
0
                                                 RecyclerMetricsContext& metrics_context) {
4374
0
    int ret = 0;
4375
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
4376
0
    std::unique_ptr<Transaction> txn;
4377
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4378
0
        LOG_WARNING("failed to recycle tablet ")
4379
0
                .tag("tablet id", tablet_id)
4380
0
                .tag("instance_id", instance_id_)
4381
0
                .tag("reason", "failed to create txn");
4382
0
        ret = -1;
4383
0
    }
4384
0
    GetRowsetResponse resp;
4385
0
    std::string msg;
4386
0
    MetaServiceCode code = MetaServiceCode::OK;
4387
    // get rowsets in tablet
4388
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4389
0
                        tablet_id, code, msg, &resp);
4390
0
    if (code != MetaServiceCode::OK) {
4391
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4392
0
                .tag("tablet id", tablet_id)
4393
0
                .tag("msg", msg)
4394
0
                .tag("code", code)
4395
0
                .tag("instance id", instance_id_);
4396
0
        ret = -1;
4397
0
    }
4398
0
    for (const auto& rs_meta : resp.rowset_meta()) {
4399
        /*
4400
        * For compatibility, we skip the loop for [0-1] here.
4401
        * The purpose of this loop is to delete object files,
4402
        * and since [0-1] only has meta and doesn't have object files,
4403
        * skipping it doesn't affect system correctness.
4404
        *
4405
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
4406
        * would return error -1 directly, causing the recycle operation to fail.
4407
        *
4408
        * [0-1] doesn't have resource id is a bug.
4409
        * In the future, we will fix this problem, after that,
4410
        * we can remove this if statement.
4411
        *
4412
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
4413
        */
4414
4415
0
        if (rs_meta.end_version() == 1) {
4416
            // Assert that [0-1] has no resource_id to make sure
4417
            // this if statement will not be forgetted to remove
4418
            // when the resource id bug is fixed
4419
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4420
0
            continue;
4421
0
        }
4422
0
        if (!rs_meta.has_resource_id()) {
4423
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4424
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4425
0
                    .tag("instance_id", instance_id_)
4426
0
                    .tag("tablet_id", tablet_id);
4427
0
            continue;
4428
0
        }
4429
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4430
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4431
        // possible if the accessor is not initilized correctly
4432
0
        if (it == accessor_map_.end()) [[unlikely]] {
4433
0
            LOG_WARNING(
4434
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4435
0
                    "recycle process")
4436
0
                    .tag("tablet id", tablet_id)
4437
0
                    .tag("instance_id", instance_id_)
4438
0
                    .tag("resource_id", rs_meta.resource_id())
4439
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4440
0
            continue;
4441
0
        }
4442
4443
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
4444
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4445
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4446
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
4447
0
    }
4448
0
    return ret;
4449
0
}
4450
4451
4.26k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
4452
4.26k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
4453
4.26k
            .tag("instance_id", instance_id_)
4454
4.26k
            .tag("tablet_id", tablet_id);
4455
4456
4.26k
    if (should_recycle_versioned_keys()) {
4457
14
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
4458
14
        if (ret != 0) {
4459
0
            return ret;
4460
0
        }
4461
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
4462
        // during the recycle_versioned_tablet process.
4463
        //
4464
        // .. And remove restore job rowsets of this tablet too
4465
14
    }
4466
4467
4.26k
    int ret = 0;
4468
4.26k
    auto start_time = steady_clock::now();
4469
4470
4.26k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4471
4472
    // collect resource ids
4473
260
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4474
260
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4475
260
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4476
260
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4477
260
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
4478
260
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
4479
4480
260
    std::set<std::string> resource_ids;
4481
260
    int64_t recycle_rowsets_number = 0;
4482
260
    int64_t recycle_segments_number = 0;
4483
260
    int64_t recycle_rowsets_data_size = 0;
4484
260
    int64_t recycle_rowsets_index_size = 0;
4485
260
    int64_t recycle_restore_job_rowsets_number = 0;
4486
260
    int64_t recycle_restore_job_segments_number = 0;
4487
260
    int64_t recycle_restore_job_rowsets_data_size = 0;
4488
260
    int64_t recycle_restore_job_rowsets_index_size = 0;
4489
260
    int64_t max_rowset_version = 0;
4490
260
    int64_t min_rowset_creation_time = INT64_MAX;
4491
260
    int64_t max_rowset_creation_time = 0;
4492
260
    int64_t min_rowset_expiration_time = INT64_MAX;
4493
260
    int64_t max_rowset_expiration_time = 0;
4494
4495
260
    DORIS_CLOUD_DEFER {
4496
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4497
260
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4498
260
                .tag("instance_id", instance_id_)
4499
260
                .tag("tablet_id", tablet_id)
4500
260
                .tag("recycle rowsets number", recycle_rowsets_number)
4501
260
                .tag("recycle segments number", recycle_segments_number)
4502
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4503
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4504
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4505
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4506
260
                .tag("all restore job rowsets recycle data size",
4507
260
                     recycle_restore_job_rowsets_data_size)
4508
260
                .tag("all restore job rowsets recycle index size",
4509
260
                     recycle_restore_job_rowsets_index_size)
4510
260
                .tag("max rowset version", max_rowset_version)
4511
260
                .tag("min rowset creation time", min_rowset_creation_time)
4512
260
                .tag("max rowset creation time", max_rowset_creation_time)
4513
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
4514
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
4515
260
                .tag("task type", metrics_context.operation_type)
4516
260
                .tag("ret", ret);
4517
260
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4495
260
    DORIS_CLOUD_DEFER {
4496
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4497
260
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4498
260
                .tag("instance_id", instance_id_)
4499
260
                .tag("tablet_id", tablet_id)
4500
260
                .tag("recycle rowsets number", recycle_rowsets_number)
4501
260
                .tag("recycle segments number", recycle_segments_number)
4502
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4503
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4504
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4505
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4506
260
                .tag("all restore job rowsets recycle data size",
4507
260
                     recycle_restore_job_rowsets_data_size)
4508
260
                .tag("all restore job rowsets recycle index size",
4509
260
                     recycle_restore_job_rowsets_index_size)
4510
260
                .tag("max rowset version", max_rowset_version)
4511
260
                .tag("min rowset creation time", min_rowset_creation_time)
4512
260
                .tag("max rowset creation time", max_rowset_creation_time)
4513
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
4514
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
4515
260
                .tag("task type", metrics_context.operation_type)
4516
260
                .tag("ret", ret);
4517
260
    };
4518
4519
260
    std::unique_ptr<Transaction> txn;
4520
260
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4521
0
        LOG_WARNING("failed to recycle tablet ")
4522
0
                .tag("tablet id", tablet_id)
4523
0
                .tag("instance_id", instance_id_)
4524
0
                .tag("reason", "failed to create txn");
4525
0
        ret = -1;
4526
0
    }
4527
260
    GetRowsetResponse resp;
4528
260
    std::string msg;
4529
260
    MetaServiceCode code = MetaServiceCode::OK;
4530
    // get rowsets in tablet
4531
260
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4532
260
                        tablet_id, code, msg, &resp);
4533
260
    if (code != MetaServiceCode::OK) {
4534
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4535
0
                .tag("tablet id", tablet_id)
4536
0
                .tag("msg", msg)
4537
0
                .tag("code", code)
4538
0
                .tag("instance id", instance_id_);
4539
0
        ret = -1;
4540
0
    }
4541
260
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
4542
4543
2.54k
    for (const auto& rs_meta : resp.rowset_meta()) {
4544
2.54k
        if (!rs_meta.has_resource_id() || rs_meta.resource_id().empty()) {
4545
3
            if (rs_meta.num_segments() <= 0) {
4546
2
                LOG_INFO("rowset meta has no segments and no resource id, skip this rowset")
4547
2
                        .tag("rs_meta", rs_meta.ShortDebugString())
4548
2
                        .tag("instance_id", instance_id_)
4549
2
                        .tag("tablet_id", tablet_id);
4550
2
                recycle_rowsets_number += 1;
4551
2
                continue;
4552
2
            }
4553
1
            LOG_WARNING("rowset meta has a missing or empty resource id, impossible!")
4554
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
4555
1
                    .tag("instance_id", instance_id_)
4556
1
                    .tag("tablet_id", tablet_id);
4557
1
            return -1;
4558
3
        }
4559
2.54k
        DCHECK(rs_meta.has_resource_id() && !rs_meta.resource_id().empty())
4560
1
                << "rs_meta" << rs_meta.ShortDebugString();
4561
2.54k
        auto it = accessor_map_.find(rs_meta.resource_id());
4562
        // possible if the accessor is not initilized correctly
4563
2.54k
        if (it == accessor_map_.end()) [[unlikely]] {
4564
1
            LOG_WARNING(
4565
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4566
1
                    "recycle process")
4567
1
                    .tag("tablet id", tablet_id)
4568
1
                    .tag("instance_id", instance_id_)
4569
1
                    .tag("resource_id", rs_meta.resource_id())
4570
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4571
1
            return -1;
4572
1
        }
4573
2.54k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4574
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
4575
0
                    .tag("instance_id", instance_id_)
4576
0
                    .tag("tablet_id", tablet_id)
4577
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4578
0
            return -1;
4579
0
        }
4580
2.54k
        recycle_rowsets_number += 1;
4581
2.54k
        recycle_segments_number += rs_meta.num_segments();
4582
2.54k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4583
2.54k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4584
2.54k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4585
2.54k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4586
2.54k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4587
2.54k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4588
2.54k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4589
2.54k
        resource_ids.emplace(rs_meta.resource_id());
4590
2.54k
    }
4591
4592
    // get restore job rowset in tablet
4593
258
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
4594
258
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
4595
258
    if (code != MetaServiceCode::OK) {
4596
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
4597
0
                .tag("tablet id", tablet_id)
4598
0
                .tag("msg", msg)
4599
0
                .tag("code", code)
4600
0
                .tag("instance id", instance_id_);
4601
0
        return -1;
4602
0
    }
4603
4604
258
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
4605
0
        if (!rs_meta.has_resource_id()) {
4606
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4607
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4608
0
                    .tag("instance_id", instance_id_)
4609
0
                    .tag("tablet_id", tablet_id);
4610
0
            return -1;
4611
0
        }
4612
4613
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4614
        // possible if the accessor is not initilized correctly
4615
0
        if (it == accessor_map_.end()) [[unlikely]] {
4616
0
            LOG_WARNING(
4617
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4618
0
                    "recycle process")
4619
0
                    .tag("tablet id", tablet_id)
4620
0
                    .tag("instance_id", instance_id_)
4621
0
                    .tag("resource_id", rs_meta.resource_id())
4622
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4623
0
            return -1;
4624
0
        }
4625
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4626
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
4627
0
                    .tag("instance_id", instance_id_)
4628
0
                    .tag("tablet_id", tablet_id)
4629
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4630
0
            return -1;
4631
0
        }
4632
0
        recycle_restore_job_rowsets_number += 1;
4633
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
4634
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
4635
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
4636
0
        resource_ids.emplace(rs_meta.resource_id());
4637
0
    }
4638
4639
258
    LOG_INFO("recycle tablet start to delete object")
4640
258
            .tag("instance id", instance_id_)
4641
258
            .tag("tablet id", tablet_id)
4642
258
            .tag("recycle tablet resource ids are",
4643
258
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
4644
258
                                 [](std::string rs_id, const auto& it) {
4645
215
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4646
215
                                 }));
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
4644
215
                                 [](std::string rs_id, const auto& it) {
4645
215
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4646
215
                                 }));
4647
4648
258
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
4649
258
            _thread_pool_group.s3_producer_pool,
4650
258
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4651
258
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKSt4pairIiNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKSt4pairIiNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE
Line
Count
Source
4651
208
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
4652
4653
    // delete all rowset data in this tablet
4654
    // ATTN: there may be data leak if not all accessor initilized successfully
4655
    //       partial data deleted if the tablet is stored cross-storage vault
4656
    //       vault id is not attached to TabletMeta...
4657
258
    for (const auto& resource_id : resource_ids) {
4658
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
4659
217
        concurrent_delete_executor.add(
4660
217
                [&, rs_id = resource_id,
4661
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4662
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4663
217
                    if (res != 0) {
4664
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4665
3
                                     << " path=" << accessor_ptr->uri()
4666
3
                                     << " task type=" << metrics_context.operation_type;
4667
3
                        return std::make_pair(-1, rs_id);
4668
3
                    }
4669
214
                    return std::make_pair(0, rs_id);
4670
217
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
4661
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4662
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4663
217
                    if (res != 0) {
4664
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4665
3
                                     << " path=" << accessor_ptr->uri()
4666
3
                                     << " task type=" << metrics_context.operation_type;
4667
3
                        return std::make_pair(-1, rs_id);
4668
3
                    }
4669
214
                    return std::make_pair(0, rs_id);
4670
217
                });
4671
217
    }
4672
4673
258
    bool finished = true;
4674
258
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
4675
258
    for (auto& r : rets) {
4676
217
        if (r.first != 0) {
4677
3
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
4678
3
            ret = -1;
4679
3
        }
4680
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
4681
217
    }
4682
258
    ret = finished ? ret : -1;
4683
4684
258
    if (ret != 0) { // failed recycle tablet data
4685
3
        LOG_WARNING("ret!=0")
4686
3
                .tag("finished", finished)
4687
3
                .tag("ret", ret)
4688
3
                .tag("instance_id", instance_id_)
4689
3
                .tag("tablet_id", tablet_id);
4690
3
        return ret;
4691
3
    }
4692
4693
255
    tablet_metrics_context_.total_recycled_data_size +=
4694
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4695
255
    tablet_metrics_context_.total_recycled_num += 1;
4696
255
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
4697
255
    segment_metrics_context_.total_recycled_data_size +=
4698
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4699
255
    metrics_context.total_recycled_data_size +=
4700
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4701
255
    tablet_metrics_context_.report();
4702
255
    segment_metrics_context_.report();
4703
255
    metrics_context.report();
4704
4705
255
    txn.reset();
4706
255
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4707
0
        LOG_WARNING("failed to recycle tablet ")
4708
0
                .tag("tablet id", tablet_id)
4709
0
                .tag("instance_id", instance_id_)
4710
0
                .tag("reason", "failed to create txn");
4711
0
        ret = -1;
4712
0
    }
4713
    // delete all rowset kv in this tablet
4714
255
    txn->remove(rs_key0, rs_key1);
4715
255
    txn->remove(recyc_rs_key0, recyc_rs_key1);
4716
255
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
4717
4718
    // remove delete bitmap for MoW table
4719
255
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
4720
255
    txn->remove(pending_key);
4721
255
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
4722
255
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
4723
255
    txn->remove(delete_bitmap_start, delete_bitmap_end);
4724
4725
255
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
4726
255
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
4727
255
    txn->remove(dbm_start_key, dbm_end_key);
4728
255
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
4729
255
              << " end=" << hex(dbm_end_key);
4730
4731
255
    TxnErrorCode err = txn->commit();
4732
255
    if (err != TxnErrorCode::TXN_OK) {
4733
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
4734
0
        ret = -1;
4735
0
    }
4736
4737
255
    if (ret == 0) {
4738
        // All object files under tablet have been deleted
4739
255
        std::lock_guard lock(recycled_tablets_mtx_);
4740
255
        recycled_tablets_.insert(tablet_id);
4741
255
    }
4742
4743
255
    return ret;
4744
258
}
4745
4746
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
4747
14
                                               RecyclerMetricsContext& metrics_context) {
4748
14
    int ret = 0;
4749
14
    auto start_time = steady_clock::now();
4750
4751
14
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4752
4753
    // collect resource ids
4754
11
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4755
11
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4756
11
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4757
11
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4758
4759
11
    int64_t recycle_rowsets_number = 0;
4760
11
    int64_t recycle_segments_number = 0;
4761
11
    int64_t recycle_rowsets_data_size = 0;
4762
11
    int64_t recycle_rowsets_index_size = 0;
4763
11
    int64_t max_rowset_version = 0;
4764
11
    int64_t min_rowset_creation_time = INT64_MAX;
4765
11
    int64_t max_rowset_creation_time = 0;
4766
11
    int64_t min_rowset_expiration_time = INT64_MAX;
4767
11
    int64_t max_rowset_expiration_time = 0;
4768
4769
11
    DORIS_CLOUD_DEFER {
4770
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4771
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4772
11
                .tag("instance_id", instance_id_)
4773
11
                .tag("tablet_id", tablet_id)
4774
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4775
11
                .tag("recycle segments number", recycle_segments_number)
4776
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4777
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4778
11
                .tag("max rowset version", max_rowset_version)
4779
11
                .tag("min rowset creation time", min_rowset_creation_time)
4780
11
                .tag("max rowset creation time", max_rowset_creation_time)
4781
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4782
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4783
11
                .tag("ret", ret);
4784
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4769
11
    DORIS_CLOUD_DEFER {
4770
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4771
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4772
11
                .tag("instance_id", instance_id_)
4773
11
                .tag("tablet_id", tablet_id)
4774
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4775
11
                .tag("recycle segments number", recycle_segments_number)
4776
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4777
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4778
11
                .tag("max rowset version", max_rowset_version)
4779
11
                .tag("min rowset creation time", min_rowset_creation_time)
4780
11
                .tag("max rowset creation time", max_rowset_creation_time)
4781
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4782
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4783
11
                .tag("ret", ret);
4784
11
    };
4785
4786
11
    std::unique_ptr<Transaction> txn;
4787
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4788
0
        LOG_WARNING("failed to recycle tablet ")
4789
0
                .tag("tablet id", tablet_id)
4790
0
                .tag("instance_id", instance_id_)
4791
0
                .tag("reason", "failed to create txn");
4792
0
        ret = -1;
4793
0
    }
4794
4795
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
4796
    // by the related operation logs.
4797
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
4798
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
4799
11
    MetaReader meta_reader(instance_id_);
4800
11
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
4801
11
    if (err == TxnErrorCode::TXN_OK) {
4802
11
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
4803
11
    }
4804
11
    if (err != TxnErrorCode::TXN_OK) {
4805
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4806
0
                .tag("tablet id", tablet_id)
4807
0
                .tag("err", err)
4808
0
                .tag("instance id", instance_id_);
4809
0
        ret = -1;
4810
0
    }
4811
4812
11
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
4813
11
             load_rowset_metas.size(), compact_rowset_metas.size())
4814
11
            .tag("instance_id", instance_id_)
4815
11
            .tag("tablet_id", tablet_id);
4816
4817
11
    SyncExecutor<int> concurrent_delete_executor(
4818
11
            _thread_pool_group.s3_producer_pool,
4819
11
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4820
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
4821
4822
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
4823
60
        recycle_rowsets_number += 1;
4824
60
        recycle_segments_number += rs_meta.num_segments();
4825
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4826
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4827
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4828
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4829
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4830
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4831
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4832
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
4822
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
4823
60
        recycle_rowsets_number += 1;
4824
60
        recycle_segments_number += rs_meta.num_segments();
4825
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4826
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4827
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4828
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4829
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4830
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4831
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4832
60
    };
4833
4834
11
    std::vector<RowsetDeleteTask> all_tasks;
4835
60
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
4836
60
        update_rowset_stats(rs_meta);
4837
        // Version 0-1 rowset has no resource_id and no actual data files,
4838
        // but still needs ref_count key cleanup, so we add it to all_tasks.
4839
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
4840
60
        RowsetDeleteTask task;
4841
60
        task.rowset_meta = rs_meta;
4842
60
        task.versioned_rowset_key =
4843
60
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
4844
60
        task.non_versioned_rowset_key =
4845
60
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
4846
60
        task.versionstamp = versionstamp;
4847
60
        all_tasks.push_back(std::move(task));
4848
60
    }
4849
4850
11
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
4851
0
        update_rowset_stats(rs_meta);
4852
        // Version 0-1 rowset has no resource_id and no actual data files,
4853
        // but still needs ref_count key cleanup, so we add it to all_tasks.
4854
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
4855
0
        RowsetDeleteTask task;
4856
0
        task.rowset_meta = rs_meta;
4857
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
4858
0
                {instance_id_, tablet_id, rs_meta.end_version()});
4859
0
        task.non_versioned_rowset_key =
4860
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
4861
0
        task.versionstamp = versionstamp;
4862
0
        all_tasks.push_back(std::move(task));
4863
0
    }
4864
4865
11
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
4866
0
        RecycleRowsetPB recycle_rowset;
4867
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
4868
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4869
0
            return -1;
4870
0
        }
4871
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
4872
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
4873
                // in old version, keep this key-value pair and it needs to be checked manually
4874
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4875
0
                return -1;
4876
0
            }
4877
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
4878
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
4879
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
4880
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
4881
0
                return -1;
4882
0
            }
4883
            // decode rowset_id
4884
0
            auto k1 = k;
4885
0
            k1.remove_prefix(1);
4886
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
4887
0
            decode_key(&k1, &out);
4888
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
4889
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
4890
0
            LOG_INFO("delete old-version rowset data")
4891
0
                    .tag("instance_id", instance_id_)
4892
0
                    .tag("tablet_id", tablet_id)
4893
0
                    .tag("rowset_id", rowset_id);
4894
4895
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
4896
            // so we must use prefix deletion directly instead of batch delete.
4897
0
            concurrent_delete_executor.add(
4898
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
4899
                        // delete by prefix, the recycle rowset key will be deleted by range later.
4900
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
4901
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
4902
0
        } else {
4903
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
4904
            // Version 0-1 rowset has no resource_id and no actual data files,
4905
            // but still needs ref_count key cleanup, so we add it to all_tasks.
4906
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
4907
0
            RowsetDeleteTask task;
4908
0
            task.rowset_meta = rowset_meta;
4909
0
            task.recycle_rowset_key = k;
4910
0
            all_tasks.push_back(std::move(task));
4911
0
        }
4912
0
        return 0;
4913
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_
4914
4915
11
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
4916
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
4917
0
                .tag("tablet id", tablet_id)
4918
0
                .tag("instance_id", instance_id_)
4919
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
4920
0
        ret = -1;
4921
0
    }
4922
4923
    // Phase 1: Classify tasks by ref_count
4924
11
    std::vector<RowsetDeleteTask> batch_delete_tasks;
4925
60
    for (auto& task : all_tasks) {
4926
60
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
4927
60
        if (classify_ret < 0) {
4928
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
4929
0
                    .tag("instance_id", instance_id_)
4930
0
                    .tag("tablet_id", tablet_id)
4931
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
4932
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
4933
0
                return recycle_rowset_meta_and_data(t);
4934
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_4clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_4clEv
4935
0
        }
4936
60
    }
4937
4938
11
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
4939
4940
11
    LOG_INFO("batch delete plan created")
4941
11
            .tag("instance_id", instance_id_)
4942
11
            .tag("tablet_id", tablet_id)
4943
11
            .tag("plan_count", batch_delete_tasks.size());
4944
4945
    // Phase 2: Execute batch delete using existing delete_rowset_data
4946
11
    if (!batch_delete_tasks.empty()) {
4947
10
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
4948
49
        for (const auto& task : batch_delete_tasks) {
4949
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
4950
49
            if (task.rowset_meta.resource_id().empty()) {
4951
10
                LOG_INFO("skip rowset with empty resource_id in batch delete")
4952
10
                        .tag("instance_id", instance_id_)
4953
10
                        .tag("tablet_id", tablet_id)
4954
10
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
4955
10
                continue;
4956
10
            }
4957
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
4958
39
        }
4959
4960
        // Only call delete_rowset_data if there are rowsets with actual data to delete
4961
10
        bool delete_success = true;
4962
10
        if (!rowsets_to_delete.empty()) {
4963
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
4964
9
                                                         "batch_delete_versioned_tablet");
4965
9
            int delete_ret = delete_rowset_data(
4966
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
4967
9
            if (delete_ret != 0) {
4968
0
                LOG_WARNING("batch delete execution failed")
4969
0
                        .tag("instance_id", instance_id_)
4970
0
                        .tag("tablet_id", tablet_id);
4971
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
4972
0
                ret = -1;
4973
0
                delete_success = false;
4974
0
            }
4975
9
        }
4976
4977
        // Phase 3: Only cleanup metadata if data deletion succeeded.
4978
        // If deletion failed, keep recycle_rowset_key so next round will retry.
4979
10
        if (delete_success) {
4980
10
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
4981
10
            if (cleanup_ret != 0) {
4982
0
                LOG_WARNING("batch delete cleanup failed")
4983
0
                        .tag("instance_id", instance_id_)
4984
0
                        .tag("tablet_id", tablet_id);
4985
0
                ret = -1;
4986
0
            }
4987
10
        }
4988
10
    }
4989
4990
    // Always wait for fallback tasks to complete before returning
4991
11
    bool finished = true;
4992
11
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4993
11
    for (int r : rets) {
4994
0
        if (r != 0) {
4995
0
            ret = -1;
4996
0
        }
4997
0
    }
4998
4999
11
    ret = finished ? ret : -1;
5000
5001
11
    if (ret != 0) { // failed recycle tablet data
5002
0
        LOG_WARNING("recycle versioned tablet failed")
5003
0
                .tag("finished", finished)
5004
0
                .tag("ret", ret)
5005
0
                .tag("instance_id", instance_id_)
5006
0
                .tag("tablet_id", tablet_id);
5007
0
        return ret;
5008
0
    }
5009
5010
11
    tablet_metrics_context_.total_recycled_data_size +=
5011
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5012
11
    tablet_metrics_context_.total_recycled_num += 1;
5013
11
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5014
11
    segment_metrics_context_.total_recycled_data_size +=
5015
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5016
11
    metrics_context.total_recycled_data_size +=
5017
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5018
11
    tablet_metrics_context_.report();
5019
11
    segment_metrics_context_.report();
5020
11
    metrics_context.report();
5021
5022
11
    txn.reset();
5023
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5024
0
        LOG_WARNING("failed to recycle tablet ")
5025
0
                .tag("tablet id", tablet_id)
5026
0
                .tag("instance_id", instance_id_)
5027
0
                .tag("reason", "failed to create txn");
5028
0
        ret = -1;
5029
0
    }
5030
    // delete all rowset kv in this tablet
5031
11
    txn->remove(rs_key0, rs_key1);
5032
11
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5033
5034
    // remove delete bitmap for MoW table
5035
11
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5036
11
    txn->remove(pending_key);
5037
11
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5038
11
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5039
11
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5040
5041
11
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5042
11
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5043
11
    txn->remove(dbm_start_key, dbm_end_key);
5044
11
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5045
11
              << " end=" << hex(dbm_end_key);
5046
5047
11
    std::string versioned_idx_key = versioned::tablet_index_key({instance_id_, tablet_id});
5048
11
    std::string tablet_index_val;
5049
11
    err = txn->get(versioned_idx_key, &tablet_index_val);
5050
11
    if (err != TxnErrorCode::TXN_KEY_NOT_FOUND && err != TxnErrorCode::TXN_OK) {
5051
0
        LOG_WARNING("failed to get tablet index kv")
5052
0
                .tag("instance_id", instance_id_)
5053
0
                .tag("tablet_id", tablet_id)
5054
0
                .tag("err", err);
5055
0
        ret = -1;
5056
11
    } else if (err == TxnErrorCode::TXN_OK) {
5057
        // If the tablet index kv exists, we need to delete it
5058
10
        TabletIndexPB tablet_index_pb;
5059
10
        if (!tablet_index_pb.ParseFromString(tablet_index_val)) {
5060
0
            LOG_WARNING("failed to parse tablet index pb")
5061
0
                    .tag("instance_id", instance_id_)
5062
0
                    .tag("tablet_id", tablet_id);
5063
0
            ret = -1;
5064
10
        } else {
5065
10
            std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
5066
10
                    {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
5067
10
                     tablet_index_pb.index_id(), tablet_index_pb.partition_id(), tablet_id});
5068
10
            txn->remove(versioned_inverted_idx_key);
5069
10
            txn->remove(versioned_idx_key);
5070
10
        }
5071
10
    }
5072
5073
11
    err = txn->commit();
5074
11
    if (err != TxnErrorCode::TXN_OK) {
5075
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5076
0
        ret = -1;
5077
0
    }
5078
5079
11
    if (ret == 0) {
5080
        // All object files under tablet have been deleted
5081
11
        std::lock_guard lock(recycled_tablets_mtx_);
5082
11
        recycled_tablets_.insert(tablet_id);
5083
11
    }
5084
5085
11
    return ret;
5086
11
}
5087
5088
68
int InstanceRecycler::recycle_rowsets() {
5089
68
    if (should_recycle_versioned_keys()) {
5090
5
        return recycle_versioned_rowsets();
5091
5
    }
5092
5093
63
    const std::string task_name = "recycle_rowsets";
5094
63
    int64_t num_scanned = 0;
5095
63
    int64_t num_expired = 0;
5096
63
    int64_t num_prepare = 0;
5097
63
    int64_t num_compacted = 0;
5098
63
    int64_t num_empty_rowset = 0;
5099
63
    size_t total_rowset_key_size = 0;
5100
63
    size_t total_rowset_value_size = 0;
5101
63
    size_t expired_rowset_size = 0;
5102
63
    std::atomic_long num_recycled = 0;
5103
63
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5104
5105
63
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5106
63
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5107
63
    std::string recyc_rs_key0;
5108
63
    std::string recyc_rs_key1;
5109
63
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5110
63
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5111
5112
63
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5113
5114
63
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5115
63
    register_recycle_task(task_name, start_time);
5116
5117
63
    DORIS_CLOUD_DEFER {
5118
63
        unregister_recycle_task(task_name);
5119
63
        int64_t cost =
5120
63
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5121
63
        metrics_context.finish_report();
5122
63
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5123
63
                .tag("instance_id", instance_id_)
5124
63
                .tag("num_scanned", num_scanned)
5125
63
                .tag("num_expired", num_expired)
5126
63
                .tag("num_recycled", num_recycled)
5127
63
                .tag("num_recycled.prepare", num_prepare)
5128
63
                .tag("num_recycled.compacted", num_compacted)
5129
63
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5130
63
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5131
63
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5132
63
                .tag("expired_rowset_meta_size", expired_rowset_size);
5133
63
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5117
7
    DORIS_CLOUD_DEFER {
5118
7
        unregister_recycle_task(task_name);
5119
7
        int64_t cost =
5120
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5121
7
        metrics_context.finish_report();
5122
7
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5123
7
                .tag("instance_id", instance_id_)
5124
7
                .tag("num_scanned", num_scanned)
5125
7
                .tag("num_expired", num_expired)
5126
7
                .tag("num_recycled", num_recycled)
5127
7
                .tag("num_recycled.prepare", num_prepare)
5128
7
                .tag("num_recycled.compacted", num_compacted)
5129
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5130
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5131
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5132
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
5133
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5117
56
    DORIS_CLOUD_DEFER {
5118
56
        unregister_recycle_task(task_name);
5119
56
        int64_t cost =
5120
56
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5121
56
        metrics_context.finish_report();
5122
56
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5123
56
                .tag("instance_id", instance_id_)
5124
56
                .tag("num_scanned", num_scanned)
5125
56
                .tag("num_expired", num_expired)
5126
56
                .tag("num_recycled", num_recycled)
5127
56
                .tag("num_recycled.prepare", num_prepare)
5128
56
                .tag("num_recycled.compacted", num_compacted)
5129
56
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5130
56
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5131
56
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5132
56
                .tag("expired_rowset_meta_size", expired_rowset_size);
5133
56
    };
5134
5135
63
    struct RecycleRowsetEntry {
5136
63
        std::string key;
5137
63
        doris::RowsetMetaCloudPB meta;
5138
63
    };
5139
63
    struct RecycleRowsetDeleteJob {
5140
63
        std::vector<std::string> keys;
5141
63
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
5142
63
    };
5143
    // Store the scanned recycle key with rowset meta. The scanned key is the actual KV key to delete.
5144
63
    std::vector<RecycleRowsetEntry> rowsets;
5145
63
    int64_t current_tablet_id = -1;
5146
63
    int64_t recycled_rowset_count_for_current_tablet = 0;
5147
63
    bool current_tablet_skip_logged = false;
5148
63
    std::string next_scan_begin;
5149
63
    const int64_t rowset_batch_size_per_tablet =
5150
63
            std::max(1, config::recycle_rowsets_per_tablet_batch_size);
5151
63
    const int64_t delete_rowset_batch_size =
5152
63
            std::min(500000, config::recycle_rowsets_delete_batch_size);
5153
4.05k
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5154
4.05k
        if (current_tablet_id != tablet_id) {
5155
27
            current_tablet_id = tablet_id;
5156
27
            recycled_rowset_count_for_current_tablet = 0;
5157
27
            current_tablet_skip_logged = false;
5158
27
        }
5159
4.05k
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5160
7
            if (!current_tablet_skip_logged) {
5161
7
                LOG_INFO(
5162
7
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5163
7
                        .tag("instance_id", instance_id_)
5164
7
                        .tag("tablet_id", tablet_id)
5165
7
                        .tag("limit", rowset_batch_size_per_tablet);
5166
7
                current_tablet_skip_logged = true;
5167
7
            }
5168
7
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5169
7
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5170
7
            return false;
5171
7
        }
5172
4.04k
        ++recycled_rowset_count_for_current_tablet;
5173
4.04k
        return true;
5174
4.05k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_8clEl
Line
Count
Source
5153
7
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5154
7
        if (current_tablet_id != tablet_id) {
5155
7
            current_tablet_id = tablet_id;
5156
7
            recycled_rowset_count_for_current_tablet = 0;
5157
7
            current_tablet_skip_logged = false;
5158
7
        }
5159
7
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5160
0
            if (!current_tablet_skip_logged) {
5161
0
                LOG_INFO(
5162
0
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5163
0
                        .tag("instance_id", instance_id_)
5164
0
                        .tag("tablet_id", tablet_id)
5165
0
                        .tag("limit", rowset_batch_size_per_tablet);
5166
0
                current_tablet_skip_logged = true;
5167
0
            }
5168
0
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5169
0
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5170
0
            return false;
5171
0
        }
5172
7
        ++recycled_rowset_count_for_current_tablet;
5173
7
        return true;
5174
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_8clEl
Line
Count
Source
5153
4.04k
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5154
4.04k
        if (current_tablet_id != tablet_id) {
5155
20
            current_tablet_id = tablet_id;
5156
20
            recycled_rowset_count_for_current_tablet = 0;
5157
20
            current_tablet_skip_logged = false;
5158
20
        }
5159
4.04k
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5160
7
            if (!current_tablet_skip_logged) {
5161
7
                LOG_INFO(
5162
7
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5163
7
                        .tag("instance_id", instance_id_)
5164
7
                        .tag("tablet_id", tablet_id)
5165
7
                        .tag("limit", rowset_batch_size_per_tablet);
5166
7
                current_tablet_skip_logged = true;
5167
7
            }
5168
7
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5169
7
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5170
7
            return false;
5171
7
        }
5172
4.04k
        ++recycled_rowset_count_for_current_tablet;
5173
4.04k
        return true;
5174
4.04k
    };
5175
4.05k
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5176
4.05k
        if (next_scan_begin.empty()) {
5177
4.04k
            return false;
5178
4.04k
        }
5179
7
        *begin = std::move(next_scan_begin);
5180
7
        next_scan_begin.clear();
5181
7
        return true;
5182
4.05k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clEPNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5175
7
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5176
7
        if (next_scan_begin.empty()) {
5177
7
            return false;
5178
7
        }
5179
0
        *begin = std::move(next_scan_begin);
5180
0
        next_scan_begin.clear();
5181
0
        return true;
5182
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clEPNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5175
4.04k
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5176
4.04k
        if (next_scan_begin.empty()) {
5177
4.04k
            return false;
5178
4.04k
        }
5179
7
        *begin = std::move(next_scan_begin);
5180
7
        next_scan_begin.clear();
5181
7
        return true;
5182
4.04k
    };
5183
5184
63
    std::vector<std::string> rowset_keys_to_mark_recycled;
5185
63
    std::vector<std::string> rowset_keys_to_abort;
5186
63
    std::vector<std::string> prepare_rowset_keys_to_delete;
5187
5188
    // Store keys of rowset recycled by background workers
5189
63
    std::mutex async_recycled_rowset_keys_mutex;
5190
63
    std::vector<std::string> async_recycled_rowset_keys;
5191
63
    std::vector<std::string> rowset_keys_without_data;
5192
63
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5193
63
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5194
63
    worker_pool->start();
5195
63
    auto mark_abort_worker_pool = std::make_unique<SimpleThreadPool>(
5196
63
            config::instance_recycler_worker_pool_size, "recycle_rs_mark_abort");
5197
63
    mark_abort_worker_pool->start();
5198
    // TODO bacth delete
5199
4.03k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5200
4.03k
        std::string dbm_start_key =
5201
4.03k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5202
4.03k
        std::string dbm_end_key = dbm_start_key;
5203
4.03k
        encode_int64(INT64_MAX, &dbm_end_key);
5204
4.03k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5205
4.03k
        if (ret != 0) {
5206
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5207
0
                         << instance_id_;
5208
0
        }
5209
4.03k
        return ret;
5210
4.03k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_7clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5199
3
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5200
3
        std::string dbm_start_key =
5201
3
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5202
3
        std::string dbm_end_key = dbm_start_key;
5203
3
        encode_int64(INT64_MAX, &dbm_end_key);
5204
3
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5205
3
        if (ret != 0) {
5206
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5207
0
                         << instance_id_;
5208
0
        }
5209
3
        return ret;
5210
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_7clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5199
4.03k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5200
4.03k
        std::string dbm_start_key =
5201
4.03k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5202
4.03k
        std::string dbm_end_key = dbm_start_key;
5203
4.03k
        encode_int64(INT64_MAX, &dbm_end_key);
5204
4.03k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5205
4.03k
        if (ret != 0) {
5206
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5207
0
                         << instance_id_;
5208
0
        }
5209
4.03k
        return ret;
5210
4.03k
    };
5211
63
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5212
903
                                            int64_t tablet_id, const std::string& rowset_id) {
5213
        // Try to delete rowset data in background thread
5214
903
        int ret = worker_pool->submit_with_timeout(
5215
903
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5216
836
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5217
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5218
0
                        return;
5219
0
                    }
5220
836
                    std::vector<std::string> keys;
5221
836
                    {
5222
836
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5223
836
                        async_recycled_rowset_keys.push_back(std::move(key));
5224
836
                        if (async_recycled_rowset_keys.size() > 100) {
5225
6
                            keys.swap(async_recycled_rowset_keys);
5226
6
                        }
5227
836
                    }
5228
836
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5229
836
                    if (keys.empty()) return;
5230
6
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5231
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5232
0
                                     << instance_id_;
5233
6
                    } else {
5234
6
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5235
6
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5236
6
                                           num_recycled, start_time);
5237
6
                    }
5238
6
                },
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
5215
3
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5216
3
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5217
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5218
0
                        return;
5219
0
                    }
5220
3
                    std::vector<std::string> keys;
5221
3
                    {
5222
3
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5223
3
                        async_recycled_rowset_keys.push_back(std::move(key));
5224
3
                        if (async_recycled_rowset_keys.size() > 100) {
5225
0
                            keys.swap(async_recycled_rowset_keys);
5226
0
                        }
5227
3
                    }
5228
3
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5229
3
                    if (keys.empty()) return;
5230
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5231
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5232
0
                                     << instance_id_;
5233
0
                    } else {
5234
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5235
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5236
0
                                           num_recycled, start_time);
5237
0
                    }
5238
0
                },
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
5215
833
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5216
833
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5217
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5218
0
                        return;
5219
0
                    }
5220
833
                    std::vector<std::string> keys;
5221
833
                    {
5222
833
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5223
833
                        async_recycled_rowset_keys.push_back(std::move(key));
5224
833
                        if (async_recycled_rowset_keys.size() > 100) {
5225
6
                            keys.swap(async_recycled_rowset_keys);
5226
6
                        }
5227
833
                    }
5228
833
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5229
833
                    if (keys.empty()) return;
5230
6
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5231
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5232
0
                                     << instance_id_;
5233
6
                    } else {
5234
6
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5235
6
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5236
6
                                           num_recycled, start_time);
5237
6
                    }
5238
6
                },
5239
903
                0);
5240
903
        if (ret == 0) return 0;
5241
        // Submit task failed, delete rowset data in current thread
5242
67
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5243
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5244
0
            return -1;
5245
0
        }
5246
67
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5247
0
            return -1;
5248
0
        }
5249
67
        rowset_keys_without_data.push_back(std::move(key));
5250
67
        return 0;
5251
67
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
5212
3
                                            int64_t tablet_id, const std::string& rowset_id) {
5213
        // Try to delete rowset data in background thread
5214
3
        int ret = worker_pool->submit_with_timeout(
5215
3
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5216
3
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5217
3
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5218
3
                        return;
5219
3
                    }
5220
3
                    std::vector<std::string> keys;
5221
3
                    {
5222
3
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5223
3
                        async_recycled_rowset_keys.push_back(std::move(key));
5224
3
                        if (async_recycled_rowset_keys.size() > 100) {
5225
3
                            keys.swap(async_recycled_rowset_keys);
5226
3
                        }
5227
3
                    }
5228
3
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5229
3
                    if (keys.empty()) return;
5230
3
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5231
3
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5232
3
                                     << instance_id_;
5233
3
                    } else {
5234
3
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5235
3
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5236
3
                                           num_recycled, start_time);
5237
3
                    }
5238
3
                },
5239
3
                0);
5240
3
        if (ret == 0) return 0;
5241
        // Submit task failed, delete rowset data in current thread
5242
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5243
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5244
0
            return -1;
5245
0
        }
5246
0
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5247
0
            return -1;
5248
0
        }
5249
0
        rowset_keys_without_data.push_back(std::move(key));
5250
0
        return 0;
5251
0
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
5212
900
                                            int64_t tablet_id, const std::string& rowset_id) {
5213
        // Try to delete rowset data in background thread
5214
900
        int ret = worker_pool->submit_with_timeout(
5215
900
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5216
900
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5217
900
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5218
900
                        return;
5219
900
                    }
5220
900
                    std::vector<std::string> keys;
5221
900
                    {
5222
900
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5223
900
                        async_recycled_rowset_keys.push_back(std::move(key));
5224
900
                        if (async_recycled_rowset_keys.size() > 100) {
5225
900
                            keys.swap(async_recycled_rowset_keys);
5226
900
                        }
5227
900
                    }
5228
900
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5229
900
                    if (keys.empty()) return;
5230
900
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5231
900
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5232
900
                                     << instance_id_;
5233
900
                    } else {
5234
900
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5235
900
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5236
900
                                           num_recycled, start_time);
5237
900
                    }
5238
900
                },
5239
900
                0);
5240
900
        if (ret == 0) return 0;
5241
        // Submit task failed, delete rowset data in current thread
5242
67
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5243
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5244
0
            return -1;
5245
0
        }
5246
67
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5247
0
            return -1;
5248
0
        }
5249
67
        rowset_keys_without_data.push_back(std::move(key));
5250
67
        return 0;
5251
67
    };
5252
5253
63
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5254
5255
4.05k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5256
4.05k
        ++num_scanned;
5257
4.05k
        total_rowset_key_size += k.size();
5258
4.05k
        total_rowset_value_size += v.size();
5259
4.05k
        RecycleRowsetPB rowset;
5260
4.05k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5261
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5262
0
            return -1;
5263
0
        }
5264
5265
4.05k
        int64_t current_time = ::time(nullptr);
5266
4.05k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5267
5268
4.05k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5269
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5270
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5271
4.05k
        if (current_time < expiration) { // not expired
5272
0
            return 0;
5273
0
        }
5274
4.05k
        ++num_expired;
5275
4.05k
        expired_rowset_size += v.size();
5276
5277
4.05k
        int64_t tablet_id =
5278
4.05k
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5279
4.05k
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5280
7
            return 0;
5281
7
        }
5282
5283
4.04k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5284
252
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5285
                // in old version, keep this key-value pair and it needs to be checked manually
5286
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5287
0
                return -1;
5288
0
            }
5289
252
            if (rowset.resource_id().empty()) [[unlikely]] {
5290
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5291
2
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5292
2
                          << hex(k) << " value=" << proto_to_json(rowset);
5293
2
                rowset_keys_without_data.emplace_back(k);
5294
2
                return 0;
5295
2
            }
5296
            // decode rowset_id
5297
250
            auto k1 = k;
5298
250
            k1.remove_prefix(1);
5299
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5300
250
            decode_key(&k1, &out);
5301
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5302
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5303
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5304
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5305
250
                      << " task_type=" << metrics_context.operation_type;
5306
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5307
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5308
0
                return -1;
5309
0
            }
5310
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5311
250
            metrics_context.total_recycled_num++;
5312
250
            segment_metrics_context_.total_recycled_data_size +=
5313
250
                    rowset.rowset_meta().total_disk_size();
5314
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5315
250
            return 0;
5316
250
        }
5317
5318
3.79k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5319
3.79k
        if (config::enable_mark_delete_rowset_before_recycle) {
5320
6
            if (need_mark_rowset_as_recycled(rowset)) {
5321
4
                rowset_keys_to_mark_recycled.emplace_back(k);
5322
4
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5323
4
                             "at next turn, instance_id="
5324
4
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5325
4
                          << " version=[" << rowset_meta->start_version() << '-'
5326
4
                          << rowset_meta->end_version() << "]";
5327
4
                return 0;
5328
4
            }
5329
6
        }
5330
5331
3.79k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5332
3.79k
            rowset_meta->end_version() != 1) {
5333
2
            if (make_deferred_abort_task(rowset).has_value()) {
5334
2
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5335
2
                             "instance_id="
5336
2
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5337
2
                          << " version=[" << rowset_meta->start_version() << '-'
5338
2
                          << rowset_meta->end_version() << "]";
5339
2
                rowset_keys_to_abort.emplace_back(k);
5340
2
            }
5341
2
        }
5342
5343
        // TODO(plat1ko): check rowset not referenced
5344
3.79k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5345
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5346
0
                LOG_INFO("recycle rowset that has empty resource id");
5347
0
            } else {
5348
                // other situations, keep this key-value pair and it needs to be checked manually
5349
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5350
0
                return -1;
5351
0
            }
5352
0
        }
5353
3.79k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5354
3.79k
                  << " tablet_id=" << rowset_meta->tablet_id()
5355
3.79k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5356
3.79k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5357
3.79k
                  << "] txn_id=" << rowset_meta->txn_id()
5358
3.79k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5359
3.79k
                  << " rowset_meta_size=" << v.size()
5360
3.79k
                  << " creation_time=" << rowset_meta->creation_time()
5361
3.79k
                  << " task_type=" << metrics_context.operation_type;
5362
3.79k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5363
            // unable to calculate file path, can only be deleted by rowset id prefix
5364
653
            num_prepare += 1;
5365
653
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5366
653
                                             rowset_meta->tablet_id(),
5367
653
                                             rowset_meta->rowset_id_v2()) != 0) {
5368
0
                return -1;
5369
0
            }
5370
3.13k
        } else {
5371
3.13k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5372
3.13k
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
5373
3.13k
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
5374
3.13k
            } else {
5375
3
                ++num_empty_rowset;
5376
3
                rowset_keys_without_data.emplace_back(k);
5377
3
            }
5378
3.13k
        }
5379
3.79k
        return 0;
5380
3.79k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5255
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5256
7
        ++num_scanned;
5257
7
        total_rowset_key_size += k.size();
5258
7
        total_rowset_value_size += v.size();
5259
7
        RecycleRowsetPB rowset;
5260
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5261
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5262
0
            return -1;
5263
0
        }
5264
5265
7
        int64_t current_time = ::time(nullptr);
5266
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5267
5268
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5269
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5270
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5271
7
        if (current_time < expiration) { // not expired
5272
0
            return 0;
5273
0
        }
5274
7
        ++num_expired;
5275
7
        expired_rowset_size += v.size();
5276
5277
7
        int64_t tablet_id =
5278
7
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5279
7
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5280
0
            return 0;
5281
0
        }
5282
5283
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5284
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5285
                // in old version, keep this key-value pair and it needs to be checked manually
5286
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5287
0
                return -1;
5288
0
            }
5289
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5290
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5291
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5292
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5293
0
                rowset_keys_without_data.emplace_back(k);
5294
0
                return 0;
5295
0
            }
5296
            // decode rowset_id
5297
0
            auto k1 = k;
5298
0
            k1.remove_prefix(1);
5299
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5300
0
            decode_key(&k1, &out);
5301
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5302
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5303
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5304
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5305
0
                      << " task_type=" << metrics_context.operation_type;
5306
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5307
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5308
0
                return -1;
5309
0
            }
5310
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5311
0
            metrics_context.total_recycled_num++;
5312
0
            segment_metrics_context_.total_recycled_data_size +=
5313
0
                    rowset.rowset_meta().total_disk_size();
5314
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5315
0
            return 0;
5316
0
        }
5317
5318
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
5319
7
        if (config::enable_mark_delete_rowset_before_recycle) {
5320
6
            if (need_mark_rowset_as_recycled(rowset)) {
5321
4
                rowset_keys_to_mark_recycled.emplace_back(k);
5322
4
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5323
4
                             "at next turn, instance_id="
5324
4
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5325
4
                          << " version=[" << rowset_meta->start_version() << '-'
5326
4
                          << rowset_meta->end_version() << "]";
5327
4
                return 0;
5328
4
            }
5329
6
        }
5330
5331
3
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5332
3
            rowset_meta->end_version() != 1) {
5333
2
            if (make_deferred_abort_task(rowset).has_value()) {
5334
2
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5335
2
                             "instance_id="
5336
2
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5337
2
                          << " version=[" << rowset_meta->start_version() << '-'
5338
2
                          << rowset_meta->end_version() << "]";
5339
2
                rowset_keys_to_abort.emplace_back(k);
5340
2
            }
5341
2
        }
5342
5343
        // TODO(plat1ko): check rowset not referenced
5344
3
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5345
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5346
0
                LOG_INFO("recycle rowset that has empty resource id");
5347
0
            } else {
5348
                // other situations, keep this key-value pair and it needs to be checked manually
5349
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5350
0
                return -1;
5351
0
            }
5352
0
        }
5353
3
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5354
3
                  << " tablet_id=" << rowset_meta->tablet_id()
5355
3
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5356
3
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5357
3
                  << "] txn_id=" << rowset_meta->txn_id()
5358
3
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5359
3
                  << " rowset_meta_size=" << v.size()
5360
3
                  << " creation_time=" << rowset_meta->creation_time()
5361
3
                  << " task_type=" << metrics_context.operation_type;
5362
3
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5363
            // unable to calculate file path, can only be deleted by rowset id prefix
5364
3
            num_prepare += 1;
5365
3
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5366
3
                                             rowset_meta->tablet_id(),
5367
3
                                             rowset_meta->rowset_id_v2()) != 0) {
5368
0
                return -1;
5369
0
            }
5370
3
        } else {
5371
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5372
0
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
5373
0
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
5374
0
            } else {
5375
0
                ++num_empty_rowset;
5376
0
                rowset_keys_without_data.emplace_back(k);
5377
0
            }
5378
0
        }
5379
3
        return 0;
5380
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5255
4.04k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5256
4.04k
        ++num_scanned;
5257
4.04k
        total_rowset_key_size += k.size();
5258
4.04k
        total_rowset_value_size += v.size();
5259
4.04k
        RecycleRowsetPB rowset;
5260
4.04k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5261
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5262
0
            return -1;
5263
0
        }
5264
5265
4.04k
        int64_t current_time = ::time(nullptr);
5266
4.04k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5267
5268
4.04k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5269
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5270
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5271
4.04k
        if (current_time < expiration) { // not expired
5272
0
            return 0;
5273
0
        }
5274
4.04k
        ++num_expired;
5275
4.04k
        expired_rowset_size += v.size();
5276
5277
4.04k
        int64_t tablet_id =
5278
4.04k
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5279
4.04k
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5280
7
            return 0;
5281
7
        }
5282
5283
4.04k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5284
252
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5285
                // in old version, keep this key-value pair and it needs to be checked manually
5286
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5287
0
                return -1;
5288
0
            }
5289
252
            if (rowset.resource_id().empty()) [[unlikely]] {
5290
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5291
2
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5292
2
                          << hex(k) << " value=" << proto_to_json(rowset);
5293
2
                rowset_keys_without_data.emplace_back(k);
5294
2
                return 0;
5295
2
            }
5296
            // decode rowset_id
5297
250
            auto k1 = k;
5298
250
            k1.remove_prefix(1);
5299
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5300
250
            decode_key(&k1, &out);
5301
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5302
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5303
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5304
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5305
250
                      << " task_type=" << metrics_context.operation_type;
5306
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5307
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5308
0
                return -1;
5309
0
            }
5310
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5311
250
            metrics_context.total_recycled_num++;
5312
250
            segment_metrics_context_.total_recycled_data_size +=
5313
250
                    rowset.rowset_meta().total_disk_size();
5314
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5315
250
            return 0;
5316
250
        }
5317
5318
3.78k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5319
3.78k
        if (config::enable_mark_delete_rowset_before_recycle) {
5320
0
            if (need_mark_rowset_as_recycled(rowset)) {
5321
0
                rowset_keys_to_mark_recycled.emplace_back(k);
5322
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5323
0
                             "at next turn, instance_id="
5324
0
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5325
0
                          << " version=[" << rowset_meta->start_version() << '-'
5326
0
                          << rowset_meta->end_version() << "]";
5327
0
                return 0;
5328
0
            }
5329
0
        }
5330
5331
3.78k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5332
3.78k
            rowset_meta->end_version() != 1) {
5333
0
            if (make_deferred_abort_task(rowset).has_value()) {
5334
0
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5335
0
                             "instance_id="
5336
0
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5337
0
                          << " version=[" << rowset_meta->start_version() << '-'
5338
0
                          << rowset_meta->end_version() << "]";
5339
0
                rowset_keys_to_abort.emplace_back(k);
5340
0
            }
5341
0
        }
5342
5343
        // TODO(plat1ko): check rowset not referenced
5344
3.78k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5345
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5346
0
                LOG_INFO("recycle rowset that has empty resource id");
5347
0
            } else {
5348
                // other situations, keep this key-value pair and it needs to be checked manually
5349
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5350
0
                return -1;
5351
0
            }
5352
0
        }
5353
3.78k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5354
3.78k
                  << " tablet_id=" << rowset_meta->tablet_id()
5355
3.78k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5356
3.78k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5357
3.78k
                  << "] txn_id=" << rowset_meta->txn_id()
5358
3.78k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5359
3.78k
                  << " rowset_meta_size=" << v.size()
5360
3.78k
                  << " creation_time=" << rowset_meta->creation_time()
5361
3.78k
                  << " task_type=" << metrics_context.operation_type;
5362
3.78k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5363
            // unable to calculate file path, can only be deleted by rowset id prefix
5364
650
            num_prepare += 1;
5365
650
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5366
650
                                             rowset_meta->tablet_id(),
5367
650
                                             rowset_meta->rowset_id_v2()) != 0) {
5368
0
                return -1;
5369
0
            }
5370
3.13k
        } else {
5371
3.13k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5372
3.13k
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
5373
3.13k
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
5374
3.13k
            } else {
5375
3
                ++num_empty_rowset;
5376
3
                rowset_keys_without_data.emplace_back(k);
5377
3
            }
5378
3.13k
        }
5379
3.78k
        return 0;
5380
3.78k
    };
5381
5382
63
    auto submit_delete_rowset_data_job = [&](std::vector<std::string> rowset_keys,
5383
63
                                             std::map<std::string, RowsetMetaCloudPB> rowsets) {
5384
22
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys),
5385
22
                             rowsets_to_delete = std::move(rowsets)]() {
5386
22
            if (!rowsets_to_delete.empty() &&
5387
22
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5388
17
                                   metrics_context) != 0) {
5389
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5390
0
                return;
5391
0
            }
5392
3.13k
            for (const auto& [_, rs] : rowsets_to_delete) {
5393
3.13k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5394
0
                    return;
5395
0
                }
5396
3.13k
            }
5397
22
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5398
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5399
0
                return;
5400
0
            }
5401
5402
22
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5403
22
        });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_6clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESt3mapIS9_NS_17RowsetMetaCloudPBESt4lessIS9_ESaISt4pairIKS9_SD_EEEENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_6clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESt3mapIS9_NS_17RowsetMetaCloudPBESt4lessIS9_ESaISt4pairIKS9_SD_EEEENKUlvE_clEv
Line
Count
Source
5385
22
                             rowsets_to_delete = std::move(rowsets)]() {
5386
22
            if (!rowsets_to_delete.empty() &&
5387
22
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5388
17
                                   metrics_context) != 0) {
5389
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5390
0
                return;
5391
0
            }
5392
3.13k
            for (const auto& [_, rs] : rowsets_to_delete) {
5393
3.13k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5394
0
                    return;
5395
0
                }
5396
3.13k
            }
5397
22
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5398
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5399
0
                return;
5400
0
            }
5401
5402
22
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5403
22
        });
5404
22
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_6clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESt3mapIS9_NS_17RowsetMetaCloudPBESt4lessIS9_ESaISt4pairIKS9_SD_EEE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_6clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESt3mapIS9_NS_17RowsetMetaCloudPBESt4lessIS9_ESaISt4pairIKS9_SD_EEE
Line
Count
Source
5383
22
                                             std::map<std::string, RowsetMetaCloudPB> rowsets) {
5384
22
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys),
5385
22
                             rowsets_to_delete = std::move(rowsets)]() {
5386
22
            if (!rowsets_to_delete.empty() &&
5387
22
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5388
22
                                   metrics_context) != 0) {
5389
22
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5390
22
                return;
5391
22
            }
5392
22
            for (const auto& [_, rs] : rowsets_to_delete) {
5393
22
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5394
22
                    return;
5395
22
                }
5396
22
            }
5397
22
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5398
22
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5399
22
                return;
5400
22
            }
5401
5402
22
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5403
22
        });
5404
22
    };
5405
5406
63
    auto submit_mark_abort_rowset_job = [&](std::vector<std::string> rowset_keys_to_mark,
5407
105
                                            std::vector<std::string> rowset_keys_to_abort) {
5408
105
        if (rowset_keys_to_mark.empty() && rowset_keys_to_abort.empty()) {
5409
99
            return;
5410
99
        }
5411
6
        mark_abort_worker_pool->submit([&, rowset_keys_to_mark = std::move(rowset_keys_to_mark),
5412
6
                                        rowset_keys_to_abort =
5413
6
                                                std::move(rowset_keys_to_abort)]() mutable {
5414
6
            auto start = steady_clock::now();
5415
6
            DORIS_CLOUD_DEFER {
5416
6
                auto cost = duration_cast<milliseconds>(steady_clock::now() - start).count();
5417
6
                LOG(INFO) << "finish mark and abort rowset job, instance_id=" << instance_id_ << ' '
5418
6
                          << "cost_ms=" << cost << ' '
5419
6
                          << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size() << ' '
5420
6
                          << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5421
6
            };
recycler.cpp:_ZZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_ENUlvE_clEvENKUlvE_clEv
Line
Count
Source
5415
6
            DORIS_CLOUD_DEFER {
5416
6
                auto cost = duration_cast<milliseconds>(steady_clock::now() - start).count();
5417
6
                LOG(INFO) << "finish mark and abort rowset job, instance_id=" << instance_id_ << ' '
5418
6
                          << "cost_ms=" << cost << ' '
5419
6
                          << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size() << ' '
5420
6
                          << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5421
6
            };
Unexecuted instantiation: recycler_test.cpp:_ZZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_ENUlvE_clEvENKUlvE_clEv
5422
6
            if (!rowset_keys_to_mark.empty() &&
5423
6
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5424
4
                                                                rowset_keys_to_mark) != 0) {
5425
0
                LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id="
5426
0
                             << instance_id_ << ' '
5427
0
                             << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size();
5428
0
                return;
5429
0
            }
5430
6
            if (!rowset_keys_to_abort.empty() &&
5431
6
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort, true) !=
5432
2
                        0) {
5433
0
                LOG(WARNING) << "failed to batch abort txn or job for related rowset, "
5434
0
                                "instance_id="
5435
0
                             << instance_id_ << ' '
5436
0
                             << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5437
0
                return;
5438
0
            }
5439
6
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_ENUlvE_clEv
Line
Count
Source
5413
6
                                                std::move(rowset_keys_to_abort)]() mutable {
5414
6
            auto start = steady_clock::now();
5415
6
            DORIS_CLOUD_DEFER {
5416
6
                auto cost = duration_cast<milliseconds>(steady_clock::now() - start).count();
5417
6
                LOG(INFO) << "finish mark and abort rowset job, instance_id=" << instance_id_ << ' '
5418
6
                          << "cost_ms=" << cost << ' '
5419
6
                          << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size() << ' '
5420
6
                          << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5421
6
            };
5422
6
            if (!rowset_keys_to_mark.empty() &&
5423
6
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5424
4
                                                                rowset_keys_to_mark) != 0) {
5425
0
                LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id="
5426
0
                             << instance_id_ << ' '
5427
0
                             << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size();
5428
0
                return;
5429
0
            }
5430
6
            if (!rowset_keys_to_abort.empty() &&
5431
6
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort, true) !=
5432
2
                        0) {
5433
0
                LOG(WARNING) << "failed to batch abort txn or job for related rowset, "
5434
0
                                "instance_id="
5435
0
                             << instance_id_ << ' '
5436
0
                             << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5437
0
                return;
5438
0
            }
5439
6
        });
Unexecuted instantiation: recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_ENUlvE_clEv
5440
6
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_
Line
Count
Source
5407
14
                                            std::vector<std::string> rowset_keys_to_abort) {
5408
14
        if (rowset_keys_to_mark.empty() && rowset_keys_to_abort.empty()) {
5409
8
            return;
5410
8
        }
5411
6
        mark_abort_worker_pool->submit([&, rowset_keys_to_mark = std::move(rowset_keys_to_mark),
5412
6
                                        rowset_keys_to_abort =
5413
6
                                                std::move(rowset_keys_to_abort)]() mutable {
5414
6
            auto start = steady_clock::now();
5415
6
            DORIS_CLOUD_DEFER {
5416
6
                auto cost = duration_cast<milliseconds>(steady_clock::now() - start).count();
5417
6
                LOG(INFO) << "finish mark and abort rowset job, instance_id=" << instance_id_ << ' '
5418
6
                          << "cost_ms=" << cost << ' '
5419
6
                          << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size() << ' '
5420
6
                          << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5421
6
            };
5422
6
            if (!rowset_keys_to_mark.empty() &&
5423
6
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5424
6
                                                                rowset_keys_to_mark) != 0) {
5425
6
                LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id="
5426
6
                             << instance_id_ << ' '
5427
6
                             << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size();
5428
6
                return;
5429
6
            }
5430
6
            if (!rowset_keys_to_abort.empty() &&
5431
6
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort, true) !=
5432
6
                        0) {
5433
6
                LOG(WARNING) << "failed to batch abort txn or job for related rowset, "
5434
6
                                "instance_id="
5435
6
                             << instance_id_ << ' '
5436
6
                             << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5437
6
                return;
5438
6
            }
5439
6
        });
5440
6
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_
Line
Count
Source
5407
91
                                            std::vector<std::string> rowset_keys_to_abort) {
5408
91
        if (rowset_keys_to_mark.empty() && rowset_keys_to_abort.empty()) {
5409
91
            return;
5410
91
        }
5411
0
        mark_abort_worker_pool->submit([&, rowset_keys_to_mark = std::move(rowset_keys_to_mark),
5412
0
                                        rowset_keys_to_abort =
5413
0
                                                std::move(rowset_keys_to_abort)]() mutable {
5414
0
            auto start = steady_clock::now();
5415
0
            DORIS_CLOUD_DEFER {
5416
0
                auto cost = duration_cast<milliseconds>(steady_clock::now() - start).count();
5417
0
                LOG(INFO) << "finish mark and abort rowset job, instance_id=" << instance_id_ << ' '
5418
0
                          << "cost_ms=" << cost << ' '
5419
0
                          << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size() << ' '
5420
0
                          << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5421
0
            };
5422
0
            if (!rowset_keys_to_mark.empty() &&
5423
0
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5424
0
                                                                rowset_keys_to_mark) != 0) {
5425
0
                LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id="
5426
0
                             << instance_id_ << ' '
5427
0
                             << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size();
5428
0
                return;
5429
0
            }
5430
0
            if (!rowset_keys_to_abort.empty() &&
5431
0
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort, true) !=
5432
0
                        0) {
5433
0
                LOG(WARNING) << "failed to batch abort txn or job for related rowset, "
5434
0
                                "instance_id="
5435
0
                             << instance_id_ << ' '
5436
0
                             << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5437
0
                return;
5438
0
            }
5439
0
        });
5440
0
    };
5441
5442
63
    bool scan_finished = false;
5443
105
    auto loop_done = [&]() -> int {
5444
105
        std::vector<std::string> mark_keys_to_process;
5445
105
        std::vector<std::string> abort_keys_to_process;
5446
105
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5447
105
        abort_keys_to_process.swap(rowset_keys_to_abort);
5448
105
        submit_mark_abort_rowset_job(std::move(mark_keys_to_process),
5449
105
                                     std::move(abort_keys_to_process));
5450
105
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
5451
42
            return 0;
5452
42
        }
5453
5454
63
        DORIS_CLOUD_DEFER {
5455
            // if return -1 in loop done, rowset info in memory is not cleared,
5456
            // it can lead to memory accumulation
5457
63
            rowset_keys_without_data.clear();
5458
63
            rowsets.clear();
5459
63
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
5454
7
        DORIS_CLOUD_DEFER {
5455
            // if return -1 in loop done, rowset info in memory is not cleared,
5456
            // it can lead to memory accumulation
5457
7
            rowset_keys_without_data.clear();
5458
7
            rowsets.clear();
5459
7
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
5454
56
        DORIS_CLOUD_DEFER {
5455
            // if return -1 in loop done, rowset info in memory is not cleared,
5456
            // it can lead to memory accumulation
5457
56
            rowset_keys_without_data.clear();
5458
56
            rowsets.clear();
5459
56
        };
5460
63
        std::random_device rd;
5461
63
        std::mt19937 g(rd());
5462
63
        std::ranges::shuffle(rowsets, g);
5463
5464
63
        std::vector<std::string> rowset_keys_to_delete;
5465
63
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
5466
        // rowset_id -> rowset_meta
5467
        // store rowset id and meta for statistics rs size when delete
5468
63
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5469
5470
63
        size_t rowsets_per_batch_size = 0;
5471
3.13k
        for (auto& rowset : rowsets) {
5472
3.13k
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
5473
3.13k
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
5474
3.13k
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
5475
3.12k
                continue;
5476
3.12k
            }
5477
5478
8
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5479
8
                                          std::move(rowsets_to_delete));
5480
8
            rowsets_per_batch_size = 0;
5481
8
            rowset_keys_to_delete.clear();
5482
8
            rowsets_to_delete.clear();
5483
8
        }
5484
5485
63
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
5486
9
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5487
9
                                          std::move(rowsets_to_delete));
5488
9
        }
5489
5490
68
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
5491
5
            auto begin = rowset_keys_without_data.begin() + i;
5492
5
            auto end = rowset_keys_without_data.begin() +
5493
5
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
5494
5
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
5495
5
                                                           std::make_move_iterator(end));
5496
5
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
5497
5
        }
5498
5499
63
        return 0;
5500
105
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5443
14
    auto loop_done = [&]() -> int {
5444
14
        std::vector<std::string> mark_keys_to_process;
5445
14
        std::vector<std::string> abort_keys_to_process;
5446
14
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5447
14
        abort_keys_to_process.swap(rowset_keys_to_abort);
5448
14
        submit_mark_abort_rowset_job(std::move(mark_keys_to_process),
5449
14
                                     std::move(abort_keys_to_process));
5450
14
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
5451
7
            return 0;
5452
7
        }
5453
5454
7
        DORIS_CLOUD_DEFER {
5455
            // if return -1 in loop done, rowset info in memory is not cleared,
5456
            // it can lead to memory accumulation
5457
7
            rowset_keys_without_data.clear();
5458
7
            rowsets.clear();
5459
7
        };
5460
7
        std::random_device rd;
5461
7
        std::mt19937 g(rd());
5462
7
        std::ranges::shuffle(rowsets, g);
5463
5464
7
        std::vector<std::string> rowset_keys_to_delete;
5465
7
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
5466
        // rowset_id -> rowset_meta
5467
        // store rowset id and meta for statistics rs size when delete
5468
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5469
5470
7
        size_t rowsets_per_batch_size = 0;
5471
7
        for (auto& rowset : rowsets) {
5472
0
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
5473
0
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
5474
0
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
5475
0
                continue;
5476
0
            }
5477
5478
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5479
0
                                          std::move(rowsets_to_delete));
5480
0
            rowsets_per_batch_size = 0;
5481
0
            rowset_keys_to_delete.clear();
5482
0
            rowsets_to_delete.clear();
5483
0
        }
5484
5485
7
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
5486
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5487
0
                                          std::move(rowsets_to_delete));
5488
0
        }
5489
5490
7
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
5491
0
            auto begin = rowset_keys_without_data.begin() + i;
5492
0
            auto end = rowset_keys_without_data.begin() +
5493
0
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
5494
0
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
5495
0
                                                           std::make_move_iterator(end));
5496
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
5497
0
        }
5498
5499
7
        return 0;
5500
14
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5443
91
    auto loop_done = [&]() -> int {
5444
91
        std::vector<std::string> mark_keys_to_process;
5445
91
        std::vector<std::string> abort_keys_to_process;
5446
91
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5447
91
        abort_keys_to_process.swap(rowset_keys_to_abort);
5448
91
        submit_mark_abort_rowset_job(std::move(mark_keys_to_process),
5449
91
                                     std::move(abort_keys_to_process));
5450
91
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
5451
35
            return 0;
5452
35
        }
5453
5454
56
        DORIS_CLOUD_DEFER {
5455
            // if return -1 in loop done, rowset info in memory is not cleared,
5456
            // it can lead to memory accumulation
5457
56
            rowset_keys_without_data.clear();
5458
56
            rowsets.clear();
5459
56
        };
5460
56
        std::random_device rd;
5461
56
        std::mt19937 g(rd());
5462
56
        std::ranges::shuffle(rowsets, g);
5463
5464
56
        std::vector<std::string> rowset_keys_to_delete;
5465
56
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
5466
        // rowset_id -> rowset_meta
5467
        // store rowset id and meta for statistics rs size when delete
5468
56
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5469
5470
56
        size_t rowsets_per_batch_size = 0;
5471
3.13k
        for (auto& rowset : rowsets) {
5472
3.13k
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
5473
3.13k
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
5474
3.13k
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
5475
3.12k
                continue;
5476
3.12k
            }
5477
5478
8
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5479
8
                                          std::move(rowsets_to_delete));
5480
8
            rowsets_per_batch_size = 0;
5481
8
            rowset_keys_to_delete.clear();
5482
8
            rowsets_to_delete.clear();
5483
8
        }
5484
5485
56
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
5486
9
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5487
9
                                          std::move(rowsets_to_delete));
5488
9
        }
5489
5490
61
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
5491
5
            auto begin = rowset_keys_without_data.begin() + i;
5492
5
            auto end = rowset_keys_without_data.begin() +
5493
5
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
5494
5
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
5495
5
                                                           std::make_move_iterator(end));
5496
5
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
5497
5
        }
5498
5499
56
        return 0;
5500
91
    };
5501
5502
63
    if (config::enable_recycler_stats_metrics) {
5503
0
        scan_and_statistics_rowsets();
5504
0
    }
5505
    // recycle_func and loop_done for scan and recycle
5506
63
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv), loop_done,
5507
63
                               std::move(next_scan_begin_getter));
5508
63
    scan_finished = true;
5509
    // if the size of rowsets is always less than delete_rowset_batch_size
5510
    // it need to submit the task directly
5511
    // else if the size of rowsets is greater than delete_rowset_batch_size,
5512
    // but there are residual, whether due to failed or unsuccessful cleanup, this behavior is idempotent
5513
63
    if (loop_done() != 0) {
5514
0
        ret = -1;
5515
0
    }
5516
5517
63
    mark_abort_worker_pool->stop();
5518
63
    worker_pool->stop();
5519
5520
63
    if (!async_recycled_rowset_keys.empty()) {
5521
7
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5522
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5523
0
            return -1;
5524
7
        } else {
5525
7
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5526
7
        }
5527
7
    }
5528
5529
    // Report final metrics after all concurrent tasks completed
5530
63
    segment_metrics_context_.report();
5531
63
    metrics_context.report();
5532
5533
63
    return ret;
5534
63
}
5535
5536
int InstanceRecycler::next_recycle_rowset_tablet_key(const std::string& instance_id,
5537
1
                                                     int64_t tablet_id, std::string* next_key) {
5538
1
    DCHECK(next_key != nullptr);
5539
1
    if (tablet_id == std::numeric_limits<int64_t>::max()) {
5540
0
        return -1;
5541
0
    }
5542
1
    *next_key = recycle_rowset_key({instance_id, tablet_id + 1, ""});
5543
1
    return 0;
5544
1
}
5545
5546
13
int InstanceRecycler::recycle_restore_jobs() {
5547
13
    const std::string task_name = "recycle_restore_jobs";
5548
13
    int64_t num_scanned = 0;
5549
13
    int64_t num_expired = 0;
5550
13
    int64_t num_recycled = 0;
5551
13
    int64_t num_aborted = 0;
5552
5553
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5554
5555
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
5556
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
5557
13
    std::string restore_job_key0;
5558
13
    std::string restore_job_key1;
5559
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
5560
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
5561
5562
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
5563
5564
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5565
13
    register_recycle_task(task_name, start_time);
5566
5567
13
    DORIS_CLOUD_DEFER {
5568
13
        unregister_recycle_task(task_name);
5569
13
        int64_t cost =
5570
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5571
13
        metrics_context.finish_report();
5572
5573
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5574
13
                .tag("instance_id", instance_id_)
5575
13
                .tag("num_scanned", num_scanned)
5576
13
                .tag("num_expired", num_expired)
5577
13
                .tag("num_recycled", num_recycled)
5578
13
                .tag("num_aborted", num_aborted);
5579
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
5567
13
    DORIS_CLOUD_DEFER {
5568
13
        unregister_recycle_task(task_name);
5569
13
        int64_t cost =
5570
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5571
13
        metrics_context.finish_report();
5572
5573
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5574
13
                .tag("instance_id", instance_id_)
5575
13
                .tag("num_scanned", num_scanned)
5576
13
                .tag("num_expired", num_expired)
5577
13
                .tag("num_recycled", num_recycled)
5578
13
                .tag("num_aborted", num_aborted);
5579
13
    };
5580
5581
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5582
5583
13
    std::vector<std::string_view> restore_job_keys;
5584
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5585
41
        ++num_scanned;
5586
41
        RestoreJobCloudPB restore_job_pb;
5587
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5588
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5589
0
            return -1;
5590
0
        }
5591
41
        int64_t expiration =
5592
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5593
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5594
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5595
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5596
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5597
0
                   << " state=" << restore_job_pb.state();
5598
41
        int64_t current_time = ::time(nullptr);
5599
41
        if (current_time < expiration) { // not expired
5600
0
            return 0;
5601
0
        }
5602
41
        ++num_expired;
5603
5604
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5605
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5606
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5607
5608
41
        std::unique_ptr<Transaction> txn;
5609
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5610
41
        if (err != TxnErrorCode::TXN_OK) {
5611
0
            LOG_WARNING("failed to recycle restore job")
5612
0
                    .tag("err", err)
5613
0
                    .tag("tablet id", tablet_id)
5614
0
                    .tag("instance_id", instance_id_)
5615
0
                    .tag("reason", "failed to create txn");
5616
0
            return -1;
5617
0
        }
5618
5619
41
        std::string val;
5620
41
        err = txn->get(k, &val);
5621
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5622
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5623
0
            return 0;
5624
0
        }
5625
41
        if (err != TxnErrorCode::TXN_OK) {
5626
0
            LOG_WARNING("failed to get kv");
5627
0
            return -1;
5628
0
        }
5629
41
        restore_job_pb.Clear();
5630
41
        if (!restore_job_pb.ParseFromString(val)) {
5631
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5632
0
            return -1;
5633
0
        }
5634
5635
        // PREPARED or COMMITTED, change state to DROPPED and return
5636
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5637
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5638
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5639
0
            restore_job_pb.set_need_recycle_data(true);
5640
0
            txn->put(k, restore_job_pb.SerializeAsString());
5641
0
            err = txn->commit();
5642
0
            if (err != TxnErrorCode::TXN_OK) {
5643
0
                LOG_WARNING("failed to commit txn: {}", err);
5644
0
                return -1;
5645
0
            }
5646
0
            num_aborted++;
5647
0
            return 0;
5648
0
        }
5649
5650
        // Change state to RECYCLING
5651
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5652
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5653
21
            txn->put(k, restore_job_pb.SerializeAsString());
5654
21
            err = txn->commit();
5655
21
            if (err != TxnErrorCode::TXN_OK) {
5656
0
                LOG_WARNING("failed to commit txn: {}", err);
5657
0
                return -1;
5658
0
            }
5659
21
            return 0;
5660
21
        }
5661
5662
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5663
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5664
5665
        // Recycle all data associated with the restore job.
5666
        // This includes rowsets, segments, and related resources.
5667
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5668
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5669
0
            LOG_WARNING("failed to recycle tablet")
5670
0
                    .tag("tablet_id", tablet_id)
5671
0
                    .tag("instance_id", instance_id_);
5672
0
            return -1;
5673
0
        }
5674
5675
        // delete all restore job rowset kv
5676
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5677
5678
20
        err = txn->commit();
5679
20
        if (err != TxnErrorCode::TXN_OK) {
5680
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5681
0
                    .tag("err", err)
5682
0
                    .tag("tablet id", tablet_id)
5683
0
                    .tag("instance_id", instance_id_)
5684
0
                    .tag("reason", "failed to commit txn");
5685
0
            return -1;
5686
0
        }
5687
5688
20
        metrics_context.total_recycled_num = ++num_recycled;
5689
20
        metrics_context.report();
5690
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5691
20
        restore_job_keys.push_back(k);
5692
5693
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5694
20
                  << " tablet_id=" << tablet_id;
5695
20
        return 0;
5696
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
5584
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5585
41
        ++num_scanned;
5586
41
        RestoreJobCloudPB restore_job_pb;
5587
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5588
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5589
0
            return -1;
5590
0
        }
5591
41
        int64_t expiration =
5592
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5593
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5594
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5595
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5596
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5597
0
                   << " state=" << restore_job_pb.state();
5598
41
        int64_t current_time = ::time(nullptr);
5599
41
        if (current_time < expiration) { // not expired
5600
0
            return 0;
5601
0
        }
5602
41
        ++num_expired;
5603
5604
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5605
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5606
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5607
5608
41
        std::unique_ptr<Transaction> txn;
5609
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5610
41
        if (err != TxnErrorCode::TXN_OK) {
5611
0
            LOG_WARNING("failed to recycle restore job")
5612
0
                    .tag("err", err)
5613
0
                    .tag("tablet id", tablet_id)
5614
0
                    .tag("instance_id", instance_id_)
5615
0
                    .tag("reason", "failed to create txn");
5616
0
            return -1;
5617
0
        }
5618
5619
41
        std::string val;
5620
41
        err = txn->get(k, &val);
5621
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5622
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5623
0
            return 0;
5624
0
        }
5625
41
        if (err != TxnErrorCode::TXN_OK) {
5626
0
            LOG_WARNING("failed to get kv");
5627
0
            return -1;
5628
0
        }
5629
41
        restore_job_pb.Clear();
5630
41
        if (!restore_job_pb.ParseFromString(val)) {
5631
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5632
0
            return -1;
5633
0
        }
5634
5635
        // PREPARED or COMMITTED, change state to DROPPED and return
5636
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5637
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5638
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5639
0
            restore_job_pb.set_need_recycle_data(true);
5640
0
            txn->put(k, restore_job_pb.SerializeAsString());
5641
0
            err = txn->commit();
5642
0
            if (err != TxnErrorCode::TXN_OK) {
5643
0
                LOG_WARNING("failed to commit txn: {}", err);
5644
0
                return -1;
5645
0
            }
5646
0
            num_aborted++;
5647
0
            return 0;
5648
0
        }
5649
5650
        // Change state to RECYCLING
5651
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5652
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5653
21
            txn->put(k, restore_job_pb.SerializeAsString());
5654
21
            err = txn->commit();
5655
21
            if (err != TxnErrorCode::TXN_OK) {
5656
0
                LOG_WARNING("failed to commit txn: {}", err);
5657
0
                return -1;
5658
0
            }
5659
21
            return 0;
5660
21
        }
5661
5662
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5663
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5664
5665
        // Recycle all data associated with the restore job.
5666
        // This includes rowsets, segments, and related resources.
5667
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5668
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5669
0
            LOG_WARNING("failed to recycle tablet")
5670
0
                    .tag("tablet_id", tablet_id)
5671
0
                    .tag("instance_id", instance_id_);
5672
0
            return -1;
5673
0
        }
5674
5675
        // delete all restore job rowset kv
5676
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5677
5678
20
        err = txn->commit();
5679
20
        if (err != TxnErrorCode::TXN_OK) {
5680
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5681
0
                    .tag("err", err)
5682
0
                    .tag("tablet id", tablet_id)
5683
0
                    .tag("instance_id", instance_id_)
5684
0
                    .tag("reason", "failed to commit txn");
5685
0
            return -1;
5686
0
        }
5687
5688
20
        metrics_context.total_recycled_num = ++num_recycled;
5689
20
        metrics_context.report();
5690
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5691
20
        restore_job_keys.push_back(k);
5692
5693
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5694
20
                  << " tablet_id=" << tablet_id;
5695
20
        return 0;
5696
20
    };
5697
5698
13
    auto loop_done = [&restore_job_keys, this]() -> int {
5699
3
        if (restore_job_keys.empty()) return 0;
5700
1
        DORIS_CLOUD_DEFER {
5701
1
            restore_job_keys.clear();
5702
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5700
1
        DORIS_CLOUD_DEFER {
5701
1
            restore_job_keys.clear();
5702
1
        };
5703
5704
1
        std::unique_ptr<Transaction> txn;
5705
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5706
1
        if (err != TxnErrorCode::TXN_OK) {
5707
0
            LOG_WARNING("failed to recycle restore job")
5708
0
                    .tag("err", err)
5709
0
                    .tag("instance_id", instance_id_)
5710
0
                    .tag("reason", "failed to create txn");
5711
0
            return -1;
5712
0
        }
5713
20
        for (auto& k : restore_job_keys) {
5714
20
            txn->remove(k);
5715
20
        }
5716
1
        err = txn->commit();
5717
1
        if (err != TxnErrorCode::TXN_OK) {
5718
0
            LOG_WARNING("failed to recycle restore job")
5719
0
                    .tag("err", err)
5720
0
                    .tag("instance_id", instance_id_)
5721
0
                    .tag("reason", "failed to commit txn");
5722
0
            return -1;
5723
0
        }
5724
1
        return 0;
5725
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
5698
3
    auto loop_done = [&restore_job_keys, this]() -> int {
5699
3
        if (restore_job_keys.empty()) return 0;
5700
1
        DORIS_CLOUD_DEFER {
5701
1
            restore_job_keys.clear();
5702
1
        };
5703
5704
1
        std::unique_ptr<Transaction> txn;
5705
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5706
1
        if (err != TxnErrorCode::TXN_OK) {
5707
0
            LOG_WARNING("failed to recycle restore job")
5708
0
                    .tag("err", err)
5709
0
                    .tag("instance_id", instance_id_)
5710
0
                    .tag("reason", "failed to create txn");
5711
0
            return -1;
5712
0
        }
5713
20
        for (auto& k : restore_job_keys) {
5714
20
            txn->remove(k);
5715
20
        }
5716
1
        err = txn->commit();
5717
1
        if (err != TxnErrorCode::TXN_OK) {
5718
0
            LOG_WARNING("failed to recycle restore job")
5719
0
                    .tag("err", err)
5720
0
                    .tag("instance_id", instance_id_)
5721
0
                    .tag("reason", "failed to commit txn");
5722
0
            return -1;
5723
0
        }
5724
1
        return 0;
5725
1
    };
5726
5727
13
    if (config::enable_recycler_stats_metrics) {
5728
0
        scan_and_statistics_restore_jobs();
5729
0
    }
5730
5731
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
5732
13
                            std::move(loop_done));
5733
13
}
5734
5735
10
int InstanceRecycler::recycle_versioned_rowsets() {
5736
10
    const std::string task_name = "recycle_rowsets";
5737
10
    int64_t num_scanned = 0;
5738
10
    int64_t num_expired = 0;
5739
10
    int64_t num_prepare = 0;
5740
10
    int64_t num_compacted = 0;
5741
10
    int64_t num_empty_rowset = 0;
5742
10
    size_t total_rowset_key_size = 0;
5743
10
    size_t total_rowset_value_size = 0;
5744
10
    size_t expired_rowset_size = 0;
5745
10
    std::atomic_long num_recycled = 0;
5746
10
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5747
5748
10
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5749
10
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5750
10
    std::string recyc_rs_key0;
5751
10
    std::string recyc_rs_key1;
5752
10
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5753
10
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5754
5755
10
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5756
5757
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5758
10
    register_recycle_task(task_name, start_time);
5759
5760
10
    DORIS_CLOUD_DEFER {
5761
10
        unregister_recycle_task(task_name);
5762
10
        int64_t cost =
5763
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5764
10
        metrics_context.finish_report();
5765
10
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5766
10
                .tag("instance_id", instance_id_)
5767
10
                .tag("num_scanned", num_scanned)
5768
10
                .tag("num_expired", num_expired)
5769
10
                .tag("num_recycled", num_recycled)
5770
10
                .tag("num_recycled.prepare", num_prepare)
5771
10
                .tag("num_recycled.compacted", num_compacted)
5772
10
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5773
10
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5774
10
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5775
10
                .tag("expired_rowset_meta_size", expired_rowset_size);
5776
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
5760
10
    DORIS_CLOUD_DEFER {
5761
10
        unregister_recycle_task(task_name);
5762
10
        int64_t cost =
5763
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5764
10
        metrics_context.finish_report();
5765
10
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5766
10
                .tag("instance_id", instance_id_)
5767
10
                .tag("num_scanned", num_scanned)
5768
10
                .tag("num_expired", num_expired)
5769
10
                .tag("num_recycled", num_recycled)
5770
10
                .tag("num_recycled.prepare", num_prepare)
5771
10
                .tag("num_recycled.compacted", num_compacted)
5772
10
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5773
10
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5774
10
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5775
10
                .tag("expired_rowset_meta_size", expired_rowset_size);
5776
10
    };
5777
5778
10
    std::vector<std::string> orphan_rowset_keys;
5779
5780
    // Store keys of rowset recycled by background workers
5781
10
    std::mutex async_recycled_rowset_keys_mutex;
5782
10
    std::vector<std::string> async_recycled_rowset_keys;
5783
10
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5784
10
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5785
10
    worker_pool->start();
5786
10
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5787
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5788
        // Try to delete rowset data in background thread
5789
400
        int ret = worker_pool->submit_with_timeout(
5790
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5791
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5792
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5793
400
                        return;
5794
400
                    }
5795
                    // The async recycled rowsets are staled format or has not been used,
5796
                    // so we don't need to check the rowset ref count key.
5797
0
                    std::vector<std::string> keys;
5798
0
                    {
5799
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5800
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5801
0
                        if (async_recycled_rowset_keys.size() > 100) {
5802
0
                            keys.swap(async_recycled_rowset_keys);
5803
0
                        }
5804
0
                    }
5805
0
                    if (keys.empty()) return;
5806
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5807
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5808
0
                                     << instance_id_;
5809
0
                    } else {
5810
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5811
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5812
0
                                           num_recycled, start_time);
5813
0
                    }
5814
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
5790
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5791
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5792
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5793
400
                        return;
5794
400
                    }
5795
                    // The async recycled rowsets are staled format or has not been used,
5796
                    // so we don't need to check the rowset ref count key.
5797
0
                    std::vector<std::string> keys;
5798
0
                    {
5799
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5800
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5801
0
                        if (async_recycled_rowset_keys.size() > 100) {
5802
0
                            keys.swap(async_recycled_rowset_keys);
5803
0
                        }
5804
0
                    }
5805
0
                    if (keys.empty()) return;
5806
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5807
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5808
0
                                     << instance_id_;
5809
0
                    } else {
5810
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5811
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5812
0
                                           num_recycled, start_time);
5813
0
                    }
5814
0
                },
5815
400
                0);
5816
400
        if (ret == 0) return 0;
5817
        // Submit task failed, delete rowset data in current thread
5818
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5819
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5820
0
            return -1;
5821
0
        }
5822
0
        orphan_rowset_keys.push_back(std::move(key));
5823
0
        return 0;
5824
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
5787
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5788
        // Try to delete rowset data in background thread
5789
400
        int ret = worker_pool->submit_with_timeout(
5790
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5791
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5792
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5793
400
                        return;
5794
400
                    }
5795
                    // The async recycled rowsets are staled format or has not been used,
5796
                    // so we don't need to check the rowset ref count key.
5797
400
                    std::vector<std::string> keys;
5798
400
                    {
5799
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5800
400
                        async_recycled_rowset_keys.push_back(std::move(key));
5801
400
                        if (async_recycled_rowset_keys.size() > 100) {
5802
400
                            keys.swap(async_recycled_rowset_keys);
5803
400
                        }
5804
400
                    }
5805
400
                    if (keys.empty()) return;
5806
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5807
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5808
400
                                     << instance_id_;
5809
400
                    } else {
5810
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5811
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5812
400
                                           num_recycled, start_time);
5813
400
                    }
5814
400
                },
5815
400
                0);
5816
400
        if (ret == 0) return 0;
5817
        // Submit task failed, delete rowset data in current thread
5818
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5819
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5820
0
            return -1;
5821
0
        }
5822
0
        orphan_rowset_keys.push_back(std::move(key));
5823
0
        return 0;
5824
0
    };
5825
5826
10
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5827
5828
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
5829
2.01k
        ++num_scanned;
5830
2.01k
        total_rowset_key_size += k.size();
5831
2.01k
        total_rowset_value_size += v.size();
5832
2.01k
        RecycleRowsetPB rowset;
5833
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5834
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5835
0
            return -1;
5836
0
        }
5837
5838
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5839
5840
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5841
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
5842
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5843
2.01k
        int64_t current_time = ::time(nullptr);
5844
2.01k
        if (current_time < final_expiration) { // not expired
5845
0
            return 0;
5846
0
        }
5847
2.01k
        ++num_expired;
5848
2.01k
        expired_rowset_size += v.size();
5849
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5850
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5851
                // in old version, keep this key-value pair and it needs to be checked manually
5852
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5853
0
                return -1;
5854
0
            }
5855
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5856
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5857
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5858
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5859
0
                orphan_rowset_keys.emplace_back(k);
5860
0
                return -1;
5861
0
            }
5862
            // decode rowset_id
5863
0
            auto k1 = k;
5864
0
            k1.remove_prefix(1);
5865
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5866
0
            decode_key(&k1, &out);
5867
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5868
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5869
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5870
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
5871
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5872
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5873
0
                return -1;
5874
0
            }
5875
0
            return 0;
5876
0
        }
5877
        // TODO(plat1ko): check rowset not referenced
5878
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
5879
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5880
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5881
0
                LOG_INFO("recycle rowset that has empty resource id");
5882
0
            } else {
5883
                // other situations, keep this key-value pair and it needs to be checked manually
5884
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5885
0
                return -1;
5886
0
            }
5887
0
        }
5888
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5889
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
5890
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5891
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5892
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
5893
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5894
2.01k
                  << " rowset_meta_size=" << v.size()
5895
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
5896
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5897
            // unable to calculate file path, can only be deleted by rowset id prefix
5898
400
            num_prepare += 1;
5899
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5900
400
                                             rowset_meta->tablet_id(),
5901
400
                                             rowset_meta->rowset_id_v2()) != 0) {
5902
0
                return -1;
5903
0
            }
5904
1.61k
        } else {
5905
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
5906
1.61k
            worker_pool->submit(
5907
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5908
                        // The load & compact rowset keys are recycled during recycling operation logs.
5909
1.61k
                        RowsetDeleteTask task;
5910
1.61k
                        task.rowset_meta = rowset_meta;
5911
1.61k
                        task.recycle_rowset_key = k;
5912
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
5913
1.60k
                            return;
5914
1.60k
                        }
5915
13
                        num_compacted += is_compacted;
5916
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5917
13
                        if (rowset_meta.num_segments() == 0) {
5918
0
                            ++num_empty_rowset;
5919
0
                        }
5920
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
5907
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5908
                        // The load & compact rowset keys are recycled during recycling operation logs.
5909
1.61k
                        RowsetDeleteTask task;
5910
1.61k
                        task.rowset_meta = rowset_meta;
5911
1.61k
                        task.recycle_rowset_key = k;
5912
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
5913
1.60k
                            return;
5914
1.60k
                        }
5915
13
                        num_compacted += is_compacted;
5916
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5917
13
                        if (rowset_meta.num_segments() == 0) {
5918
0
                            ++num_empty_rowset;
5919
0
                        }
5920
13
                    });
5921
1.61k
        }
5922
2.01k
        return 0;
5923
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
5828
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
5829
2.01k
        ++num_scanned;
5830
2.01k
        total_rowset_key_size += k.size();
5831
2.01k
        total_rowset_value_size += v.size();
5832
2.01k
        RecycleRowsetPB rowset;
5833
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5834
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5835
0
            return -1;
5836
0
        }
5837
5838
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5839
5840
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5841
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
5842
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5843
2.01k
        int64_t current_time = ::time(nullptr);
5844
2.01k
        if (current_time < final_expiration) { // not expired
5845
0
            return 0;
5846
0
        }
5847
2.01k
        ++num_expired;
5848
2.01k
        expired_rowset_size += v.size();
5849
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5850
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5851
                // in old version, keep this key-value pair and it needs to be checked manually
5852
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5853
0
                return -1;
5854
0
            }
5855
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5856
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5857
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5858
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5859
0
                orphan_rowset_keys.emplace_back(k);
5860
0
                return -1;
5861
0
            }
5862
            // decode rowset_id
5863
0
            auto k1 = k;
5864
0
            k1.remove_prefix(1);
5865
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5866
0
            decode_key(&k1, &out);
5867
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5868
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5869
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5870
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
5871
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5872
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5873
0
                return -1;
5874
0
            }
5875
0
            return 0;
5876
0
        }
5877
        // TODO(plat1ko): check rowset not referenced
5878
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
5879
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5880
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5881
0
                LOG_INFO("recycle rowset that has empty resource id");
5882
0
            } else {
5883
                // other situations, keep this key-value pair and it needs to be checked manually
5884
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5885
0
                return -1;
5886
0
            }
5887
0
        }
5888
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5889
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
5890
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5891
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5892
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
5893
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5894
2.01k
                  << " rowset_meta_size=" << v.size()
5895
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
5896
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5897
            // unable to calculate file path, can only be deleted by rowset id prefix
5898
400
            num_prepare += 1;
5899
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5900
400
                                             rowset_meta->tablet_id(),
5901
400
                                             rowset_meta->rowset_id_v2()) != 0) {
5902
0
                return -1;
5903
0
            }
5904
1.61k
        } else {
5905
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
5906
1.61k
            worker_pool->submit(
5907
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5908
                        // The load & compact rowset keys are recycled during recycling operation logs.
5909
1.61k
                        RowsetDeleteTask task;
5910
1.61k
                        task.rowset_meta = rowset_meta;
5911
1.61k
                        task.recycle_rowset_key = k;
5912
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
5913
1.61k
                            return;
5914
1.61k
                        }
5915
1.61k
                        num_compacted += is_compacted;
5916
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5917
1.61k
                        if (rowset_meta.num_segments() == 0) {
5918
1.61k
                            ++num_empty_rowset;
5919
1.61k
                        }
5920
1.61k
                    });
5921
1.61k
        }
5922
2.01k
        return 0;
5923
2.01k
    };
5924
5925
10
    if (config::enable_recycler_stats_metrics) {
5926
0
        scan_and_statistics_rowsets();
5927
0
    }
5928
5929
10
    auto loop_done = [&]() -> int {
5930
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
5931
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5932
0
        }
5933
6
        orphan_rowset_keys.clear();
5934
6
        return 0;
5935
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
Line
Count
Source
5929
6
    auto loop_done = [&]() -> int {
5930
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
5931
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5932
0
        }
5933
6
        orphan_rowset_keys.clear();
5934
6
        return 0;
5935
6
    };
5936
5937
    // recycle_func and loop_done for scan and recycle
5938
10
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
5939
10
                               std::move(loop_done));
5940
5941
10
    worker_pool->stop();
5942
5943
10
    if (!async_recycled_rowset_keys.empty()) {
5944
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5945
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5946
0
            return -1;
5947
0
        } else {
5948
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5949
0
        }
5950
0
    }
5951
5952
    // Report final metrics after all concurrent tasks completed
5953
10
    segment_metrics_context_.report();
5954
10
    metrics_context.report();
5955
5956
10
    return ret;
5957
10
}
5958
5959
1.61k
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task) {
5960
1.61k
    constexpr int MAX_RETRY = 10;
5961
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
5962
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
5963
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
5964
1.61k
    std::string_view reference_instance_id = instance_id_;
5965
1.61k
    if (rowset_meta.has_reference_instance_id()) {
5966
8
        reference_instance_id = rowset_meta.reference_instance_id();
5967
8
    }
5968
5969
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
5970
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
5971
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
5972
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
5973
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
5974
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
5975
1.61k
        std::unique_ptr<Transaction> txn;
5976
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5977
1.61k
        if (err != TxnErrorCode::TXN_OK) {
5978
0
            LOG_WARNING("failed to create txn").tag("err", err);
5979
0
            return -1;
5980
0
        }
5981
5982
1.61k
        std::string rowset_ref_count_key =
5983
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
5984
1.61k
        int64_t ref_count = 0;
5985
1.61k
        {
5986
1.61k
            std::string value;
5987
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
5988
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
5989
                // This is the old version rowset, we could recycle it directly.
5990
1.60k
                ref_count = 1;
5991
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
5992
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
5993
0
                return -1;
5994
11
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
5995
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
5996
0
                return -1;
5997
0
            }
5998
1.61k
        }
5999
6000
1.61k
        if (ref_count == 1) {
6001
            // It would not be added since it is recycling.
6002
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
6003
1.60k
                LOG_WARNING("failed to delete rowset data");
6004
1.60k
                return -1;
6005
1.60k
            }
6006
6007
            // Reset the transaction to avoid timeout.
6008
10
            err = txn_kv_->create_txn(&txn);
6009
10
            if (err != TxnErrorCode::TXN_OK) {
6010
0
                LOG_WARNING("failed to create txn").tag("err", err);
6011
0
                return -1;
6012
0
            }
6013
10
            txn->remove(rowset_ref_count_key);
6014
10
            LOG_INFO("delete rowset data ref count key")
6015
10
                    .tag("txn_id", rowset_meta.txn_id())
6016
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6017
6018
10
            std::string dbm_start_key =
6019
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
6020
10
            std::string dbm_end_key = meta_delete_bitmap_key(
6021
10
                    {reference_instance_id, tablet_id, rowset_id,
6022
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
6023
10
            txn->remove(dbm_start_key, dbm_end_key);
6024
10
            LOG_INFO("remove delete bitmap kv")
6025
10
                    .tag("begin", hex(dbm_start_key))
6026
10
                    .tag("end", hex(dbm_end_key));
6027
6028
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
6029
10
                    {reference_instance_id, tablet_id, rowset_id});
6030
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
6031
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
6032
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
6033
10
            LOG_INFO("remove versioned delete bitmap kv")
6034
10
                    .tag("begin", hex(versioned_dbm_start_key))
6035
10
                    .tag("end", hex(versioned_dbm_end_key));
6036
10
        } else {
6037
            // Decrease the rowset ref count.
6038
            //
6039
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
6040
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
6041
3
            txn->atomic_add(rowset_ref_count_key, -1);
6042
3
            LOG_INFO("decrease rowset data ref count")
6043
3
                    .tag("txn_id", rowset_meta.txn_id())
6044
3
                    .tag("ref_count", ref_count - 1)
6045
3
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6046
3
        }
6047
6048
13
        if (!task.versioned_rowset_key.empty()) {
6049
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
6050
0
                                                          task.versionstamp);
6051
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
6052
0
        }
6053
6054
13
        if (!task.non_versioned_rowset_key.empty()) {
6055
0
            txn->remove(task.non_versioned_rowset_key);
6056
0
            LOG_INFO("remove non versioned rowset key")
6057
0
                    .tag("key", hex(task.non_versioned_rowset_key));
6058
0
        }
6059
6060
        // empty when recycle ref rowsets for deleted instance
6061
13
        if (!task.recycle_rowset_key.empty()) {
6062
13
            txn->remove(task.recycle_rowset_key);
6063
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
6064
13
        }
6065
6066
13
        err = txn->commit();
6067
13
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
6068
            // The rowset ref count key has been changed, we need to retry.
6069
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
6070
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
6071
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
6072
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6073
0
            continue;
6074
13
        } else if (err != TxnErrorCode::TXN_OK) {
6075
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
6076
0
            return -1;
6077
0
        }
6078
13
        LOG_INFO("recycle rowset meta and data success");
6079
13
        return 0;
6080
13
    }
6081
0
    LOG_WARNING("failed to recycle rowset meta and data after retry")
6082
0
            .tag("tablet_id", tablet_id)
6083
0
            .tag("rowset_id", rowset_id)
6084
0
            .tag("retry", MAX_RETRY);
6085
0
    return -1;
6086
1.61k
}
6087
6088
34
int InstanceRecycler::recycle_tmp_rowsets() {
6089
34
    const std::string task_name = "recycle_tmp_rowsets";
6090
34
    int64_t num_scanned = 0;
6091
34
    int64_t num_expired = 0;
6092
34
    std::atomic_long num_recycled = 0;
6093
34
    size_t expired_rowset_size = 0;
6094
34
    size_t total_rowset_key_size = 0;
6095
34
    size_t total_rowset_value_size = 0;
6096
34
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6097
6098
34
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
6099
34
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
6100
34
    std::string tmp_rs_key0;
6101
34
    std::string tmp_rs_key1;
6102
34
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
6103
34
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
6104
6105
34
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
6106
6107
34
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6108
34
    register_recycle_task(task_name, start_time);
6109
6110
34
    DORIS_CLOUD_DEFER {
6111
34
        unregister_recycle_task(task_name);
6112
34
        int64_t cost =
6113
34
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6114
34
        metrics_context.finish_report();
6115
34
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6116
34
                .tag("instance_id", instance_id_)
6117
34
                .tag("num_scanned", num_scanned)
6118
34
                .tag("num_expired", num_expired)
6119
34
                .tag("num_recycled", num_recycled)
6120
34
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6121
34
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6122
34
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6123
34
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6110
12
    DORIS_CLOUD_DEFER {
6111
12
        unregister_recycle_task(task_name);
6112
12
        int64_t cost =
6113
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6114
12
        metrics_context.finish_report();
6115
12
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6116
12
                .tag("instance_id", instance_id_)
6117
12
                .tag("num_scanned", num_scanned)
6118
12
                .tag("num_expired", num_expired)
6119
12
                .tag("num_recycled", num_recycled)
6120
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6121
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6122
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6123
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6110
22
    DORIS_CLOUD_DEFER {
6111
22
        unregister_recycle_task(task_name);
6112
22
        int64_t cost =
6113
22
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6114
22
        metrics_context.finish_report();
6115
22
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6116
22
                .tag("instance_id", instance_id_)
6117
22
                .tag("num_scanned", num_scanned)
6118
22
                .tag("num_expired", num_expired)
6119
22
                .tag("num_recycled", num_recycled)
6120
22
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6121
22
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6122
22
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6123
22
    };
6124
6125
    // Elements in `tmp_rowset_keys` has the same lifetime as `it`
6126
6127
34
    std::vector<std::string> tmp_rowset_keys;
6128
34
    std::vector<std::string> tmp_rowset_ref_count_keys;
6129
34
    std::vector<std::string> tmp_rowset_keys_to_mark_recycled;
6130
34
    std::vector<std::string> tmp_rowset_keys_to_abort;
6131
6132
    // rowset_id -> rowset_meta
6133
    // store tmp_rowset id and meta for statistics rs size when delete
6134
34
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
6135
34
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6136
34
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
6137
34
    worker_pool->start();
6138
6139
34
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6140
6141
34
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &tmp_rowsets,
6142
34
                             &expired_rowset_size, &total_rowset_key_size, &total_rowset_value_size,
6143
34
                             &earlest_ts, &tmp_rowset_ref_count_keys,
6144
34
                             &tmp_rowset_keys_to_mark_recycled, &tmp_rowset_keys_to_abort, this,
6145
53.0k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
6146
53.0k
        ++num_scanned;
6147
53.0k
        total_rowset_key_size += k.size();
6148
53.0k
        total_rowset_value_size += v.size();
6149
53.0k
        doris::RowsetMetaCloudPB rowset;
6150
53.0k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6151
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6152
0
            return -1;
6153
0
        }
6154
53.0k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6155
53.0k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6156
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6157
0
                   << " txn_expiration=" << rowset.txn_expiration()
6158
0
                   << " rowset_creation_time=" << rowset.creation_time();
6159
53.0k
        int64_t current_time = ::time(nullptr);
6160
53.0k
        if (current_time < expiration) { // not expired
6161
0
            return 0;
6162
0
        }
6163
6164
53.0k
        if (config::enable_mark_delete_rowset_before_recycle) {
6165
16
            if (need_mark_rowset_as_recycled(rowset)) {
6166
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6167
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6168
9
                             "at next turn, instance_id="
6169
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6170
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6171
9
                return 0;
6172
9
            }
6173
16
        }
6174
6175
53.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6176
7
            if (make_deferred_abort_task(rowset).has_value()) {
6177
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6178
3
                             "instance_id="
6179
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6180
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6181
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6182
3
            }
6183
7
        }
6184
6185
53.0k
        ++num_expired;
6186
53.0k
        expired_rowset_size += v.size();
6187
53.0k
        if (!rowset.has_resource_id()) {
6188
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6189
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6190
0
                return -1;
6191
0
            }
6192
            // might be a delete pred rowset
6193
0
            tmp_rowset_keys.emplace_back(k);
6194
0
            return 0;
6195
0
        }
6196
        // TODO(plat1ko): check rowset not referenced
6197
53.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6198
53.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6199
53.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6200
53.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6201
53.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6202
53.0k
                  << " num_expired=" << num_expired
6203
53.0k
                  << " task_type=" << metrics_context.operation_type;
6204
6205
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6206
        // Remove the rowset ref count key directly since it has not been used.
6207
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6208
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6209
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6210
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6211
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6212
6213
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6214
53.0k
        return 0;
6215
53.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6145
16
                             &metrics_context](std::string_view k, std::string_view v) -> int {
6146
16
        ++num_scanned;
6147
16
        total_rowset_key_size += k.size();
6148
16
        total_rowset_value_size += v.size();
6149
16
        doris::RowsetMetaCloudPB rowset;
6150
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6151
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6152
0
            return -1;
6153
0
        }
6154
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6155
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6156
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6157
0
                   << " txn_expiration=" << rowset.txn_expiration()
6158
0
                   << " rowset_creation_time=" << rowset.creation_time();
6159
16
        int64_t current_time = ::time(nullptr);
6160
16
        if (current_time < expiration) { // not expired
6161
0
            return 0;
6162
0
        }
6163
6164
16
        if (config::enable_mark_delete_rowset_before_recycle) {
6165
16
            if (need_mark_rowset_as_recycled(rowset)) {
6166
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6167
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6168
9
                             "at next turn, instance_id="
6169
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6170
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6171
9
                return 0;
6172
9
            }
6173
16
        }
6174
6175
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6176
7
            if (make_deferred_abort_task(rowset).has_value()) {
6177
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6178
3
                             "instance_id="
6179
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6180
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6181
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6182
3
            }
6183
7
        }
6184
6185
7
        ++num_expired;
6186
7
        expired_rowset_size += v.size();
6187
7
        if (!rowset.has_resource_id()) {
6188
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6189
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6190
0
                return -1;
6191
0
            }
6192
            // might be a delete pred rowset
6193
0
            tmp_rowset_keys.emplace_back(k);
6194
0
            return 0;
6195
0
        }
6196
        // TODO(plat1ko): check rowset not referenced
6197
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6198
7
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6199
7
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6200
7
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6201
7
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6202
7
                  << " num_expired=" << num_expired
6203
7
                  << " task_type=" << metrics_context.operation_type;
6204
6205
7
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6206
        // Remove the rowset ref count key directly since it has not been used.
6207
7
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6208
7
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6209
7
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6210
7
                  << "key=" << hex(rowset_ref_count_key);
6211
7
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6212
6213
7
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6214
7
        return 0;
6215
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6145
53.0k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
6146
53.0k
        ++num_scanned;
6147
53.0k
        total_rowset_key_size += k.size();
6148
53.0k
        total_rowset_value_size += v.size();
6149
53.0k
        doris::RowsetMetaCloudPB rowset;
6150
53.0k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6151
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6152
0
            return -1;
6153
0
        }
6154
53.0k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6155
53.0k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6156
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6157
0
                   << " txn_expiration=" << rowset.txn_expiration()
6158
0
                   << " rowset_creation_time=" << rowset.creation_time();
6159
53.0k
        int64_t current_time = ::time(nullptr);
6160
53.0k
        if (current_time < expiration) { // not expired
6161
0
            return 0;
6162
0
        }
6163
6164
53.0k
        if (config::enable_mark_delete_rowset_before_recycle) {
6165
0
            if (need_mark_rowset_as_recycled(rowset)) {
6166
0
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6167
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6168
0
                             "at next turn, instance_id="
6169
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6170
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6171
0
                return 0;
6172
0
            }
6173
0
        }
6174
6175
53.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6176
0
            if (make_deferred_abort_task(rowset).has_value()) {
6177
0
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6178
0
                             "instance_id="
6179
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6180
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6181
0
                tmp_rowset_keys_to_abort.emplace_back(k);
6182
0
            }
6183
0
        }
6184
6185
53.0k
        ++num_expired;
6186
53.0k
        expired_rowset_size += v.size();
6187
53.0k
        if (!rowset.has_resource_id()) {
6188
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6189
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6190
0
                return -1;
6191
0
            }
6192
            // might be a delete pred rowset
6193
0
            tmp_rowset_keys.emplace_back(k);
6194
0
            return 0;
6195
0
        }
6196
        // TODO(plat1ko): check rowset not referenced
6197
53.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6198
53.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6199
53.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6200
53.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6201
53.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6202
53.0k
                  << " num_expired=" << num_expired
6203
53.0k
                  << " task_type=" << metrics_context.operation_type;
6204
6205
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6206
        // Remove the rowset ref count key directly since it has not been used.
6207
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6208
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6209
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6210
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6211
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6212
6213
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6214
53.0k
        return 0;
6215
53.0k
    };
6216
6217
    // TODO bacth delete
6218
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6219
51.0k
        std::string dbm_start_key =
6220
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
6221
51.0k
        std::string dbm_end_key = dbm_start_key;
6222
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
6223
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
6224
51.0k
        if (ret != 0) {
6225
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6226
0
                         << instance_id_ << ", tablet_id=" << tablet_id
6227
0
                         << ", rowset_id=" << rowset_id;
6228
0
        }
6229
51.0k
        return ret;
6230
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6218
7
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6219
7
        std::string dbm_start_key =
6220
7
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
6221
7
        std::string dbm_end_key = dbm_start_key;
6222
7
        encode_int64(INT64_MAX, &dbm_end_key);
6223
7
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
6224
7
        if (ret != 0) {
6225
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6226
0
                         << instance_id_ << ", tablet_id=" << tablet_id
6227
0
                         << ", rowset_id=" << rowset_id;
6228
0
        }
6229
7
        return ret;
6230
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6218
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6219
51.0k
        std::string dbm_start_key =
6220
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
6221
51.0k
        std::string dbm_end_key = dbm_start_key;
6222
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
6223
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
6224
51.0k
        if (ret != 0) {
6225
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6226
0
                         << instance_id_ << ", tablet_id=" << tablet_id
6227
0
                         << ", rowset_id=" << rowset_id;
6228
0
        }
6229
51.0k
        return ret;
6230
51.0k
    };
6231
6232
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6233
51.0k
        auto delete_bitmap_start =
6234
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
6235
51.0k
        auto delete_bitmap_end =
6236
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
6237
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
6238
51.0k
        if (ret != 0) {
6239
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
6240
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
6241
0
        }
6242
51.0k
        return ret;
6243
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6232
7
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6233
7
        auto delete_bitmap_start =
6234
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
6235
7
        auto delete_bitmap_end =
6236
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
6237
7
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
6238
7
        if (ret != 0) {
6239
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
6240
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
6241
0
        }
6242
7
        return ret;
6243
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6232
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6233
51.0k
        auto delete_bitmap_start =
6234
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
6235
51.0k
        auto delete_bitmap_end =
6236
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
6237
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
6238
51.0k
        if (ret != 0) {
6239
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
6240
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
6241
0
        }
6242
51.0k
        return ret;
6243
51.0k
    };
6244
6245
34
    auto loop_done = [&]() -> int {
6246
22
        std::vector<std::string> tmp_rowset_keys_to_delete;
6247
22
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6248
22
        std::vector<std::string> mark_keys_to_process;
6249
22
        std::vector<std::string> abort_keys_to_process;
6250
22
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6251
22
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6252
22
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6253
22
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6254
22
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6255
22
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6256
22
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6257
22
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6258
22
                             tmp_rowset_ref_count_keys_to_delete =
6259
22
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6260
22
                             mark_keys_to_process = std::move(mark_keys_to_process),
6261
22
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6262
22
            if (!mark_keys_to_process.empty() &&
6263
22
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6264
7
                                                                  mark_keys_to_process) != 0) {
6265
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6266
0
                             << instance_id_;
6267
0
                return;
6268
0
            }
6269
22
            if (!abort_keys_to_process.empty() &&
6270
22
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6271
3
                                                                      false) != 0) {
6272
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6273
0
                             << instance_id_;
6274
0
                return;
6275
0
            }
6276
22
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6277
22
                                   metrics_context) != 0) {
6278
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6279
2
                return;
6280
2
            }
6281
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6282
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6283
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6284
0
                                 << rs.ShortDebugString();
6285
0
                    return;
6286
0
                }
6287
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6288
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6289
0
                                 << rs.ShortDebugString();
6290
0
                    return;
6291
0
                }
6292
51.0k
            }
6293
20
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6294
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6295
0
                return;
6296
0
            }
6297
20
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6298
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6299
0
                return;
6300
0
            }
6301
20
            num_recycled += tmp_rowset_keys_to_delete.size();
6302
20
            return;
6303
20
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
6261
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6262
12
            if (!mark_keys_to_process.empty() &&
6263
12
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6264
7
                                                                  mark_keys_to_process) != 0) {
6265
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6266
0
                             << instance_id_;
6267
0
                return;
6268
0
            }
6269
12
            if (!abort_keys_to_process.empty() &&
6270
12
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6271
3
                                                                      false) != 0) {
6272
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6273
0
                             << instance_id_;
6274
0
                return;
6275
0
            }
6276
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6277
12
                                   metrics_context) != 0) {
6278
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6279
0
                return;
6280
0
            }
6281
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6282
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6283
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6284
0
                                 << rs.ShortDebugString();
6285
0
                    return;
6286
0
                }
6287
7
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6288
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6289
0
                                 << rs.ShortDebugString();
6290
0
                    return;
6291
0
                }
6292
7
            }
6293
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6294
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6295
0
                return;
6296
0
            }
6297
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6298
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6299
0
                return;
6300
0
            }
6301
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6302
12
            return;
6303
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
6261
10
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6262
10
            if (!mark_keys_to_process.empty() &&
6263
10
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6264
0
                                                                  mark_keys_to_process) != 0) {
6265
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6266
0
                             << instance_id_;
6267
0
                return;
6268
0
            }
6269
10
            if (!abort_keys_to_process.empty() &&
6270
10
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6271
0
                                                                      false) != 0) {
6272
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6273
0
                             << instance_id_;
6274
0
                return;
6275
0
            }
6276
10
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6277
10
                                   metrics_context) != 0) {
6278
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6279
2
                return;
6280
2
            }
6281
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6282
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6283
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6284
0
                                 << rs.ShortDebugString();
6285
0
                    return;
6286
0
                }
6287
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6288
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6289
0
                                 << rs.ShortDebugString();
6290
0
                    return;
6291
0
                }
6292
51.0k
            }
6293
8
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6294
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6295
0
                return;
6296
0
            }
6297
8
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6298
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6299
0
                return;
6300
0
            }
6301
8
            num_recycled += tmp_rowset_keys_to_delete.size();
6302
8
            return;
6303
8
        });
6304
22
        return 0;
6305
22
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEv
Line
Count
Source
6245
12
    auto loop_done = [&]() -> int {
6246
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6247
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6248
12
        std::vector<std::string> mark_keys_to_process;
6249
12
        std::vector<std::string> abort_keys_to_process;
6250
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6251
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6252
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6253
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6254
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6255
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6256
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6257
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6258
12
                             tmp_rowset_ref_count_keys_to_delete =
6259
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6260
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6261
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6262
12
            if (!mark_keys_to_process.empty() &&
6263
12
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6264
12
                                                                  mark_keys_to_process) != 0) {
6265
12
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6266
12
                             << instance_id_;
6267
12
                return;
6268
12
            }
6269
12
            if (!abort_keys_to_process.empty() &&
6270
12
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6271
12
                                                                      false) != 0) {
6272
12
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6273
12
                             << instance_id_;
6274
12
                return;
6275
12
            }
6276
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6277
12
                                   metrics_context) != 0) {
6278
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6279
12
                return;
6280
12
            }
6281
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6282
12
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6283
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6284
12
                                 << rs.ShortDebugString();
6285
12
                    return;
6286
12
                }
6287
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6288
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6289
12
                                 << rs.ShortDebugString();
6290
12
                    return;
6291
12
                }
6292
12
            }
6293
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6294
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6295
12
                return;
6296
12
            }
6297
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6298
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6299
12
                return;
6300
12
            }
6301
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6302
12
            return;
6303
12
        });
6304
12
        return 0;
6305
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEv
Line
Count
Source
6245
10
    auto loop_done = [&]() -> int {
6246
10
        std::vector<std::string> tmp_rowset_keys_to_delete;
6247
10
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6248
10
        std::vector<std::string> mark_keys_to_process;
6249
10
        std::vector<std::string> abort_keys_to_process;
6250
10
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6251
10
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6252
10
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6253
10
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6254
10
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6255
10
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6256
10
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6257
10
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6258
10
                             tmp_rowset_ref_count_keys_to_delete =
6259
10
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6260
10
                             mark_keys_to_process = std::move(mark_keys_to_process),
6261
10
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6262
10
            if (!mark_keys_to_process.empty() &&
6263
10
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6264
10
                                                                  mark_keys_to_process) != 0) {
6265
10
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6266
10
                             << instance_id_;
6267
10
                return;
6268
10
            }
6269
10
            if (!abort_keys_to_process.empty() &&
6270
10
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6271
10
                                                                      false) != 0) {
6272
10
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6273
10
                             << instance_id_;
6274
10
                return;
6275
10
            }
6276
10
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6277
10
                                   metrics_context) != 0) {
6278
10
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6279
10
                return;
6280
10
            }
6281
10
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6282
10
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6283
10
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6284
10
                                 << rs.ShortDebugString();
6285
10
                    return;
6286
10
                }
6287
10
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6288
10
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6289
10
                                 << rs.ShortDebugString();
6290
10
                    return;
6291
10
                }
6292
10
            }
6293
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6294
10
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6295
10
                return;
6296
10
            }
6297
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6298
10
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6299
10
                return;
6300
10
            }
6301
10
            num_recycled += tmp_rowset_keys_to_delete.size();
6302
10
            return;
6303
10
        });
6304
10
        return 0;
6305
10
    };
6306
6307
34
    if (config::enable_recycler_stats_metrics) {
6308
0
        scan_and_statistics_tmp_rowsets();
6309
0
    }
6310
    // recycle_func and loop_done for scan and recycle
6311
34
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
6312
34
                               std::move(loop_done));
6313
6314
34
    worker_pool->stop();
6315
6316
    // Report final metrics after all concurrent tasks completed
6317
34
    segment_metrics_context_.report();
6318
34
    metrics_context.report();
6319
6320
34
    return ret;
6321
34
}
6322
6323
int InstanceRecycler::scan_and_recycle(
6324
        std::string begin, std::string_view end,
6325
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
6326
322
        std::function<int()> loop_done, std::function<bool(std::string*)> next_begin_getter) {
6327
322
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
6328
322
    int ret = 0;
6329
322
    int64_t cnt = 0;
6330
322
    int get_range_retried = 0;
6331
322
    std::string err;
6332
322
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6333
322
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6334
322
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6335
322
                  << " ret=" << ret << " err=" << err;
6336
322
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6332
36
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6333
36
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6334
36
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6335
36
                  << " ret=" << ret << " err=" << err;
6336
36
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6332
286
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6333
286
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6334
286
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6335
286
                  << " ret=" << ret << " err=" << err;
6336
286
    };
6337
6338
322
    std::unique_ptr<RangeGetIterator> it;
6339
499
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
6340
356
        if (get_range_retried > 1000) {
6341
0
            err = "txn_get exceeds max retry(1000), may not scan all keys";
6342
0
            ret = -3;
6343
0
            return ret;
6344
0
        }
6345
356
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
6346
356
        if (get_ret != 0) { // txn kv may complain "Request for future version"
6347
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
6348
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
6349
0
                         << " get_range_retried=" << get_range_retried;
6350
0
            ++get_range_retried;
6351
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6352
0
            continue; // try again
6353
0
        }
6354
356
        if (!it->has_next()) {
6355
179
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
6356
179
            break; // scan finished
6357
179
        }
6358
177
        bool begin_updated = false;
6359
177
        LOG(INFO) << "scan_and_recycle iterator key_range=[" << hex(begin) << "," << hex(end)
6360
177
                  << ") iterator->size()=" << it->size();
6361
97.6k
        while (it->has_next()) {
6362
97.4k
            ++cnt;
6363
            // recycle corresponding resources
6364
97.4k
            auto [k, v] = it->next();
6365
97.4k
            if (!it->has_next()) {
6366
172
                begin = k;
6367
172
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
6368
172
            }
6369
            // FIXME(gavin): if we want to continue scanning, the recycle_func should not return non-zero
6370
97.4k
            if (recycle_func(k, v) != 0) {
6371
4.00k
                err = "recycle_func error";
6372
4.00k
                ret = -1;
6373
4.00k
            }
6374
97.4k
            if (next_begin_getter) {
6375
4.05k
                std::string next_begin;
6376
4.05k
                if (next_begin_getter(&next_begin)) {
6377
7
                    if (next_begin > k) {
6378
7
                        begin = std::move(next_begin);
6379
7
                        begin_updated = true;
6380
7
                        VLOG_DEBUG << "scan_and_recycle updates begin to " << hex(begin)
6381
0
                                   << " after key=" << hex(k);
6382
7
                        break;
6383
7
                    }
6384
0
                    LOG_WARNING("ignore invalid next begin in scan_and_recycle")
6385
0
                            .tag("next_begin", hex(next_begin))
6386
0
                            .tag("current_key", hex(k));
6387
0
                }
6388
4.05k
            }
6389
97.4k
        }
6390
177
        if (!begin_updated) {
6391
171
            begin.push_back('\x00'); // Update to next smallest key for iteration
6392
171
        } else {
6393
6
            it.reset();
6394
6
        }
6395
6396
        // FIXME(gavin): if we want to continue scanning, the loop_done should not return non-zero
6397
        // if we want to continue scanning, the recycle_func should not return non-zero
6398
177
        if (loop_done && loop_done() != 0) {
6399
5
            err = "loop_done error";
6400
5
            ret = -1;
6401
5
        }
6402
177
    }
6403
322
    return ret;
6404
322
}
6405
6406
19
int InstanceRecycler::abort_timeout_txn() {
6407
19
    const std::string task_name = "abort_timeout_txn";
6408
19
    int64_t num_scanned = 0;
6409
19
    int64_t num_timeout = 0;
6410
19
    int64_t num_abort = 0;
6411
19
    int64_t num_advance = 0;
6412
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6413
6414
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6415
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6416
19
    std::string begin_txn_running_key;
6417
19
    std::string end_txn_running_key;
6418
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6419
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6420
6421
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
6422
6423
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6424
19
    register_recycle_task(task_name, start_time);
6425
6426
19
    DORIS_CLOUD_DEFER {
6427
19
        unregister_recycle_task(task_name);
6428
19
        int64_t cost =
6429
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6430
19
        metrics_context.finish_report();
6431
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6432
19
                .tag("instance_id", instance_id_)
6433
19
                .tag("num_scanned", num_scanned)
6434
19
                .tag("num_timeout", num_timeout)
6435
19
                .tag("num_abort", num_abort)
6436
19
                .tag("num_advance", num_advance);
6437
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6426
3
    DORIS_CLOUD_DEFER {
6427
3
        unregister_recycle_task(task_name);
6428
3
        int64_t cost =
6429
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6430
3
        metrics_context.finish_report();
6431
3
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6432
3
                .tag("instance_id", instance_id_)
6433
3
                .tag("num_scanned", num_scanned)
6434
3
                .tag("num_timeout", num_timeout)
6435
3
                .tag("num_abort", num_abort)
6436
3
                .tag("num_advance", num_advance);
6437
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6426
16
    DORIS_CLOUD_DEFER {
6427
16
        unregister_recycle_task(task_name);
6428
16
        int64_t cost =
6429
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6430
16
        metrics_context.finish_report();
6431
16
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6432
16
                .tag("instance_id", instance_id_)
6433
16
                .tag("num_scanned", num_scanned)
6434
16
                .tag("num_timeout", num_timeout)
6435
16
                .tag("num_abort", num_abort)
6436
16
                .tag("num_advance", num_advance);
6437
16
    };
6438
6439
19
    int64_t current_time =
6440
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6441
6442
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
6443
19
                                  &current_time, &metrics_context,
6444
19
                                  this](std::string_view k, std::string_view v) -> int {
6445
9
        ++num_scanned;
6446
6447
9
        std::unique_ptr<Transaction> txn;
6448
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6449
9
        if (err != TxnErrorCode::TXN_OK) {
6450
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6451
0
            return -1;
6452
0
        }
6453
9
        std::string_view k1 = k;
6454
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6455
9
        k1.remove_prefix(1); // Remove key space
6456
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6457
9
        if (decode_key(&k1, &out) != 0) {
6458
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6459
0
            return -1;
6460
0
        }
6461
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6462
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6463
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6464
        // Update txn_info
6465
9
        std::string txn_inf_key, txn_inf_val;
6466
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6467
9
        err = txn->get(txn_inf_key, &txn_inf_val);
6468
9
        if (err != TxnErrorCode::TXN_OK) {
6469
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6470
0
            return -1;
6471
0
        }
6472
9
        TxnInfoPB txn_info;
6473
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
6474
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6475
0
            return -1;
6476
0
        }
6477
6478
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6479
3
            txn.reset();
6480
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6481
3
            std::shared_ptr<TxnLazyCommitTask> task =
6482
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6483
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6484
3
            if (ret.first != MetaServiceCode::OK) {
6485
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6486
0
                             << "msg=" << ret.second;
6487
0
                return -1;
6488
0
            }
6489
3
            ++num_advance;
6490
3
            return 0;
6491
6
        } else {
6492
6
            TxnRunningPB txn_running_pb;
6493
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6494
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6495
0
                return -1;
6496
0
            }
6497
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6498
4
                return 0;
6499
4
            }
6500
2
            ++num_timeout;
6501
6502
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6503
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6504
2
            txn_info.set_finish_time(current_time);
6505
2
            txn_info.set_reason("timeout");
6506
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6507
2
            txn_inf_val.clear();
6508
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6509
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6510
0
                return -1;
6511
0
            }
6512
2
            txn->put(txn_inf_key, txn_inf_val);
6513
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6514
            // Put recycle txn key
6515
2
            std::string recyc_txn_key, recyc_txn_val;
6516
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6517
2
            RecycleTxnPB recycle_txn_pb;
6518
2
            recycle_txn_pb.set_creation_time(current_time);
6519
2
            recycle_txn_pb.set_label(txn_info.label());
6520
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6521
0
                LOG_WARNING("failed to serialize txn recycle info")
6522
0
                        .tag("key", hex(k))
6523
0
                        .tag("db_id", db_id)
6524
0
                        .tag("txn_id", txn_id);
6525
0
                return -1;
6526
0
            }
6527
2
            txn->put(recyc_txn_key, recyc_txn_val);
6528
            // Remove txn running key
6529
2
            txn->remove(k);
6530
2
            err = txn->commit();
6531
2
            if (err != TxnErrorCode::TXN_OK) {
6532
0
                LOG_WARNING("failed to commit txn err={}", err)
6533
0
                        .tag("key", hex(k))
6534
0
                        .tag("db_id", db_id)
6535
0
                        .tag("txn_id", txn_id);
6536
0
                return -1;
6537
0
            }
6538
2
            metrics_context.total_recycled_num = ++num_abort;
6539
2
            metrics_context.report();
6540
2
        }
6541
6542
2
        return 0;
6543
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6444
3
                                  this](std::string_view k, std::string_view v) -> int {
6445
3
        ++num_scanned;
6446
6447
3
        std::unique_ptr<Transaction> txn;
6448
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6449
3
        if (err != TxnErrorCode::TXN_OK) {
6450
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6451
0
            return -1;
6452
0
        }
6453
3
        std::string_view k1 = k;
6454
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6455
3
        k1.remove_prefix(1); // Remove key space
6456
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6457
3
        if (decode_key(&k1, &out) != 0) {
6458
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6459
0
            return -1;
6460
0
        }
6461
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6462
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6463
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6464
        // Update txn_info
6465
3
        std::string txn_inf_key, txn_inf_val;
6466
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6467
3
        err = txn->get(txn_inf_key, &txn_inf_val);
6468
3
        if (err != TxnErrorCode::TXN_OK) {
6469
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6470
0
            return -1;
6471
0
        }
6472
3
        TxnInfoPB txn_info;
6473
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
6474
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6475
0
            return -1;
6476
0
        }
6477
6478
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6479
3
            txn.reset();
6480
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6481
3
            std::shared_ptr<TxnLazyCommitTask> task =
6482
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6483
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6484
3
            if (ret.first != MetaServiceCode::OK) {
6485
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6486
0
                             << "msg=" << ret.second;
6487
0
                return -1;
6488
0
            }
6489
3
            ++num_advance;
6490
3
            return 0;
6491
3
        } else {
6492
0
            TxnRunningPB txn_running_pb;
6493
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6494
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6495
0
                return -1;
6496
0
            }
6497
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6498
0
                return 0;
6499
0
            }
6500
0
            ++num_timeout;
6501
6502
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6503
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6504
0
            txn_info.set_finish_time(current_time);
6505
0
            txn_info.set_reason("timeout");
6506
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6507
0
            txn_inf_val.clear();
6508
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6509
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6510
0
                return -1;
6511
0
            }
6512
0
            txn->put(txn_inf_key, txn_inf_val);
6513
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6514
            // Put recycle txn key
6515
0
            std::string recyc_txn_key, recyc_txn_val;
6516
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6517
0
            RecycleTxnPB recycle_txn_pb;
6518
0
            recycle_txn_pb.set_creation_time(current_time);
6519
0
            recycle_txn_pb.set_label(txn_info.label());
6520
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6521
0
                LOG_WARNING("failed to serialize txn recycle info")
6522
0
                        .tag("key", hex(k))
6523
0
                        .tag("db_id", db_id)
6524
0
                        .tag("txn_id", txn_id);
6525
0
                return -1;
6526
0
            }
6527
0
            txn->put(recyc_txn_key, recyc_txn_val);
6528
            // Remove txn running key
6529
0
            txn->remove(k);
6530
0
            err = txn->commit();
6531
0
            if (err != TxnErrorCode::TXN_OK) {
6532
0
                LOG_WARNING("failed to commit txn err={}", err)
6533
0
                        .tag("key", hex(k))
6534
0
                        .tag("db_id", db_id)
6535
0
                        .tag("txn_id", txn_id);
6536
0
                return -1;
6537
0
            }
6538
0
            metrics_context.total_recycled_num = ++num_abort;
6539
0
            metrics_context.report();
6540
0
        }
6541
6542
0
        return 0;
6543
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6444
6
                                  this](std::string_view k, std::string_view v) -> int {
6445
6
        ++num_scanned;
6446
6447
6
        std::unique_ptr<Transaction> txn;
6448
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6449
6
        if (err != TxnErrorCode::TXN_OK) {
6450
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6451
0
            return -1;
6452
0
        }
6453
6
        std::string_view k1 = k;
6454
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6455
6
        k1.remove_prefix(1); // Remove key space
6456
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6457
6
        if (decode_key(&k1, &out) != 0) {
6458
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6459
0
            return -1;
6460
0
        }
6461
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6462
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6463
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6464
        // Update txn_info
6465
6
        std::string txn_inf_key, txn_inf_val;
6466
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6467
6
        err = txn->get(txn_inf_key, &txn_inf_val);
6468
6
        if (err != TxnErrorCode::TXN_OK) {
6469
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6470
0
            return -1;
6471
0
        }
6472
6
        TxnInfoPB txn_info;
6473
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
6474
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6475
0
            return -1;
6476
0
        }
6477
6478
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6479
0
            txn.reset();
6480
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6481
0
            std::shared_ptr<TxnLazyCommitTask> task =
6482
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6483
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6484
0
            if (ret.first != MetaServiceCode::OK) {
6485
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6486
0
                             << "msg=" << ret.second;
6487
0
                return -1;
6488
0
            }
6489
0
            ++num_advance;
6490
0
            return 0;
6491
6
        } else {
6492
6
            TxnRunningPB txn_running_pb;
6493
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6494
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6495
0
                return -1;
6496
0
            }
6497
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6498
4
                return 0;
6499
4
            }
6500
2
            ++num_timeout;
6501
6502
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6503
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6504
2
            txn_info.set_finish_time(current_time);
6505
2
            txn_info.set_reason("timeout");
6506
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6507
2
            txn_inf_val.clear();
6508
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6509
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6510
0
                return -1;
6511
0
            }
6512
2
            txn->put(txn_inf_key, txn_inf_val);
6513
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6514
            // Put recycle txn key
6515
2
            std::string recyc_txn_key, recyc_txn_val;
6516
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6517
2
            RecycleTxnPB recycle_txn_pb;
6518
2
            recycle_txn_pb.set_creation_time(current_time);
6519
2
            recycle_txn_pb.set_label(txn_info.label());
6520
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6521
0
                LOG_WARNING("failed to serialize txn recycle info")
6522
0
                        .tag("key", hex(k))
6523
0
                        .tag("db_id", db_id)
6524
0
                        .tag("txn_id", txn_id);
6525
0
                return -1;
6526
0
            }
6527
2
            txn->put(recyc_txn_key, recyc_txn_val);
6528
            // Remove txn running key
6529
2
            txn->remove(k);
6530
2
            err = txn->commit();
6531
2
            if (err != TxnErrorCode::TXN_OK) {
6532
0
                LOG_WARNING("failed to commit txn err={}", err)
6533
0
                        .tag("key", hex(k))
6534
0
                        .tag("db_id", db_id)
6535
0
                        .tag("txn_id", txn_id);
6536
0
                return -1;
6537
0
            }
6538
2
            metrics_context.total_recycled_num = ++num_abort;
6539
2
            metrics_context.report();
6540
2
        }
6541
6542
2
        return 0;
6543
6
    };
6544
6545
19
    if (config::enable_recycler_stats_metrics) {
6546
0
        scan_and_statistics_abort_timeout_txn();
6547
0
    }
6548
    // recycle_func and loop_done for scan and recycle
6549
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
6550
19
                            std::move(handle_txn_running_kv));
6551
19
}
6552
6553
19
int InstanceRecycler::recycle_expired_txn_label() {
6554
19
    const std::string task_name = "recycle_expired_txn_label";
6555
19
    int64_t num_scanned = 0;
6556
19
    int64_t num_expired = 0;
6557
19
    std::atomic_long num_recycled = 0;
6558
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6559
19
    int ret = 0;
6560
6561
19
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
6562
19
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6563
19
    std::string begin_recycle_txn_key;
6564
19
    std::string end_recycle_txn_key;
6565
19
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
6566
19
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
6567
19
    std::vector<std::string> recycle_txn_info_keys;
6568
6569
19
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
6570
6571
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6572
19
    register_recycle_task(task_name, start_time);
6573
19
    DORIS_CLOUD_DEFER {
6574
19
        unregister_recycle_task(task_name);
6575
19
        int64_t cost =
6576
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6577
19
        metrics_context.finish_report();
6578
19
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6579
19
                .tag("instance_id", instance_id_)
6580
19
                .tag("num_scanned", num_scanned)
6581
19
                .tag("num_expired", num_expired)
6582
19
                .tag("num_recycled", num_recycled);
6583
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6573
1
    DORIS_CLOUD_DEFER {
6574
1
        unregister_recycle_task(task_name);
6575
1
        int64_t cost =
6576
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6577
1
        metrics_context.finish_report();
6578
1
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6579
1
                .tag("instance_id", instance_id_)
6580
1
                .tag("num_scanned", num_scanned)
6581
1
                .tag("num_expired", num_expired)
6582
1
                .tag("num_recycled", num_recycled);
6583
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6573
18
    DORIS_CLOUD_DEFER {
6574
18
        unregister_recycle_task(task_name);
6575
18
        int64_t cost =
6576
18
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6577
18
        metrics_context.finish_report();
6578
18
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6579
18
                .tag("instance_id", instance_id_)
6580
18
                .tag("num_scanned", num_scanned)
6581
18
                .tag("num_expired", num_expired)
6582
18
                .tag("num_recycled", num_recycled);
6583
18
    };
6584
6585
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6586
6587
19
    SyncExecutor<int> concurrent_delete_executor(
6588
19
            _thread_pool_group.s3_producer_pool,
6589
19
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
6590
23.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
6590
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
6590
23.0k
            [](const int& ret) { return ret != 0; });
6591
6592
19
    int64_t current_time_ms =
6593
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6594
6595
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6596
30.0k
        ++num_scanned;
6597
30.0k
        RecycleTxnPB recycle_txn_pb;
6598
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6599
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6600
0
            return -1;
6601
0
        }
6602
30.0k
        if ((config::force_immediate_recycle) ||
6603
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6604
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6605
30.0k
             current_time_ms)) {
6606
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6607
23.0k
            num_expired++;
6608
23.0k
            recycle_txn_info_keys.emplace_back(k);
6609
23.0k
        }
6610
30.0k
        return 0;
6611
30.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6595
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6596
1
        ++num_scanned;
6597
1
        RecycleTxnPB recycle_txn_pb;
6598
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6599
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6600
0
            return -1;
6601
0
        }
6602
1
        if ((config::force_immediate_recycle) ||
6603
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6604
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6605
1
             current_time_ms)) {
6606
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6607
1
            num_expired++;
6608
1
            recycle_txn_info_keys.emplace_back(k);
6609
1
        }
6610
1
        return 0;
6611
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6595
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6596
30.0k
        ++num_scanned;
6597
30.0k
        RecycleTxnPB recycle_txn_pb;
6598
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6599
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6600
0
            return -1;
6601
0
        }
6602
30.0k
        if ((config::force_immediate_recycle) ||
6603
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6604
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6605
30.0k
             current_time_ms)) {
6606
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6607
23.0k
            num_expired++;
6608
23.0k
            recycle_txn_info_keys.emplace_back(k);
6609
23.0k
        }
6610
30.0k
        return 0;
6611
30.0k
    };
6612
6613
    // int 0 for success, 1 for conflict, -1 for error
6614
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6615
23.0k
        std::string_view k1 = k;
6616
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6617
23.0k
        k1.remove_prefix(1); // Remove key space
6618
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6619
23.0k
        int ret = decode_key(&k1, &out);
6620
23.0k
        if (ret != 0) {
6621
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6622
0
            return -1;
6623
0
        }
6624
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6625
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6626
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6627
23.0k
        std::unique_ptr<Transaction> txn;
6628
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6629
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6630
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6631
0
            return -1;
6632
0
        }
6633
        // Remove txn index kv
6634
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6635
23.0k
        txn->remove(index_key);
6636
        // Remove txn info kv
6637
23.0k
        std::string info_key, info_val;
6638
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6639
23.0k
        err = txn->get(info_key, &info_val);
6640
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6641
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6642
0
            return -1;
6643
0
        }
6644
23.0k
        TxnInfoPB txn_info;
6645
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6646
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6647
0
            return -1;
6648
0
        }
6649
23.0k
        txn->remove(info_key);
6650
        // Remove sub txn index kvs
6651
23.0k
        std::vector<std::string> sub_txn_index_keys;
6652
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6653
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6654
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6655
22.9k
        }
6656
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6657
22.9k
            txn->remove(sub_txn_index_key);
6658
22.9k
        }
6659
        // Update txn label
6660
23.0k
        std::string label_key, label_val;
6661
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6662
23.0k
        err = txn->get(label_key, &label_val);
6663
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6664
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6665
0
                         << " err=" << err;
6666
0
            return -1;
6667
0
        }
6668
23.0k
        TxnLabelPB txn_label;
6669
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6670
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6671
0
            return -1;
6672
0
        }
6673
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6674
23.0k
        if (it != txn_label.txn_ids().end()) {
6675
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6676
23.0k
        }
6677
23.0k
        if (txn_label.txn_ids().empty()) {
6678
23.0k
            txn->remove(label_key);
6679
23.0k
            TEST_SYNC_POINT_CALLBACK(
6680
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6681
23.0k
        } else {
6682
73
            if (!txn_label.SerializeToString(&label_val)) {
6683
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6684
0
                return -1;
6685
0
            }
6686
73
            TEST_SYNC_POINT_CALLBACK(
6687
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6688
73
            txn->atomic_set_ver_value(label_key, label_val);
6689
73
            TEST_SYNC_POINT_CALLBACK(
6690
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6691
73
        }
6692
        // Remove recycle txn kv
6693
23.0k
        txn->remove(k);
6694
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6695
23.0k
        err = txn->commit();
6696
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6697
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6698
62
                TEST_SYNC_POINT_CALLBACK(
6699
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6700
                // log the txn_id and label
6701
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6702
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6703
62
                             << " txn_label=" << txn_info.label();
6704
62
                return 1;
6705
62
            }
6706
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6707
0
            return -1;
6708
62
        }
6709
23.0k
        ++num_recycled;
6710
6711
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6712
23.0k
        return 0;
6713
23.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6614
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6615
1
        std::string_view k1 = k;
6616
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6617
1
        k1.remove_prefix(1); // Remove key space
6618
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6619
1
        int ret = decode_key(&k1, &out);
6620
1
        if (ret != 0) {
6621
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6622
0
            return -1;
6623
0
        }
6624
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6625
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6626
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6627
1
        std::unique_ptr<Transaction> txn;
6628
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6629
1
        if (err != TxnErrorCode::TXN_OK) {
6630
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6631
0
            return -1;
6632
0
        }
6633
        // Remove txn index kv
6634
1
        auto index_key = txn_index_key({instance_id_, txn_id});
6635
1
        txn->remove(index_key);
6636
        // Remove txn info kv
6637
1
        std::string info_key, info_val;
6638
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6639
1
        err = txn->get(info_key, &info_val);
6640
1
        if (err != TxnErrorCode::TXN_OK) {
6641
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6642
0
            return -1;
6643
0
        }
6644
1
        TxnInfoPB txn_info;
6645
1
        if (!txn_info.ParseFromString(info_val)) {
6646
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6647
0
            return -1;
6648
0
        }
6649
1
        txn->remove(info_key);
6650
        // Remove sub txn index kvs
6651
1
        std::vector<std::string> sub_txn_index_keys;
6652
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6653
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6654
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
6655
0
        }
6656
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6657
0
            txn->remove(sub_txn_index_key);
6658
0
        }
6659
        // Update txn label
6660
1
        std::string label_key, label_val;
6661
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6662
1
        err = txn->get(label_key, &label_val);
6663
1
        if (err != TxnErrorCode::TXN_OK) {
6664
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6665
0
                         << " err=" << err;
6666
0
            return -1;
6667
0
        }
6668
1
        TxnLabelPB txn_label;
6669
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6670
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6671
0
            return -1;
6672
0
        }
6673
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6674
1
        if (it != txn_label.txn_ids().end()) {
6675
1
            txn_label.mutable_txn_ids()->erase(it);
6676
1
        }
6677
1
        if (txn_label.txn_ids().empty()) {
6678
1
            txn->remove(label_key);
6679
1
            TEST_SYNC_POINT_CALLBACK(
6680
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6681
1
        } else {
6682
0
            if (!txn_label.SerializeToString(&label_val)) {
6683
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6684
0
                return -1;
6685
0
            }
6686
0
            TEST_SYNC_POINT_CALLBACK(
6687
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6688
0
            txn->atomic_set_ver_value(label_key, label_val);
6689
0
            TEST_SYNC_POINT_CALLBACK(
6690
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6691
0
        }
6692
        // Remove recycle txn kv
6693
1
        txn->remove(k);
6694
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6695
1
        err = txn->commit();
6696
1
        if (err != TxnErrorCode::TXN_OK) {
6697
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
6698
0
                TEST_SYNC_POINT_CALLBACK(
6699
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6700
                // log the txn_id and label
6701
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6702
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6703
0
                             << " txn_label=" << txn_info.label();
6704
0
                return 1;
6705
0
            }
6706
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6707
0
            return -1;
6708
0
        }
6709
1
        ++num_recycled;
6710
6711
1
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6712
1
        return 0;
6713
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6614
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6615
23.0k
        std::string_view k1 = k;
6616
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6617
23.0k
        k1.remove_prefix(1); // Remove key space
6618
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6619
23.0k
        int ret = decode_key(&k1, &out);
6620
23.0k
        if (ret != 0) {
6621
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6622
0
            return -1;
6623
0
        }
6624
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6625
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6626
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6627
23.0k
        std::unique_ptr<Transaction> txn;
6628
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6629
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6630
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6631
0
            return -1;
6632
0
        }
6633
        // Remove txn index kv
6634
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6635
23.0k
        txn->remove(index_key);
6636
        // Remove txn info kv
6637
23.0k
        std::string info_key, info_val;
6638
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6639
23.0k
        err = txn->get(info_key, &info_val);
6640
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6641
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6642
0
            return -1;
6643
0
        }
6644
23.0k
        TxnInfoPB txn_info;
6645
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6646
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6647
0
            return -1;
6648
0
        }
6649
23.0k
        txn->remove(info_key);
6650
        // Remove sub txn index kvs
6651
23.0k
        std::vector<std::string> sub_txn_index_keys;
6652
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6653
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6654
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6655
22.9k
        }
6656
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6657
22.9k
            txn->remove(sub_txn_index_key);
6658
22.9k
        }
6659
        // Update txn label
6660
23.0k
        std::string label_key, label_val;
6661
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6662
23.0k
        err = txn->get(label_key, &label_val);
6663
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6664
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6665
0
                         << " err=" << err;
6666
0
            return -1;
6667
0
        }
6668
23.0k
        TxnLabelPB txn_label;
6669
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6670
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6671
0
            return -1;
6672
0
        }
6673
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6674
23.0k
        if (it != txn_label.txn_ids().end()) {
6675
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6676
23.0k
        }
6677
23.0k
        if (txn_label.txn_ids().empty()) {
6678
23.0k
            txn->remove(label_key);
6679
23.0k
            TEST_SYNC_POINT_CALLBACK(
6680
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6681
23.0k
        } else {
6682
73
            if (!txn_label.SerializeToString(&label_val)) {
6683
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6684
0
                return -1;
6685
0
            }
6686
73
            TEST_SYNC_POINT_CALLBACK(
6687
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6688
73
            txn->atomic_set_ver_value(label_key, label_val);
6689
73
            TEST_SYNC_POINT_CALLBACK(
6690
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6691
73
        }
6692
        // Remove recycle txn kv
6693
23.0k
        txn->remove(k);
6694
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6695
23.0k
        err = txn->commit();
6696
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6697
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6698
62
                TEST_SYNC_POINT_CALLBACK(
6699
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6700
                // log the txn_id and label
6701
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6702
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6703
62
                             << " txn_label=" << txn_info.label();
6704
62
                return 1;
6705
62
            }
6706
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6707
0
            return -1;
6708
62
        }
6709
23.0k
        ++num_recycled;
6710
6711
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6712
23.0k
        return 0;
6713
23.0k
    };
6714
6715
19
    auto loop_done = [&]() -> int {
6716
10
        DORIS_CLOUD_DEFER {
6717
10
            recycle_txn_info_keys.clear();
6718
10
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6716
1
        DORIS_CLOUD_DEFER {
6717
1
            recycle_txn_info_keys.clear();
6718
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6716
9
        DORIS_CLOUD_DEFER {
6717
9
            recycle_txn_info_keys.clear();
6718
9
        };
6719
10
        TEST_SYNC_POINT_CALLBACK(
6720
10
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6721
10
                &recycle_txn_info_keys);
6722
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6723
23.0k
            concurrent_delete_executor.add([&]() {
6724
23.0k
                int ret = delete_recycle_txn_kv(k);
6725
23.0k
                if (ret == 1) {
6726
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6727
54
                    for (int i = 1; i <= max_retry; ++i) {
6728
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6729
54
                        ret = delete_recycle_txn_kv(k);
6730
                        // clang-format off
6731
54
                        TEST_SYNC_POINT_CALLBACK(
6732
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6733
                        // clang-format off
6734
54
                        if (ret != 1) {
6735
18
                            break;
6736
18
                        }
6737
                        // random sleep 0-100 ms to retry
6738
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6739
36
                    }
6740
18
                }
6741
23.0k
                if (ret != 0) {
6742
9
                    LOG_WARNING("failed to delete recycle txn kv")
6743
9
                            .tag("instance id", instance_id_)
6744
9
                            .tag("key", hex(k));
6745
9
                    return -1;
6746
9
                }
6747
23.0k
                return 0;
6748
23.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6723
1
            concurrent_delete_executor.add([&]() {
6724
1
                int ret = delete_recycle_txn_kv(k);
6725
1
                if (ret == 1) {
6726
0
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6727
0
                    for (int i = 1; i <= max_retry; ++i) {
6728
0
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6729
0
                        ret = delete_recycle_txn_kv(k);
6730
                        // clang-format off
6731
0
                        TEST_SYNC_POINT_CALLBACK(
6732
0
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6733
                        // clang-format off
6734
0
                        if (ret != 1) {
6735
0
                            break;
6736
0
                        }
6737
                        // random sleep 0-100 ms to retry
6738
0
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6739
0
                    }
6740
0
                }
6741
1
                if (ret != 0) {
6742
0
                    LOG_WARNING("failed to delete recycle txn kv")
6743
0
                            .tag("instance id", instance_id_)
6744
0
                            .tag("key", hex(k));
6745
0
                    return -1;
6746
0
                }
6747
1
                return 0;
6748
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6723
23.0k
            concurrent_delete_executor.add([&]() {
6724
23.0k
                int ret = delete_recycle_txn_kv(k);
6725
23.0k
                if (ret == 1) {
6726
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6727
54
                    for (int i = 1; i <= max_retry; ++i) {
6728
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6729
54
                        ret = delete_recycle_txn_kv(k);
6730
                        // clang-format off
6731
54
                        TEST_SYNC_POINT_CALLBACK(
6732
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6733
                        // clang-format off
6734
54
                        if (ret != 1) {
6735
18
                            break;
6736
18
                        }
6737
                        // random sleep 0-100 ms to retry
6738
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6739
36
                    }
6740
18
                }
6741
23.0k
                if (ret != 0) {
6742
9
                    LOG_WARNING("failed to delete recycle txn kv")
6743
9
                            .tag("instance id", instance_id_)
6744
9
                            .tag("key", hex(k));
6745
9
                    return -1;
6746
9
                }
6747
23.0k
                return 0;
6748
23.0k
            });
6749
23.0k
        }
6750
10
        bool finished = true;
6751
10
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6752
23.0k
        for (int r : rets) {
6753
23.0k
            if (r != 0) {
6754
9
                ret = -1;
6755
9
            }
6756
23.0k
        }
6757
6758
10
        ret = finished ? ret : -1;
6759
6760
        // Update metrics after all concurrent tasks completed
6761
10
        metrics_context.total_recycled_num = num_recycled.load();
6762
10
        metrics_context.report();
6763
6764
10
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6765
6766
10
        if (ret != 0) {
6767
3
            LOG_WARNING("recycle txn kv ret!=0")
6768
3
                    .tag("finished", finished)
6769
3
                    .tag("ret", ret)
6770
3
                    .tag("instance_id", instance_id_);
6771
3
            return ret;
6772
3
        }
6773
7
        return ret;
6774
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6715
1
    auto loop_done = [&]() -> int {
6716
1
        DORIS_CLOUD_DEFER {
6717
1
            recycle_txn_info_keys.clear();
6718
1
        };
6719
1
        TEST_SYNC_POINT_CALLBACK(
6720
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6721
1
                &recycle_txn_info_keys);
6722
1
        for (const auto& k : recycle_txn_info_keys) {
6723
1
            concurrent_delete_executor.add([&]() {
6724
1
                int ret = delete_recycle_txn_kv(k);
6725
1
                if (ret == 1) {
6726
1
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6727
1
                    for (int i = 1; i <= max_retry; ++i) {
6728
1
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6729
1
                        ret = delete_recycle_txn_kv(k);
6730
                        // clang-format off
6731
1
                        TEST_SYNC_POINT_CALLBACK(
6732
1
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6733
                        // clang-format off
6734
1
                        if (ret != 1) {
6735
1
                            break;
6736
1
                        }
6737
                        // random sleep 0-100 ms to retry
6738
1
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6739
1
                    }
6740
1
                }
6741
1
                if (ret != 0) {
6742
1
                    LOG_WARNING("failed to delete recycle txn kv")
6743
1
                            .tag("instance id", instance_id_)
6744
1
                            .tag("key", hex(k));
6745
1
                    return -1;
6746
1
                }
6747
1
                return 0;
6748
1
            });
6749
1
        }
6750
1
        bool finished = true;
6751
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6752
1
        for (int r : rets) {
6753
1
            if (r != 0) {
6754
0
                ret = -1;
6755
0
            }
6756
1
        }
6757
6758
1
        ret = finished ? ret : -1;
6759
6760
        // Update metrics after all concurrent tasks completed
6761
1
        metrics_context.total_recycled_num = num_recycled.load();
6762
1
        metrics_context.report();
6763
6764
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6765
6766
1
        if (ret != 0) {
6767
0
            LOG_WARNING("recycle txn kv ret!=0")
6768
0
                    .tag("finished", finished)
6769
0
                    .tag("ret", ret)
6770
0
                    .tag("instance_id", instance_id_);
6771
0
            return ret;
6772
0
        }
6773
1
        return ret;
6774
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6715
9
    auto loop_done = [&]() -> int {
6716
9
        DORIS_CLOUD_DEFER {
6717
9
            recycle_txn_info_keys.clear();
6718
9
        };
6719
9
        TEST_SYNC_POINT_CALLBACK(
6720
9
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6721
9
                &recycle_txn_info_keys);
6722
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6723
23.0k
            concurrent_delete_executor.add([&]() {
6724
23.0k
                int ret = delete_recycle_txn_kv(k);
6725
23.0k
                if (ret == 1) {
6726
23.0k
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6727
23.0k
                    for (int i = 1; i <= max_retry; ++i) {
6728
23.0k
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6729
23.0k
                        ret = delete_recycle_txn_kv(k);
6730
                        // clang-format off
6731
23.0k
                        TEST_SYNC_POINT_CALLBACK(
6732
23.0k
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6733
                        // clang-format off
6734
23.0k
                        if (ret != 1) {
6735
23.0k
                            break;
6736
23.0k
                        }
6737
                        // random sleep 0-100 ms to retry
6738
23.0k
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6739
23.0k
                    }
6740
23.0k
                }
6741
23.0k
                if (ret != 0) {
6742
23.0k
                    LOG_WARNING("failed to delete recycle txn kv")
6743
23.0k
                            .tag("instance id", instance_id_)
6744
23.0k
                            .tag("key", hex(k));
6745
23.0k
                    return -1;
6746
23.0k
                }
6747
23.0k
                return 0;
6748
23.0k
            });
6749
23.0k
        }
6750
9
        bool finished = true;
6751
9
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6752
23.0k
        for (int r : rets) {
6753
23.0k
            if (r != 0) {
6754
9
                ret = -1;
6755
9
            }
6756
23.0k
        }
6757
6758
9
        ret = finished ? ret : -1;
6759
6760
        // Update metrics after all concurrent tasks completed
6761
9
        metrics_context.total_recycled_num = num_recycled.load();
6762
9
        metrics_context.report();
6763
6764
9
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6765
6766
9
        if (ret != 0) {
6767
3
            LOG_WARNING("recycle txn kv ret!=0")
6768
3
                    .tag("finished", finished)
6769
3
                    .tag("ret", ret)
6770
3
                    .tag("instance_id", instance_id_);
6771
3
            return ret;
6772
3
        }
6773
6
        return ret;
6774
9
    };
6775
6776
19
    if (config::enable_recycler_stats_metrics) {
6777
0
        scan_and_statistics_expired_txn_label();
6778
0
    }
6779
    // recycle_func and loop_done for scan and recycle
6780
19
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
6781
19
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
6782
19
}
6783
6784
struct CopyJobIdTuple {
6785
    std::string instance_id;
6786
    std::string stage_id;
6787
    long table_id;
6788
    std::string copy_id;
6789
    std::string stage_path;
6790
};
6791
struct BatchObjStoreAccessor {
6792
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
6793
                          TxnKv* txn_kv)
6794
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
6795
3
    ~BatchObjStoreAccessor() {
6796
3
        if (!paths_.empty()) {
6797
3
            consume();
6798
3
        }
6799
3
    }
6800
6801
    /**
6802
    * To implicitely do batch work and submit the batch delete task to s3
6803
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
6804
    *
6805
    * @param copy_job The protubuf struct consists of the copy job files.
6806
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
6807
    *            it would last until we finish the delete task, here we need pass one string value
6808
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
6809
    */
6810
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
6811
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
6812
5
        auto& file_keys = copy_file_keys_[key];
6813
5
        file_keys.log_trace =
6814
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
6815
5
                            instance_id, stage_id, table_id, copy_id, path);
6816
5
        std::string_view log_trace = file_keys.log_trace;
6817
2.03k
        for (const auto& file : copy_job.object_files()) {
6818
2.03k
            auto relative_path = file.relative_path();
6819
2.03k
            paths_.push_back(relative_path);
6820
2.03k
            file_keys.keys.push_back(copy_file_key(
6821
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
6822
2.03k
            LOG_INFO(log_trace)
6823
2.03k
                    .tag("relative_path", relative_path)
6824
2.03k
                    .tag("batch_count", batch_count_);
6825
2.03k
        }
6826
5
        LOG_INFO(log_trace)
6827
5
                .tag("objects_num", copy_job.object_files().size())
6828
5
                .tag("batch_count", batch_count_);
6829
        // 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
6830
        // recommend using delete objects when objects num is less than 10)
6831
5
        if (paths_.size() < 1000) {
6832
3
            return;
6833
3
        }
6834
2
        consume();
6835
2
    }
6836
6837
private:
6838
5
    void consume() {
6839
5
        DORIS_CLOUD_DEFER {
6840
5
            paths_.clear();
6841
5
            copy_file_keys_.clear();
6842
5
            batch_count_++;
6843
6844
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
6845
5
                        batch_count_);
6846
5
        };
6847
6848
5
        StopWatch sw;
6849
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
6850
5
        if (0 != accessor_->delete_files(paths_)) {
6851
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
6852
2
                        paths_.size(), batch_count_, sw.elapsed_us());
6853
2
            return;
6854
2
        }
6855
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
6856
3
                    paths_.size(), batch_count_, sw.elapsed_us());
6857
        // delete fdb's keys
6858
3
        for (auto& file_keys : copy_file_keys_) {
6859
3
            auto& [log_trace, keys] = file_keys.second;
6860
3
            std::unique_ptr<Transaction> txn;
6861
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
6862
0
                LOG(WARNING) << "failed to create txn";
6863
0
                continue;
6864
0
            }
6865
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6866
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6867
            // limited, should not cause the txn commit failed.
6868
1.02k
            for (const auto& key : keys) {
6869
1.02k
                txn->remove(key);
6870
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
6871
1.02k
            }
6872
3
            txn->remove(file_keys.first);
6873
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
6874
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
6875
0
                continue;
6876
0
            }
6877
3
        }
6878
3
    }
6879
    std::shared_ptr<StorageVaultAccessor> accessor_;
6880
    // the path of the s3 files to be deleted
6881
    std::vector<std::string> paths_;
6882
    struct CopyFiles {
6883
        std::string log_trace;
6884
        std::vector<std::string> keys;
6885
    };
6886
    // pair<std::string, std::vector<std::string>>
6887
    // first: instance_id_ stage_id table_id query_id
6888
    // second: keys to be deleted
6889
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
6890
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
6891
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
6892
    // which can together uniquely identifies different tasks for tracing log
6893
    uint64_t& batch_count_;
6894
    TxnKv* txn_kv_;
6895
};
6896
6897
13
int InstanceRecycler::recycle_copy_jobs() {
6898
13
    int64_t num_scanned = 0;
6899
13
    int64_t num_finished = 0;
6900
13
    int64_t num_expired = 0;
6901
13
    int64_t num_recycled = 0;
6902
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
6903
13
    uint64_t batch_count = 0;
6904
13
    const std::string task_name = "recycle_copy_jobs";
6905
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6906
6907
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
6908
6909
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6910
13
    register_recycle_task(task_name, start_time);
6911
6912
13
    DORIS_CLOUD_DEFER {
6913
13
        unregister_recycle_task(task_name);
6914
13
        int64_t cost =
6915
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6916
13
        metrics_context.finish_report();
6917
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
6918
13
                .tag("instance_id", instance_id_)
6919
13
                .tag("num_scanned", num_scanned)
6920
13
                .tag("num_finished", num_finished)
6921
13
                .tag("num_expired", num_expired)
6922
13
                .tag("num_recycled", num_recycled);
6923
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
6912
13
    DORIS_CLOUD_DEFER {
6913
13
        unregister_recycle_task(task_name);
6914
13
        int64_t cost =
6915
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6916
13
        metrics_context.finish_report();
6917
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
6918
13
                .tag("instance_id", instance_id_)
6919
13
                .tag("num_scanned", num_scanned)
6920
13
                .tag("num_finished", num_finished)
6921
13
                .tag("num_expired", num_expired)
6922
13
                .tag("num_recycled", num_recycled);
6923
13
    };
6924
6925
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
6926
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
6927
13
    std::string key0;
6928
13
    std::string key1;
6929
13
    copy_job_key(key_info0, &key0);
6930
13
    copy_job_key(key_info1, &key1);
6931
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
6932
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
6933
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
6934
16
                         this](std::string_view k, std::string_view v) -> int {
6935
16
        ++num_scanned;
6936
16
        CopyJobPB copy_job;
6937
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
6938
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
6939
0
            return -1;
6940
0
        }
6941
6942
        // decode copy job key
6943
16
        auto k1 = k;
6944
16
        k1.remove_prefix(1);
6945
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6946
16
        decode_key(&k1, &out);
6947
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
6948
        // -> CopyJobPB
6949
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
6950
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
6951
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
6952
6953
16
        bool check_storage = true;
6954
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
6955
12
            ++num_finished;
6956
6957
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
6958
7
                auto it = stage_accessor_map.find(stage_id);
6959
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
6960
7
                std::string_view path;
6961
7
                if (it != stage_accessor_map.end()) {
6962
2
                    accessor = it->second;
6963
5
                } else {
6964
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
6965
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
6966
5
                                                      &inner_accessor);
6967
5
                    if (ret < 0) { // error
6968
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
6969
0
                        return -1;
6970
5
                    } else if (ret == 0) {
6971
3
                        path = inner_accessor->uri();
6972
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
6973
3
                                inner_accessor, batch_count, txn_kv_.get());
6974
3
                        stage_accessor_map.emplace(stage_id, accessor);
6975
3
                    } else { // stage not found, skip check storage
6976
2
                        check_storage = false;
6977
2
                    }
6978
5
                }
6979
7
                if (check_storage) {
6980
                    // TODO delete objects with key and etag is not supported
6981
5
                    accessor->add(std::move(copy_job), std::string(k),
6982
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
6983
5
                    return 0;
6984
5
                }
6985
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
6986
5
                int64_t current_time =
6987
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6988
5
                if (copy_job.finish_time_ms() > 0) {
6989
2
                    if (!config::force_immediate_recycle &&
6990
2
                        current_time < copy_job.finish_time_ms() +
6991
2
                                               config::copy_job_max_retention_second * 1000) {
6992
1
                        return 0;
6993
1
                    }
6994
3
                } else {
6995
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
6996
3
                    if (!config::force_immediate_recycle &&
6997
3
                        current_time < copy_job.start_time_ms() +
6998
3
                                               config::copy_job_max_retention_second * 1000) {
6999
1
                        return 0;
7000
1
                    }
7001
3
                }
7002
5
            }
7003
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7004
4
            int64_t current_time =
7005
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7006
            // if copy job is timeout: delete all copy file kvs and copy job kv
7007
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7008
2
                return 0;
7009
2
            }
7010
2
            ++num_expired;
7011
2
        }
7012
7013
        // delete all copy files
7014
7
        std::vector<std::string> copy_file_keys;
7015
70
        for (auto& file : copy_job.object_files()) {
7016
70
            copy_file_keys.push_back(copy_file_key(
7017
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7018
70
        }
7019
7
        std::unique_ptr<Transaction> txn;
7020
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7021
0
            LOG(WARNING) << "failed to create txn";
7022
0
            return -1;
7023
0
        }
7024
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7025
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7026
        // limited, should not cause the txn commit failed.
7027
70
        for (const auto& key : copy_file_keys) {
7028
70
            txn->remove(key);
7029
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7030
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7031
70
                      << ", query_id=" << copy_id;
7032
70
        }
7033
7
        txn->remove(k);
7034
7
        TxnErrorCode err = txn->commit();
7035
7
        if (err != TxnErrorCode::TXN_OK) {
7036
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7037
0
            return -1;
7038
0
        }
7039
7040
7
        metrics_context.total_recycled_num = ++num_recycled;
7041
7
        metrics_context.report();
7042
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7043
7
        return 0;
7044
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
6934
16
                         this](std::string_view k, std::string_view v) -> int {
6935
16
        ++num_scanned;
6936
16
        CopyJobPB copy_job;
6937
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
6938
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
6939
0
            return -1;
6940
0
        }
6941
6942
        // decode copy job key
6943
16
        auto k1 = k;
6944
16
        k1.remove_prefix(1);
6945
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6946
16
        decode_key(&k1, &out);
6947
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
6948
        // -> CopyJobPB
6949
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
6950
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
6951
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
6952
6953
16
        bool check_storage = true;
6954
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
6955
12
            ++num_finished;
6956
6957
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
6958
7
                auto it = stage_accessor_map.find(stage_id);
6959
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
6960
7
                std::string_view path;
6961
7
                if (it != stage_accessor_map.end()) {
6962
2
                    accessor = it->second;
6963
5
                } else {
6964
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
6965
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
6966
5
                                                      &inner_accessor);
6967
5
                    if (ret < 0) { // error
6968
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
6969
0
                        return -1;
6970
5
                    } else if (ret == 0) {
6971
3
                        path = inner_accessor->uri();
6972
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
6973
3
                                inner_accessor, batch_count, txn_kv_.get());
6974
3
                        stage_accessor_map.emplace(stage_id, accessor);
6975
3
                    } else { // stage not found, skip check storage
6976
2
                        check_storage = false;
6977
2
                    }
6978
5
                }
6979
7
                if (check_storage) {
6980
                    // TODO delete objects with key and etag is not supported
6981
5
                    accessor->add(std::move(copy_job), std::string(k),
6982
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
6983
5
                    return 0;
6984
5
                }
6985
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
6986
5
                int64_t current_time =
6987
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6988
5
                if (copy_job.finish_time_ms() > 0) {
6989
2
                    if (!config::force_immediate_recycle &&
6990
2
                        current_time < copy_job.finish_time_ms() +
6991
2
                                               config::copy_job_max_retention_second * 1000) {
6992
1
                        return 0;
6993
1
                    }
6994
3
                } else {
6995
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
6996
3
                    if (!config::force_immediate_recycle &&
6997
3
                        current_time < copy_job.start_time_ms() +
6998
3
                                               config::copy_job_max_retention_second * 1000) {
6999
1
                        return 0;
7000
1
                    }
7001
3
                }
7002
5
            }
7003
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7004
4
            int64_t current_time =
7005
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7006
            // if copy job is timeout: delete all copy file kvs and copy job kv
7007
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7008
2
                return 0;
7009
2
            }
7010
2
            ++num_expired;
7011
2
        }
7012
7013
        // delete all copy files
7014
7
        std::vector<std::string> copy_file_keys;
7015
70
        for (auto& file : copy_job.object_files()) {
7016
70
            copy_file_keys.push_back(copy_file_key(
7017
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7018
70
        }
7019
7
        std::unique_ptr<Transaction> txn;
7020
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7021
0
            LOG(WARNING) << "failed to create txn";
7022
0
            return -1;
7023
0
        }
7024
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7025
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7026
        // limited, should not cause the txn commit failed.
7027
70
        for (const auto& key : copy_file_keys) {
7028
70
            txn->remove(key);
7029
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7030
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7031
70
                      << ", query_id=" << copy_id;
7032
70
        }
7033
7
        txn->remove(k);
7034
7
        TxnErrorCode err = txn->commit();
7035
7
        if (err != TxnErrorCode::TXN_OK) {
7036
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7037
0
            return -1;
7038
0
        }
7039
7040
7
        metrics_context.total_recycled_num = ++num_recycled;
7041
7
        metrics_context.report();
7042
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7043
7
        return 0;
7044
7
    };
7045
7046
13
    if (config::enable_recycler_stats_metrics) {
7047
0
        scan_and_statistics_copy_jobs();
7048
0
    }
7049
    // recycle_func and loop_done for scan and recycle
7050
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
7051
13
}
7052
7053
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
7054
                                             const StagePB::StageType& stage_type,
7055
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
7056
5
#ifdef UNIT_TEST
7057
    // In unit test, external use the same accessor as the internal stage
7058
5
    auto it = accessor_map_.find(stage_id);
7059
5
    if (it != accessor_map_.end()) {
7060
3
        *accessor = it->second;
7061
3
    } else {
7062
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
7063
2
        return 1;
7064
2
    }
7065
#else
7066
    // init s3 accessor and add to accessor map
7067
    auto stage_it =
7068
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
7069
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
7070
7071
    if (stage_it == instance_info_.stages().end()) {
7072
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
7073
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
7074
        return 1;
7075
    }
7076
7077
    const auto& object_store_info = stage_it->obj_info();
7078
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
7079
7080
    S3Conf s3_conf;
7081
    if (stage_type == StagePB::EXTERNAL) {
7082
        if (stage_access_type == StagePB::AKSK) {
7083
            auto conf = S3Conf::from_obj_store_info(object_store_info);
7084
            if (!conf) {
7085
                return -1;
7086
            }
7087
7088
            s3_conf = std::move(*conf);
7089
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
7090
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
7091
            if (!conf) {
7092
                return -1;
7093
            }
7094
7095
            s3_conf = std::move(*conf);
7096
            if (instance_info_.ram_user().has_encryption_info()) {
7097
                AkSkPair plain_ak_sk_pair;
7098
                int ret = decrypt_ak_sk_helper(
7099
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
7100
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
7101
                if (ret != 0) {
7102
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
7103
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
7104
                    return -1;
7105
                }
7106
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
7107
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
7108
            } else {
7109
                s3_conf.ak = instance_info_.ram_user().ak();
7110
                s3_conf.sk = instance_info_.ram_user().sk();
7111
            }
7112
        } else {
7113
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
7114
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
7115
            return -1;
7116
        }
7117
    } else if (stage_type == StagePB::INTERNAL) {
7118
        int idx = stoi(object_store_info.id());
7119
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7120
            LOG(WARNING) << "invalid idx: " << idx;
7121
            return -1;
7122
        }
7123
7124
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7125
        auto conf = S3Conf::from_obj_store_info(old_obj);
7126
        if (!conf) {
7127
            return -1;
7128
        }
7129
7130
        s3_conf = std::move(*conf);
7131
        s3_conf.prefix = object_store_info.prefix();
7132
    } else {
7133
        LOG(WARNING) << "unknown stage type " << stage_type;
7134
        return -1;
7135
    }
7136
7137
    std::shared_ptr<S3Accessor> s3_accessor;
7138
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
7139
    if (ret != 0) {
7140
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
7141
        return -1;
7142
    }
7143
7144
    *accessor = std::move(s3_accessor);
7145
#endif
7146
3
    return 0;
7147
5
}
7148
7149
11
int InstanceRecycler::recycle_stage() {
7150
11
    int64_t num_scanned = 0;
7151
11
    int64_t num_recycled = 0;
7152
11
    const std::string task_name = "recycle_stage";
7153
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7154
7155
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
7156
7157
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7158
11
    register_recycle_task(task_name, start_time);
7159
7160
11
    DORIS_CLOUD_DEFER {
7161
11
        unregister_recycle_task(task_name);
7162
11
        int64_t cost =
7163
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7164
11
        metrics_context.finish_report();
7165
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7166
11
                .tag("instance_id", instance_id_)
7167
11
                .tag("num_scanned", num_scanned)
7168
11
                .tag("num_recycled", num_recycled);
7169
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
7160
11
    DORIS_CLOUD_DEFER {
7161
11
        unregister_recycle_task(task_name);
7162
11
        int64_t cost =
7163
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7164
11
        metrics_context.finish_report();
7165
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7166
11
                .tag("instance_id", instance_id_)
7167
11
                .tag("num_scanned", num_scanned)
7168
11
                .tag("num_recycled", num_recycled);
7169
11
    };
7170
7171
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7172
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7173
11
    std::string key0 = recycle_stage_key(key_info0);
7174
11
    std::string key1 = recycle_stage_key(key_info1);
7175
7176
11
    std::vector<std::string_view> stage_keys;
7177
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
7178
11
                         this](std::string_view k, std::string_view v) -> int {
7179
1
        ++num_scanned;
7180
1
        RecycleStagePB recycle_stage;
7181
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7182
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7183
0
            return -1;
7184
0
        }
7185
7186
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7187
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7188
0
            LOG(WARNING) << "invalid idx: " << idx;
7189
0
            return -1;
7190
0
        }
7191
7192
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7193
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7194
1
                [&] {
7195
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7196
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7197
1
                    if (!s3_conf) {
7198
1
                        return -1;
7199
1
                    }
7200
7201
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7202
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7203
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7204
1
                    if (ret != 0) {
7205
1
                        return -1;
7206
1
                    }
7207
7208
1
                    accessor = std::move(s3_accessor);
7209
1
                    return 0;
7210
1
                }(),
7211
1
                "recycle_stage:get_accessor", &accessor);
7212
7213
1
        if (ret != 0) {
7214
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7215
0
            return ret;
7216
0
        }
7217
7218
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7219
1
                .tag("instance_id", instance_id_)
7220
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7221
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7222
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7223
1
                .tag("obj_info_id", idx)
7224
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7225
1
        ret = accessor->delete_all();
7226
1
        if (ret != 0) {
7227
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7228
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7229
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7230
0
                         << ", ret=" << ret;
7231
0
            return -1;
7232
0
        }
7233
1
        metrics_context.total_recycled_num = ++num_recycled;
7234
1
        metrics_context.report();
7235
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7236
1
        stage_keys.push_back(k);
7237
1
        return 0;
7238
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7178
1
                         this](std::string_view k, std::string_view v) -> int {
7179
1
        ++num_scanned;
7180
1
        RecycleStagePB recycle_stage;
7181
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7182
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7183
0
            return -1;
7184
0
        }
7185
7186
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7187
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7188
0
            LOG(WARNING) << "invalid idx: " << idx;
7189
0
            return -1;
7190
0
        }
7191
7192
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7193
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7194
1
                [&] {
7195
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7196
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7197
1
                    if (!s3_conf) {
7198
1
                        return -1;
7199
1
                    }
7200
7201
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7202
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7203
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7204
1
                    if (ret != 0) {
7205
1
                        return -1;
7206
1
                    }
7207
7208
1
                    accessor = std::move(s3_accessor);
7209
1
                    return 0;
7210
1
                }(),
7211
1
                "recycle_stage:get_accessor", &accessor);
7212
7213
1
        if (ret != 0) {
7214
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7215
0
            return ret;
7216
0
        }
7217
7218
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7219
1
                .tag("instance_id", instance_id_)
7220
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7221
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7222
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7223
1
                .tag("obj_info_id", idx)
7224
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7225
1
        ret = accessor->delete_all();
7226
1
        if (ret != 0) {
7227
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7228
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7229
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7230
0
                         << ", ret=" << ret;
7231
0
            return -1;
7232
0
        }
7233
1
        metrics_context.total_recycled_num = ++num_recycled;
7234
1
        metrics_context.report();
7235
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7236
1
        stage_keys.push_back(k);
7237
1
        return 0;
7238
1
    };
7239
7240
11
    auto loop_done = [&stage_keys, this]() -> int {
7241
1
        if (stage_keys.empty()) return 0;
7242
1
        DORIS_CLOUD_DEFER {
7243
1
            stage_keys.clear();
7244
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
7242
1
        DORIS_CLOUD_DEFER {
7243
1
            stage_keys.clear();
7244
1
        };
7245
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7246
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7247
0
            return -1;
7248
0
        }
7249
1
        return 0;
7250
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
7240
1
    auto loop_done = [&stage_keys, this]() -> int {
7241
1
        if (stage_keys.empty()) return 0;
7242
1
        DORIS_CLOUD_DEFER {
7243
1
            stage_keys.clear();
7244
1
        };
7245
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7246
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7247
0
            return -1;
7248
0
        }
7249
1
        return 0;
7250
1
    };
7251
11
    if (config::enable_recycler_stats_metrics) {
7252
0
        scan_and_statistics_stage();
7253
0
    }
7254
    // recycle_func and loop_done for scan and recycle
7255
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
7256
11
}
7257
7258
10
int InstanceRecycler::recycle_expired_stage_objects() {
7259
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
7260
7261
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7262
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7263
7264
10
    DORIS_CLOUD_DEFER {
7265
10
        int64_t cost =
7266
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7267
10
        metrics_context.finish_report();
7268
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7269
10
                .tag("instance_id", instance_id_);
7270
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
7264
10
    DORIS_CLOUD_DEFER {
7265
10
        int64_t cost =
7266
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7267
10
        metrics_context.finish_report();
7268
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7269
10
                .tag("instance_id", instance_id_);
7270
10
    };
7271
7272
10
    int ret = 0;
7273
7274
10
    if (config::enable_recycler_stats_metrics) {
7275
0
        scan_and_statistics_expired_stage_objects();
7276
0
    }
7277
7278
10
    for (const auto& stage : instance_info_.stages()) {
7279
0
        std::stringstream ss;
7280
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
7281
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
7282
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
7283
0
           << ", prefix=" << stage.obj_info().prefix();
7284
7285
0
        if (stopped()) {
7286
0
            break;
7287
0
        }
7288
0
        if (stage.type() == StagePB::EXTERNAL) {
7289
0
            continue;
7290
0
        }
7291
0
        int idx = stoi(stage.obj_info().id());
7292
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7293
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
7294
0
            continue;
7295
0
        }
7296
7297
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7298
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7299
0
        if (!s3_conf) {
7300
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
7301
0
            continue;
7302
0
        }
7303
7304
0
        s3_conf->prefix = stage.obj_info().prefix();
7305
0
        std::shared_ptr<S3Accessor> accessor;
7306
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
7307
0
        if (ret1 != 0) {
7308
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
7309
0
            ret = -1;
7310
0
            continue;
7311
0
        }
7312
7313
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7314
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
7315
0
            ret = -1;
7316
0
            continue;
7317
0
        }
7318
7319
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
7320
0
        int64_t expiration_time =
7321
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
7322
0
                config::internal_stage_objects_expire_time_second;
7323
0
        if (config::force_immediate_recycle) {
7324
0
            expiration_time = INT64_MAX;
7325
0
        }
7326
0
        ret1 = accessor->delete_all(expiration_time);
7327
0
        if (ret1 != 0) {
7328
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
7329
0
                         << ss.str();
7330
0
            ret = -1;
7331
0
            continue;
7332
0
        }
7333
0
        metrics_context.total_recycled_num++;
7334
0
        metrics_context.report();
7335
0
    }
7336
10
    return ret;
7337
10
}
7338
7339
233
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
7340
233
    std::lock_guard lock(recycle_tasks_mutex);
7341
233
    running_recycle_tasks[task_name] = start_time;
7342
233
}
7343
7344
233
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
7345
233
    std::lock_guard lock(recycle_tasks_mutex);
7346
233
    DCHECK(running_recycle_tasks[task_name] > 0);
7347
233
    running_recycle_tasks.erase(task_name);
7348
233
}
7349
7350
3
bool InstanceRecycler::check_recycle_tasks() {
7351
3
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
7352
3
    {
7353
3
        std::lock_guard lock(recycle_tasks_mutex);
7354
3
        tmp_running_recycle_tasks = running_recycle_tasks;
7355
3
    }
7356
7357
3
    bool found = false;
7358
3
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7359
3
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
7360
2
        int64_t cost = now - start_time;
7361
2
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
7362
2
            LOG_INFO("recycle task cost too much time cost={}s", cost)
7363
2
                    .tag("instance_id", instance_id_)
7364
2
                    .tag("task", task_name);
7365
2
            found = true;
7366
2
        }
7367
2
    }
7368
7369
3
    return found;
7370
3
}
7371
7372
// Scan and statistics indexes that need to be recycled
7373
1
int InstanceRecycler::scan_and_statistics_indexes() {
7374
1
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
7375
1
    RecyclerMetricsContext stream_metrics_context(instance_id_, "recycle_stream");
7376
7377
1
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
7378
1
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
7379
1
    std::string index_key0;
7380
1
    std::string index_key1;
7381
1
    recycle_index_key(index_key_info0, &index_key0);
7382
1
    recycle_index_key(index_key_info1, &index_key1);
7383
1
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7384
7385
1
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7386
1
        RecycleIndexPB index_pb;
7387
1
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7388
0
            return 0;
7389
0
        }
7390
1
        int64_t current_time = ::time(nullptr);
7391
1
        if (current_time <
7392
1
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7393
0
            return 0;
7394
0
        }
7395
        // decode index_id
7396
1
        auto k1 = k;
7397
1
        k1.remove_prefix(1);
7398
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7399
1
        decode_key(&k1, &out);
7400
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7401
1
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7402
1
        std::unique_ptr<Transaction> txn;
7403
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7404
1
        if (err != TxnErrorCode::TXN_OK) {
7405
0
            return 0;
7406
0
        }
7407
1
        std::string val;
7408
1
        err = txn->get(k, &val);
7409
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7410
0
            return 0;
7411
0
        }
7412
1
        if (err != TxnErrorCode::TXN_OK) {
7413
0
            return 0;
7414
0
        }
7415
1
        index_pb.Clear();
7416
1
        if (!index_pb.ParseFromString(val)) {
7417
0
            return 0;
7418
0
        }
7419
1
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
7420
1
            if (!index_pb.has_db_id() || !index_pb.has_stream_db_id()) {
7421
0
                LOG_WARNING("table stream recycle index is missing binding")
7422
0
                        .tag("instance_id", instance_id_)
7423
0
                        .tag("stream_id", index_id);
7424
0
                return 0;
7425
0
            }
7426
2
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7427
2
                std::string end = prefix;
7428
2
                end.push_back('\xff');
7429
2
                auto count_offset = [&stream_metrics_context](std::string_view key,
7430
6
                                                              std::string_view value) {
7431
6
                    stream_metrics_context.total_need_recycle_num++;
7432
6
                    stream_metrics_context.total_need_recycle_data_size +=
7433
6
                            key.size() + value.size();
7434
6
                    return 0;
7435
6
                };
Unexecuted instantiation: recycler.cpp:_ZZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_ENKUlS6_S6_E_clES6_S6_
recycler_test.cpp:_ZZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_ENKUlS6_S6_E_clES6_S6_
Line
Count
Source
7430
6
                                                              std::string_view value) {
7431
6
                    stream_metrics_context.total_need_recycle_num++;
7432
6
                    stream_metrics_context.total_need_recycle_data_size +=
7433
6
                            key.size() + value.size();
7434
6
                    return 0;
7435
6
                };
7436
2
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7437
2
            };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_
Line
Count
Source
7426
2
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7427
2
                std::string end = prefix;
7428
2
                end.push_back('\xff');
7429
2
                auto count_offset = [&stream_metrics_context](std::string_view key,
7430
2
                                                              std::string_view value) {
7431
2
                    stream_metrics_context.total_need_recycle_num++;
7432
2
                    stream_metrics_context.total_need_recycle_data_size +=
7433
2
                            key.size() + value.size();
7434
2
                    return 0;
7435
2
                };
7436
2
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7437
2
            };
7438
1
            const std::string latest_prefix = table_stream_offset_key_prefix(
7439
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7440
1
                    index_id);
7441
1
            const std::string versioned_prefix = versioned::table_stream_offset_key_prefix(
7442
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7443
1
                    index_id);
7444
1
            if (scan_offset_prefix(latest_prefix) != 0 ||
7445
1
                scan_offset_prefix(versioned_prefix) != 0) {
7446
0
                LOG_WARNING("failed to scan table stream offsets for recycle statistics")
7447
0
                        .tag("instance_id", instance_id_)
7448
0
                        .tag("stream_id", index_id);
7449
0
            }
7450
1
            return 0;
7451
1
        }
7452
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7453
0
            return 0;
7454
0
        }
7455
0
        metrics_context.total_need_recycle_num++;
7456
0
        return 0;
7457
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7385
1
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7386
1
        RecycleIndexPB index_pb;
7387
1
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7388
0
            return 0;
7389
0
        }
7390
1
        int64_t current_time = ::time(nullptr);
7391
1
        if (current_time <
7392
1
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7393
0
            return 0;
7394
0
        }
7395
        // decode index_id
7396
1
        auto k1 = k;
7397
1
        k1.remove_prefix(1);
7398
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7399
1
        decode_key(&k1, &out);
7400
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7401
1
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7402
1
        std::unique_ptr<Transaction> txn;
7403
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7404
1
        if (err != TxnErrorCode::TXN_OK) {
7405
0
            return 0;
7406
0
        }
7407
1
        std::string val;
7408
1
        err = txn->get(k, &val);
7409
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7410
0
            return 0;
7411
0
        }
7412
1
        if (err != TxnErrorCode::TXN_OK) {
7413
0
            return 0;
7414
0
        }
7415
1
        index_pb.Clear();
7416
1
        if (!index_pb.ParseFromString(val)) {
7417
0
            return 0;
7418
0
        }
7419
1
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
7420
1
            if (!index_pb.has_db_id() || !index_pb.has_stream_db_id()) {
7421
0
                LOG_WARNING("table stream recycle index is missing binding")
7422
0
                        .tag("instance_id", instance_id_)
7423
0
                        .tag("stream_id", index_id);
7424
0
                return 0;
7425
0
            }
7426
1
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7427
1
                std::string end = prefix;
7428
1
                end.push_back('\xff');
7429
1
                auto count_offset = [&stream_metrics_context](std::string_view key,
7430
1
                                                              std::string_view value) {
7431
1
                    stream_metrics_context.total_need_recycle_num++;
7432
1
                    stream_metrics_context.total_need_recycle_data_size +=
7433
1
                            key.size() + value.size();
7434
1
                    return 0;
7435
1
                };
7436
1
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7437
1
            };
7438
1
            const std::string latest_prefix = table_stream_offset_key_prefix(
7439
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7440
1
                    index_id);
7441
1
            const std::string versioned_prefix = versioned::table_stream_offset_key_prefix(
7442
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7443
1
                    index_id);
7444
1
            if (scan_offset_prefix(latest_prefix) != 0 ||
7445
1
                scan_offset_prefix(versioned_prefix) != 0) {
7446
0
                LOG_WARNING("failed to scan table stream offsets for recycle statistics")
7447
0
                        .tag("instance_id", instance_id_)
7448
0
                        .tag("stream_id", index_id);
7449
0
            }
7450
1
            return 0;
7451
1
        }
7452
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7453
0
            return 0;
7454
0
        }
7455
0
        metrics_context.total_need_recycle_num++;
7456
0
        return 0;
7457
0
    };
7458
7459
1
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
7460
1
    metrics_context.report(true);
7461
1
    stream_metrics_context.report(true);
7462
1
    segment_metrics_context_.report(true);
7463
1
    tablet_metrics_context_.report(true);
7464
1
    return ret;
7465
1
}
7466
7467
// Scan and statistics partitions that need to be recycled
7468
0
int InstanceRecycler::scan_and_statistics_partitions() {
7469
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
7470
7471
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
7472
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
7473
0
    std::string part_key0;
7474
0
    std::string part_key1;
7475
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7476
7477
0
    recycle_partition_key(part_key_info0, &part_key0);
7478
0
    recycle_partition_key(part_key_info1, &part_key1);
7479
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
7480
0
        RecyclePartitionPB part_pb;
7481
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
7482
0
            return 0;
7483
0
        }
7484
0
        int64_t current_time = ::time(nullptr);
7485
0
        if (current_time <
7486
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
7487
0
            return 0;
7488
0
        }
7489
        // decode partition_id
7490
0
        auto k1 = k;
7491
0
        k1.remove_prefix(1);
7492
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7493
0
        decode_key(&k1, &out);
7494
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
7495
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
7496
        // Change state to RECYCLING
7497
0
        std::unique_ptr<Transaction> txn;
7498
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7499
0
        if (err != TxnErrorCode::TXN_OK) {
7500
0
            return 0;
7501
0
        }
7502
0
        std::string val;
7503
0
        err = txn->get(k, &val);
7504
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7505
0
            return 0;
7506
0
        }
7507
0
        if (err != TxnErrorCode::TXN_OK) {
7508
0
            return 0;
7509
0
        }
7510
0
        part_pb.Clear();
7511
0
        if (!part_pb.ParseFromString(val)) {
7512
0
            return 0;
7513
0
        }
7514
        // Partitions with PREPARED state MUST have no data
7515
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
7516
0
        int ret = 0;
7517
0
        for (int64_t index_id : part_pb.index_id()) {
7518
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
7519
0
                                            partition_id, is_empty_tablet) != 0) {
7520
0
                ret = 0;
7521
0
            }
7522
0
        }
7523
0
        metrics_context.total_need_recycle_num++;
7524
0
        return ret;
7525
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_
7526
7527
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
7528
0
    metrics_context.report(true);
7529
0
    segment_metrics_context_.report(true);
7530
0
    tablet_metrics_context_.report(true);
7531
0
    return ret;
7532
0
}
7533
7534
// Scan and statistics rowsets that need to be recycled
7535
0
int InstanceRecycler::scan_and_statistics_rowsets() {
7536
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
7537
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
7538
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
7539
0
    std::string recyc_rs_key0;
7540
0
    std::string recyc_rs_key1;
7541
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
7542
0
                recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
7543
0
       int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7544
7545
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
7546
0
        RecycleRowsetPB rowset;
7547
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7548
0
            return 0;
7549
0
        }
7550
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
7551
0
        int64_t current_time = ::time(nullptr);
7552
0
        if (current_time <
7553
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
7554
0
            return 0;
7555
0
        }
7556
7557
0
        if (!rowset.has_type()) {
7558
0
            if (!rowset.has_resource_id()) [[unlikely]] {
7559
0
                return 0;
7560
0
            }
7561
0
            if (rowset.resource_id().empty()) [[unlikely]] {
7562
0
                return 0;
7563
0
            }
7564
0
            metrics_context.total_need_recycle_num++;
7565
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7566
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
7567
0
            segment_metrics_context_.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7568
0
            return 0;
7569
0
        }
7570
7571
0
        if(!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled()) {
7572
0
            return 0;
7573
0
        }
7574
7575
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
7576
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
7577
0
                return 0;
7578
0
            }
7579
0
        }
7580
0
        metrics_context.total_need_recycle_num++;
7581
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
7582
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
7583
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
7584
0
        return 0;
7585
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_
7586
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
7587
0
    metrics_context.report(true);
7588
0
    segment_metrics_context_.report(true);
7589
0
    return ret;
7590
0
}
7591
7592
// Scan and statistics tmp_rowsets that need to be recycled
7593
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
7594
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
7595
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
7596
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
7597
0
    std::string tmp_rs_key0;
7598
0
    std::string tmp_rs_key1;
7599
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
7600
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
7601
7602
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7603
7604
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
7605
0
        doris::RowsetMetaCloudPB rowset;
7606
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7607
0
            return 0;
7608
0
        }
7609
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
7610
0
        int64_t current_time = ::time(nullptr);
7611
0
        if (current_time < expiration) {
7612
0
            return 0;
7613
0
        }
7614
7615
0
        DCHECK_GT(rowset.txn_id(), 0)
7616
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
7617
7618
0
        if(!rowset.has_is_recycled() || !rowset.is_recycled()) {
7619
0
            return 0;
7620
0
        }
7621
7622
0
        if (!rowset.has_resource_id()) {
7623
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
7624
0
                return 0;
7625
0
            }
7626
0
            return 0;
7627
0
        }
7628
7629
0
        metrics_context.total_need_recycle_num++;
7630
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
7631
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
7632
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
7633
0
        return 0;
7634
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_
7635
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
7636
0
    metrics_context.report(true);
7637
0
    segment_metrics_context_.report(true);
7638
0
    return ret;
7639
0
}
7640
7641
// Scan and statistics abort_timeout_txn that need to be recycled
7642
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
7643
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
7644
7645
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
7646
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7647
0
    std::string begin_txn_running_key;
7648
0
    std::string end_txn_running_key;
7649
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
7650
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
7651
7652
0
    int64_t current_time =
7653
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7654
7655
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
7656
0
                                               std::string_view k, std::string_view v) -> int {
7657
0
        std::unique_ptr<Transaction> txn;
7658
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7659
0
        if (err != TxnErrorCode::TXN_OK) {
7660
0
            return 0;
7661
0
        }
7662
0
        std::string_view k1 = k;
7663
0
        k1.remove_prefix(1);
7664
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7665
0
        if (decode_key(&k1, &out) != 0) {
7666
0
            return 0;
7667
0
        }
7668
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7669
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7670
        // Update txn_info
7671
0
        std::string txn_inf_key, txn_inf_val;
7672
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
7673
0
        err = txn->get(txn_inf_key, &txn_inf_val);
7674
0
        if (err != TxnErrorCode::TXN_OK) {
7675
0
            return 0;
7676
0
        }
7677
0
        TxnInfoPB txn_info;
7678
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
7679
0
            return 0;
7680
0
        }
7681
7682
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
7683
0
            TxnRunningPB txn_running_pb;
7684
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7685
0
                return 0;
7686
0
            }
7687
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7688
0
                return 0;
7689
0
            }
7690
0
            metrics_context.total_need_recycle_num++;
7691
0
        }
7692
0
        return 0;
7693
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_
7694
7695
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key, std::move(handle_abort_timeout_txn_kv));
7696
0
    metrics_context.report(true);
7697
0
    return ret;
7698
0
}
7699
7700
// Scan and statistics expired_txn_label that need to be recycled
7701
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
7702
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
7703
7704
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7705
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7706
0
    std::string begin_recycle_txn_key;
7707
0
    std::string end_recycle_txn_key;
7708
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7709
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7710
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7711
0
    int64_t current_time_ms =
7712
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7713
7714
    // for calculate the total num or bytes of recyled objects
7715
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
7716
0
        RecycleTxnPB recycle_txn_pb;
7717
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7718
0
            return 0;
7719
0
        }
7720
0
        if ((config::force_immediate_recycle) ||
7721
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7722
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7723
0
             current_time_ms)) {
7724
0
            metrics_context.total_need_recycle_num++;
7725
0
        }
7726
0
        return 0;
7727
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_
7728
7729
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key, std::move(handle_expired_txn_label_kv));
7730
0
    metrics_context.report(true);
7731
0
    return ret;
7732
0
}
7733
7734
// Scan and statistics copy_jobs that need to be recycled
7735
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
7736
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
7737
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7738
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7739
0
    std::string key0;
7740
0
    std::string key1;
7741
0
    copy_job_key(key_info0, &key0);
7742
0
    copy_job_key(key_info1, &key1);
7743
7744
    // for calculate the total num or bytes of recyled objects
7745
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
7746
0
        CopyJobPB copy_job;
7747
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7748
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7749
0
            return 0;
7750
0
        }
7751
7752
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7753
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
7754
0
                int64_t current_time =
7755
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7756
0
                if (copy_job.finish_time_ms() > 0) {
7757
0
                    if (!config::force_immediate_recycle &&
7758
0
                        current_time < copy_job.finish_time_ms() +
7759
0
                                               config::copy_job_max_retention_second * 1000) {
7760
0
                        return 0;
7761
0
                    }
7762
0
                } else {
7763
0
                    if (!config::force_immediate_recycle &&
7764
0
                        current_time < copy_job.start_time_ms() +
7765
0
                                               config::copy_job_max_retention_second * 1000) {
7766
0
                        return 0;
7767
0
                    }
7768
0
                }
7769
0
            }
7770
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7771
0
            int64_t current_time =
7772
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7773
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7774
0
                return 0;
7775
0
            }
7776
0
        }
7777
0
        metrics_context.total_need_recycle_num++;
7778
0
        return 0;
7779
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_
7780
7781
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7782
0
    metrics_context.report(true);
7783
0
    return ret;
7784
0
}
7785
7786
// Scan and statistics stage that need to be recycled
7787
0
int InstanceRecycler::scan_and_statistics_stage() {
7788
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
7789
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7790
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7791
0
    std::string key0 = recycle_stage_key(key_info0);
7792
0
    std::string key1 = recycle_stage_key(key_info1);
7793
7794
    // for calculate the total num or bytes of recyled objects
7795
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
7796
0
                                                        std::string_view v) -> int {
7797
0
        RecycleStagePB recycle_stage;
7798
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7799
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7800
0
            return 0;
7801
0
        }
7802
7803
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
7804
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7805
0
            LOG(WARNING) << "invalid idx: " << idx;
7806
0
            return 0;
7807
0
        }
7808
7809
0
        std::shared_ptr<StorageVaultAccessor> accessor;
7810
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7811
0
                [&] {
7812
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7813
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7814
0
                    if (!s3_conf) {
7815
0
                        return 0;
7816
0
                    }
7817
7818
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7819
0
                    std::shared_ptr<S3Accessor> s3_accessor;
7820
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7821
0
                    if (ret != 0) {
7822
0
                        return 0;
7823
0
                    }
7824
7825
0
                    accessor = std::move(s3_accessor);
7826
0
                    return 0;
7827
0
                }(),
7828
0
                "recycle_stage:get_accessor", &accessor);
7829
7830
0
        if (ret != 0) {
7831
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7832
0
            return 0;
7833
0
        }
7834
7835
0
        metrics_context.total_need_recycle_num++;
7836
0
        return 0;
7837
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_
7838
7839
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7840
0
    metrics_context.report(true);
7841
0
    return ret;
7842
0
}
7843
7844
// Scan and statistics expired_stage_objects that need to be recycled
7845
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
7846
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7847
7848
    // for calculate the total num or bytes of recyled objects
7849
0
    auto scan_and_statistics = [&metrics_context, this]() {
7850
0
        for (const auto& stage : instance_info_.stages()) {
7851
0
            if (stopped()) {
7852
0
                break;
7853
0
            }
7854
0
            if (stage.type() == StagePB::EXTERNAL) {
7855
0
                continue;
7856
0
            }
7857
0
            int idx = stoi(stage.obj_info().id());
7858
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
7859
0
                continue;
7860
0
            }
7861
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
7862
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7863
0
            if (!s3_conf) {
7864
0
                continue;
7865
0
            }
7866
0
            s3_conf->prefix = stage.obj_info().prefix();
7867
0
            std::shared_ptr<S3Accessor> accessor;
7868
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
7869
0
            if (ret1 != 0) {
7870
0
                continue;
7871
0
            }
7872
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7873
0
                continue;
7874
0
            }
7875
0
            metrics_context.total_need_recycle_num++;
7876
0
        }
7877
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
7878
7879
0
    scan_and_statistics();
7880
0
    metrics_context.report(true);
7881
0
    return 0;
7882
0
}
7883
7884
// Scan and statistics versions that need to be recycled
7885
0
int InstanceRecycler::scan_and_statistics_versions() {
7886
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
7887
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
7888
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
7889
7890
0
    int64_t last_scanned_table_id = 0;
7891
0
    bool is_recycled = false; // Is last scanned kv recycled
7892
    // for calculate the total num or bytes of recyled objects
7893
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
7894
0
                                       std::string_view k, std::string_view) {
7895
0
        auto k1 = k;
7896
0
        k1.remove_prefix(1);
7897
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
7898
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7899
0
        decode_key(&k1, &out);
7900
0
        DCHECK_EQ(out.size(), 6) << k;
7901
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
7902
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
7903
0
            metrics_context.total_need_recycle_num +=
7904
0
                    is_recycled; // Version kv of this table has been recycled
7905
0
            return 0;
7906
0
        }
7907
0
        last_scanned_table_id = table_id;
7908
0
        is_recycled = false;
7909
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
7910
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
7911
0
        std::unique_ptr<Transaction> txn;
7912
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7913
0
        if (err != TxnErrorCode::TXN_OK) {
7914
0
            return 0;
7915
0
        }
7916
0
        std::unique_ptr<RangeGetIterator> iter;
7917
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
7918
0
        if (err != TxnErrorCode::TXN_OK) {
7919
0
            return 0;
7920
0
        }
7921
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
7922
0
            return 0;
7923
0
        }
7924
0
        metrics_context.total_need_recycle_num++;
7925
0
        is_recycled = true;
7926
0
        return 0;
7927
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_
7928
7929
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
7930
0
    metrics_context.report(true);
7931
0
    return ret;
7932
0
}
7933
7934
// Scan and statistics restore jobs that need to be recycled
7935
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
7936
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
7937
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
7938
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
7939
0
    std::string restore_job_key0;
7940
0
    std::string restore_job_key1;
7941
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
7942
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
7943
7944
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7945
7946
    // for calculate the total num or bytes of recyled objects
7947
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
7948
0
        RestoreJobCloudPB restore_job_pb;
7949
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
7950
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
7951
0
            return 0;
7952
0
        }
7953
0
        int64_t expiration =
7954
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
7955
0
        int64_t current_time = ::time(nullptr);
7956
0
        if (current_time < expiration) { // not expired
7957
0
            return 0;
7958
0
        }
7959
0
        metrics_context.total_need_recycle_num++;
7960
0
        if(restore_job_pb.need_recycle_data()) {
7961
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
7962
0
        }
7963
0
        return 0;
7964
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_
7965
7966
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
7967
0
    metrics_context.report(true);
7968
0
    return ret;
7969
0
}
7970
7971
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
7972
3
    if (!should_recycle_versioned_keys()) {
7973
0
        return;
7974
0
    }
7975
7976
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
7977
7978
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
7979
3
    if (recycle_checker.init() != 0) {
7980
0
        return;
7981
0
    }
7982
7983
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
7984
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
7985
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
7986
7987
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
7988
8
    for (; iter->valid(); iter->next()) {
7989
5
        OperationLogPB operation_log;
7990
5
        if (!iter->parse_value(&operation_log)) {
7991
0
            continue;
7992
0
        }
7993
7994
5
        std::string_view key = iter->key();
7995
5
        Versionstamp log_versionstamp;
7996
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
7997
0
            continue;
7998
0
        }
7999
8000
5
        OperationLogReferenceInfo ref_info;
8001
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
8002
5
                                         &ref_info)) {
8003
4
            metrics_context.total_need_recycle_num++;
8004
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
8005
4
        }
8006
5
    }
8007
8008
3
    metrics_context.report(true);
8009
3
}
8010
8011
int InstanceRecycler::classify_rowset_task_by_ref_count(
8012
60
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
8013
60
    constexpr int MAX_RETRY = 10;
8014
60
    const auto& rowset_meta = task.rowset_meta;
8015
60
    int64_t tablet_id = rowset_meta.tablet_id();
8016
60
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
8017
60
    std::string_view reference_instance_id = instance_id_;
8018
60
    if (rowset_meta.has_reference_instance_id()) {
8019
5
        reference_instance_id = rowset_meta.reference_instance_id();
8020
5
    }
8021
8022
61
    for (int i = 0; i < MAX_RETRY; ++i) {
8023
61
        std::unique_ptr<Transaction> txn;
8024
61
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8025
61
        if (err != TxnErrorCode::TXN_OK) {
8026
0
            LOG_WARNING("failed to create txn when classifying rowset task")
8027
0
                    .tag("instance_id", instance_id_)
8028
0
                    .tag("tablet_id", tablet_id)
8029
0
                    .tag("rowset_id", rowset_id)
8030
0
                    .tag("err", err);
8031
0
            return -1;
8032
0
        }
8033
8034
61
        std::string rowset_ref_count_key =
8035
61
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
8036
61
        task.rowset_ref_count_key = rowset_ref_count_key;
8037
8038
61
        int64_t ref_count = 0;
8039
61
        {
8040
61
            std::string value;
8041
61
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
8042
61
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
8043
0
                ref_count = 1;
8044
61
            } else if (err != TxnErrorCode::TXN_OK) {
8045
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
8046
0
                        .tag("instance_id", instance_id_)
8047
0
                        .tag("tablet_id", tablet_id)
8048
0
                        .tag("rowset_id", rowset_id)
8049
0
                        .tag("err", err);
8050
0
                return -1;
8051
61
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
8052
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
8053
0
                        .tag("instance_id", instance_id_)
8054
0
                        .tag("tablet_id", tablet_id)
8055
0
                        .tag("rowset_id", rowset_id)
8056
0
                        .tag("value", hex(value));
8057
0
                return -1;
8058
0
            }
8059
61
        }
8060
8061
61
        if (ref_count > 1) {
8062
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
8063
12
            txn->atomic_add(rowset_ref_count_key, -1);
8064
12
            LOG_INFO("decrease rowset data ref count in classification phase")
8065
12
                    .tag("instance_id", instance_id_)
8066
12
                    .tag("tablet_id", tablet_id)
8067
12
                    .tag("rowset_id", rowset_id)
8068
12
                    .tag("ref_count", ref_count - 1)
8069
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
8070
8071
12
            if (!task.recycle_rowset_key.empty()) {
8072
0
                txn->remove(task.recycle_rowset_key);
8073
0
                LOG_INFO("remove recycle rowset key in classification phase")
8074
0
                        .tag("key", hex(task.recycle_rowset_key));
8075
0
            }
8076
12
            if (!task.non_versioned_rowset_key.empty()) {
8077
12
                txn->remove(task.non_versioned_rowset_key);
8078
12
                LOG_INFO("remove non versioned rowset key in classification phase")
8079
12
                        .tag("key", hex(task.non_versioned_rowset_key));
8080
12
            }
8081
8082
12
            err = txn->commit();
8083
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
8084
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
8085
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
8086
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
8087
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
8088
1
                continue;
8089
11
            } else if (err != TxnErrorCode::TXN_OK) {
8090
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
8091
0
                        .tag("instance_id", instance_id_)
8092
0
                        .tag("tablet_id", tablet_id)
8093
0
                        .tag("rowset_id", rowset_id)
8094
0
                        .tag("err", err);
8095
0
                return -1;
8096
0
            }
8097
11
            return 1; // handled, not added to batch delete
8098
49
        } else {
8099
            // ref_count == 1: Add to batch delete plan without modifying any KV.
8100
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
8101
49
            LOG_INFO("add rowset to batch delete plan")
8102
49
                    .tag("instance_id", instance_id_)
8103
49
                    .tag("tablet_id", tablet_id)
8104
49
                    .tag("rowset_id", rowset_id)
8105
49
                    .tag("resource_id", rowset_meta.resource_id())
8106
49
                    .tag("ref_count", ref_count);
8107
8108
49
            batch_delete_tasks.push_back(std::move(task));
8109
49
            return 0; // added to batch delete
8110
49
        }
8111
61
    }
8112
8113
0
    LOG_WARNING("failed to classify rowset task after retry")
8114
0
            .tag("instance_id", instance_id_)
8115
0
            .tag("tablet_id", tablet_id)
8116
0
            .tag("rowset_id", rowset_id)
8117
0
            .tag("retry", MAX_RETRY);
8118
0
    return -1;
8119
60
}
8120
8121
10
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
8122
10
    int ret = 0;
8123
49
    for (const auto& task : tasks) {
8124
49
        int64_t tablet_id = task.rowset_meta.tablet_id();
8125
49
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
8126
8127
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
8128
        // so we don't need to call it again here.
8129
8130
        // Remove all metadata keys in one transaction
8131
49
        std::unique_ptr<Transaction> txn;
8132
49
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8133
49
        if (err != TxnErrorCode::TXN_OK) {
8134
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
8135
0
                    .tag("instance_id", instance_id_)
8136
0
                    .tag("tablet_id", tablet_id)
8137
0
                    .tag("rowset_id", rowset_id)
8138
0
                    .tag("err", err);
8139
0
            ret = -1;
8140
0
            continue;
8141
0
        }
8142
8143
49
        std::string_view reference_instance_id = instance_id_;
8144
49
        if (task.rowset_meta.has_reference_instance_id()) {
8145
5
            reference_instance_id = task.rowset_meta.reference_instance_id();
8146
5
        }
8147
8148
49
        txn->remove(task.rowset_ref_count_key);
8149
49
        LOG_INFO("delete rowset data ref count key in cleanup phase")
8150
49
                .tag("instance_id", instance_id_)
8151
49
                .tag("tablet_id", tablet_id)
8152
49
                .tag("rowset_id", rowset_id)
8153
49
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
8154
8155
49
        std::string dbm_start_key =
8156
49
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
8157
49
        std::string dbm_end_key = meta_delete_bitmap_key(
8158
49
                {reference_instance_id, tablet_id, rowset_id,
8159
49
                 std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
8160
49
        txn->remove(dbm_start_key, dbm_end_key);
8161
49
        LOG_INFO("remove delete bitmap kv in cleanup phase")
8162
49
                .tag("instance_id", instance_id_)
8163
49
                .tag("tablet_id", tablet_id)
8164
49
                .tag("rowset_id", rowset_id)
8165
49
                .tag("begin", hex(dbm_start_key))
8166
49
                .tag("end", hex(dbm_end_key));
8167
8168
49
        std::string versioned_dbm_start_key =
8169
49
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
8170
49
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
8171
49
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
8172
49
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
8173
49
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
8174
49
                .tag("instance_id", instance_id_)
8175
49
                .tag("tablet_id", tablet_id)
8176
49
                .tag("rowset_id", rowset_id)
8177
49
                .tag("begin", hex(versioned_dbm_start_key))
8178
49
                .tag("end", hex(versioned_dbm_end_key));
8179
8180
        // Remove versioned meta rowset key
8181
49
        if (!task.versioned_rowset_key.empty()) {
8182
49
            versioned::document_remove<RowsetMetaCloudPB>(
8183
49
                txn.get(), task.versioned_rowset_key, task.versionstamp);
8184
49
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
8185
49
                    .tag("instance_id", instance_id_)
8186
49
                    .tag("tablet_id", tablet_id)
8187
49
                    .tag("rowset_id", rowset_id)
8188
49
                    .tag("key_prefix", hex(task.versioned_rowset_key));
8189
49
        }
8190
8191
49
        if (!task.non_versioned_rowset_key.empty()) {
8192
49
            txn->remove(task.non_versioned_rowset_key);
8193
49
            LOG_INFO("remove non versioned rowset key in cleanup phase")
8194
49
                    .tag("instance_id", instance_id_)
8195
49
                    .tag("tablet_id", tablet_id)
8196
49
                    .tag("rowset_id", rowset_id)
8197
49
                    .tag("key", hex(task.non_versioned_rowset_key));
8198
49
        }
8199
8200
        // Remove recycle_rowset_key last to ensure retry safety:
8201
        // if cleanup fails, this key remains and triggers next round retry.
8202
49
        if (!task.recycle_rowset_key.empty()) {
8203
0
            txn->remove(task.recycle_rowset_key);
8204
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
8205
0
                    .tag("instance_id", instance_id_)
8206
0
                    .tag("tablet_id", tablet_id)
8207
0
                    .tag("rowset_id", rowset_id)
8208
0
                    .tag("key", hex(task.recycle_rowset_key));
8209
0
        }
8210
8211
49
        err = txn->commit();
8212
49
        if (err != TxnErrorCode::TXN_OK) {
8213
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
8214
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
8215
0
                    .tag("instance_id", instance_id_)
8216
0
                    .tag("tablet_id", tablet_id)
8217
0
                    .tag("rowset_id", rowset_id)
8218
0
                    .tag("err", err);
8219
0
            ret = -1;
8220
0
            continue;
8221
0
        }
8222
8223
49
        LOG_INFO("cleanup rowset metadata success")
8224
49
                .tag("instance_id", instance_id_)
8225
49
                .tag("tablet_id", tablet_id)
8226
49
                .tag("rowset_id", rowset_id);
8227
49
    }
8228
10
    return ret;
8229
10
}
8230
8231
} // namespace doris::cloud