Coverage Report

Created: 2026-08-15 23:31

/root/doris/cloud/src/recycler/recycler.cpp
Line
Count
Source (jump to first uncovered line)
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "recycler/recycler.h"
19
20
#include <brpc/builtin_service.pb.h>
21
#include <brpc/server.h>
22
#include <butil/endpoint.h>
23
#include <butil/strings/string_split.h>
24
#include <bvar/status.h>
25
#include <gen_cpp/cloud.pb.h>
26
#include <gen_cpp/olap_file.pb.h>
27
28
#include <algorithm>
29
#include <atomic>
30
#include <chrono>
31
#include <cstddef>
32
#include <cstdint>
33
#include <cstdlib>
34
#include <deque>
35
#include <functional>
36
#include <initializer_list>
37
#include <memory>
38
#include <numeric>
39
#include <optional>
40
#include <random>
41
#include <string>
42
#include <string_view>
43
#include <thread>
44
#include <unordered_map>
45
#include <unordered_set>
46
#include <utility>
47
#include <variant>
48
49
#include "common/defer.h"
50
#include "common/stopwatch.h"
51
#include "meta-service/meta_service.h"
52
#include "meta-service/meta_service_helper.h"
53
#include "meta-service/meta_service_schema.h"
54
#include "meta-store/blob_message.h"
55
#include "meta-store/meta_reader.h"
56
#include "meta-store/txn_kv.h"
57
#include "meta-store/txn_kv_error.h"
58
#include "meta-store/versioned_value.h"
59
#include "recycler/checker.h"
60
#ifdef ENABLE_HDFS_STORAGE_VAULT
61
#include "recycler/hdfs_accessor.h"
62
#endif
63
#include "recycler/s3_accessor.h"
64
#include "recycler/storage_vault_accessor.h"
65
#ifdef UNIT_TEST
66
#include "../test/mock_accessor.h"
67
#endif
68
#include "common/bvars.h"
69
#include "common/config.h"
70
#include "common/encryption_util.h"
71
#include "common/logging.h"
72
#include "common/simple_thread_pool.h"
73
#include "common/util.h"
74
#include "cpp/sync_point.h"
75
#include "meta-store/codec.h"
76
#include "meta-store/document_message.h"
77
#include "meta-store/keys.h"
78
#include "recycler/recycler_service.h"
79
#include "recycler/sync_executor.h"
80
#include "recycler/util.h"
81
#include "snapshot/snapshot_manager_factory.h"
82
83
namespace doris::cloud {
84
85
using namespace std::chrono;
86
87
namespace {
88
89
0
int64_t packed_file_retry_sleep_ms() {
90
0
    const int64_t min_ms = std::max<int64_t>(0, config::packed_file_txn_retry_sleep_min_ms);
91
0
    const int64_t max_ms = std::max<int64_t>(min_ms, config::packed_file_txn_retry_sleep_max_ms);
92
0
    thread_local std::mt19937_64 gen(std::random_device {}());
93
0
    std::uniform_int_distribution<int64_t> dist(min_ms, max_ms);
94
0
    return dist(gen);
95
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_126packed_file_retry_sleep_msEv
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_126packed_file_retry_sleep_msEv
96
97
0
void sleep_for_packed_file_retry() {
98
0
    std::this_thread::sleep_for(std::chrono::milliseconds(packed_file_retry_sleep_ms()));
99
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_127sleep_for_packed_file_retryEv
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_127sleep_for_packed_file_retryEv
100
101
868k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
102
868k
    const auto& locations = rowset.packed_slice_locations();
103
868k
    auto it = locations.find(path);
104
868k
    return it != locations.end() && it->second.has_packed_file_path() &&
105
868k
           !it->second.packed_file_path().empty();
106
868k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
101
7
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
102
7
    const auto& locations = rowset.packed_slice_locations();
103
7
    auto it = locations.find(path);
104
7
    return it != locations.end() && it->second.has_packed_file_path() &&
105
7
           !it->second.packed_file_path().empty();
106
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
101
868k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
102
868k
    const auto& locations = rowset.packed_slice_locations();
103
868k
    auto it = locations.find(path);
104
868k
    return it != locations.end() && it->second.has_packed_file_path() &&
105
868k
           !it->second.packed_file_path().empty();
106
868k
}
107
108
void add_file_to_delete_if_not_packed(const doris::RowsetMetaCloudPB& rowset,
109
                                      const std::string& path,
110
867k
                                      std::vector<std::string>* file_paths) {
111
867k
    if (!is_packed_slice_path(rowset, path)) {
112
867k
        file_paths->push_back(path);
113
867k
    }
114
867k
}
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
867k
                                      std::vector<std::string>* file_paths) {
111
867k
    if (!is_packed_slice_path(rowset, path)) {
112
867k
        file_paths->push_back(path);
113
867k
    }
114
867k
}
115
116
37
bool filter_out_instance(const std::string& instance_id) {
117
37
    if (config::recycle_whitelist.empty()) {
118
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
119
35
               config::recycle_blacklist.end();
120
35
    }
121
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
122
2
           config::recycle_whitelist.end();
123
37
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_119filter_out_instanceERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_119filter_out_instanceERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
116
37
bool filter_out_instance(const std::string& instance_id) {
117
37
    if (config::recycle_whitelist.empty()) {
118
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
119
35
               config::recycle_blacklist.end();
120
35
    }
121
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
122
2
           config::recycle_whitelist.end();
123
37
}
124
125
} // namespace
126
127
// return 0 for success get a key, 1 for key not found, negative for error
128
0
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
129
0
    std::unique_ptr<Transaction> txn;
130
0
    TxnErrorCode err = txn_kv->create_txn(&txn);
131
0
    if (err != TxnErrorCode::TXN_OK) {
132
0
        return -1;
133
0
    }
134
0
    switch (txn->get(key, &val, true)) {
135
0
    case TxnErrorCode::TXN_OK:
136
0
        return 0;
137
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
138
0
        return 1;
139
0
    default:
140
0
        return -1;
141
0
    };
142
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
143
144
// 0 for success, negative for error
145
static int txn_get(TxnKv* txn_kv, std::string_view begin, std::string_view end,
146
375
                   std::unique_ptr<RangeGetIterator>& it) {
147
375
    std::unique_ptr<Transaction> txn;
148
375
    TxnErrorCode err = txn_kv->create_txn(&txn);
149
375
    if (err != TxnErrorCode::TXN_OK) {
150
0
        return -1;
151
0
    }
152
375
    switch (txn->get(begin, end, &it, true)) {
153
375
    case TxnErrorCode::TXN_OK:
154
375
        return 0;
155
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
156
0
        return 1;
157
0
    default:
158
0
        return -1;
159
375
    };
160
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
146
36
                   std::unique_ptr<RangeGetIterator>& it) {
147
36
    std::unique_ptr<Transaction> txn;
148
36
    TxnErrorCode err = txn_kv->create_txn(&txn);
149
36
    if (err != TxnErrorCode::TXN_OK) {
150
0
        return -1;
151
0
    }
152
36
    switch (txn->get(begin, end, &it, true)) {
153
36
    case TxnErrorCode::TXN_OK:
154
36
        return 0;
155
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
156
0
        return 1;
157
0
    default:
158
0
        return -1;
159
36
    };
160
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
146
339
                   std::unique_ptr<RangeGetIterator>& it) {
147
339
    std::unique_ptr<Transaction> txn;
148
339
    TxnErrorCode err = txn_kv->create_txn(&txn);
149
339
    if (err != TxnErrorCode::TXN_OK) {
150
0
        return -1;
151
0
    }
152
339
    switch (txn->get(begin, end, &it, true)) {
153
339
    case TxnErrorCode::TXN_OK:
154
339
        return 0;
155
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
156
0
        return 1;
157
0
    default:
158
0
        return -1;
159
339
    };
160
0
}
161
162
// return 0 for success otherwise error
163
10
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
164
10
    std::unique_ptr<Transaction> txn;
165
10
    TxnErrorCode err = txn_kv->create_txn(&txn);
166
10
    if (err != TxnErrorCode::TXN_OK) {
167
0
        return -1;
168
0
    }
169
18
    for (auto k : keys) {
170
18
        txn->remove(k);
171
18
    }
172
10
    switch (txn->commit()) {
173
10
    case TxnErrorCode::TXN_OK:
174
10
        return 0;
175
0
    case TxnErrorCode::TXN_CONFLICT:
176
0
        return -1;
177
0
    default:
178
0
        return -1;
179
10
    }
180
10
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
163
3
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
164
3
    std::unique_ptr<Transaction> txn;
165
3
    TxnErrorCode err = txn_kv->create_txn(&txn);
166
3
    if (err != TxnErrorCode::TXN_OK) {
167
0
        return -1;
168
0
    }
169
3
    for (auto k : keys) {
170
3
        txn->remove(k);
171
3
    }
172
3
    switch (txn->commit()) {
173
3
    case TxnErrorCode::TXN_OK:
174
3
        return 0;
175
0
    case TxnErrorCode::TXN_CONFLICT:
176
0
        return -1;
177
0
    default:
178
0
        return -1;
179
3
    }
180
3
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
163
7
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
164
7
    std::unique_ptr<Transaction> txn;
165
7
    TxnErrorCode err = txn_kv->create_txn(&txn);
166
7
    if (err != TxnErrorCode::TXN_OK) {
167
0
        return -1;
168
0
    }
169
15
    for (auto k : keys) {
170
15
        txn->remove(k);
171
15
    }
172
7
    switch (txn->commit()) {
173
7
    case TxnErrorCode::TXN_OK:
174
7
        return 0;
175
0
    case TxnErrorCode::TXN_CONFLICT:
176
0
        return -1;
177
0
    default:
178
0
        return -1;
179
7
    }
180
7
}
181
182
// return 0 for success otherwise error
183
80
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
184
80
    std::unique_ptr<Transaction> txn;
185
80
    TxnErrorCode err = txn_kv->create_txn(&txn);
186
80
    if (err != TxnErrorCode::TXN_OK) {
187
0
        return -1;
188
0
    }
189
106k
    for (auto& k : keys) {
190
106k
        txn->remove(k);
191
106k
    }
192
80
    switch (txn->commit()) {
193
80
    case TxnErrorCode::TXN_OK:
194
80
        return 0;
195
0
    case TxnErrorCode::TXN_CONFLICT:
196
0
        return -1;
197
0
    default:
198
0
        return -1;
199
80
    }
200
80
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
183
27
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
184
27
    std::unique_ptr<Transaction> txn;
185
27
    TxnErrorCode err = txn_kv->create_txn(&txn);
186
27
    if (err != TxnErrorCode::TXN_OK) {
187
0
        return -1;
188
0
    }
189
27
    for (auto& k : keys) {
190
17
        txn->remove(k);
191
17
    }
192
27
    switch (txn->commit()) {
193
27
    case TxnErrorCode::TXN_OK:
194
27
        return 0;
195
0
    case TxnErrorCode::TXN_CONFLICT:
196
0
        return -1;
197
0
    default:
198
0
        return -1;
199
27
    }
200
27
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
183
53
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
184
53
    std::unique_ptr<Transaction> txn;
185
53
    TxnErrorCode err = txn_kv->create_txn(&txn);
186
53
    if (err != TxnErrorCode::TXN_OK) {
187
0
        return -1;
188
0
    }
189
105k
    for (auto& k : keys) {
190
105k
        txn->remove(k);
191
105k
    }
192
53
    switch (txn->commit()) {
193
53
    case TxnErrorCode::TXN_OK:
194
53
        return 0;
195
0
    case TxnErrorCode::TXN_CONFLICT:
196
0
        return -1;
197
0
    default:
198
0
        return -1;
199
53
    }
200
53
}
201
202
// return 0 for success otherwise error
203
[[maybe_unused]] static int txn_remove(TxnKv* txn_kv, std::string_view begin,
204
106k
                                       std::string_view end) {
205
106k
    std::unique_ptr<Transaction> txn;
206
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
207
106k
    if (err != TxnErrorCode::TXN_OK) {
208
0
        return -1;
209
0
    }
210
106k
    txn->remove(begin, end);
211
106k
    switch (txn->commit()) {
212
106k
    case TxnErrorCode::TXN_OK:
213
106k
        return 0;
214
0
    case TxnErrorCode::TXN_CONFLICT:
215
0
        return -1;
216
0
    default:
217
0
        return -1;
218
106k
    }
219
106k
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
204
17
                                       std::string_view end) {
205
17
    std::unique_ptr<Transaction> txn;
206
17
    TxnErrorCode err = txn_kv->create_txn(&txn);
207
17
    if (err != TxnErrorCode::TXN_OK) {
208
0
        return -1;
209
0
    }
210
17
    txn->remove(begin, end);
211
17
    switch (txn->commit()) {
212
17
    case TxnErrorCode::TXN_OK:
213
17
        return 0;
214
0
    case TxnErrorCode::TXN_CONFLICT:
215
0
        return -1;
216
0
    default:
217
0
        return -1;
218
17
    }
219
17
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
204
106k
                                       std::string_view end) {
205
106k
    std::unique_ptr<Transaction> txn;
206
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
207
106k
    if (err != TxnErrorCode::TXN_OK) {
208
0
        return -1;
209
0
    }
210
106k
    txn->remove(begin, end);
211
106k
    switch (txn->commit()) {
212
106k
    case TxnErrorCode::TXN_OK:
213
106k
        return 0;
214
0
    case TxnErrorCode::TXN_CONFLICT:
215
0
        return -1;
216
0
    default:
217
0
        return -1;
218
106k
    }
219
106k
}
220
221
void scan_restore_job_rowset(
222
        Transaction* txn, const std::string& instance_id, int64_t tablet_id, MetaServiceCode& code,
223
        std::string& msg,
224
        std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>* restore_job_rs_metas);
225
226
static inline void check_recycle_task(const std::string& instance_id, const std::string& task_name,
227
                                      int64_t num_scanned, int64_t num_recycled,
228
55
                                      int64_t start_time) {
229
55
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
230
0
        int64_t cost =
231
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
232
0
        if (cost > config::recycle_task_threshold_seconds) {
233
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
234
0
                    .tag("instance_id", instance_id)
235
0
                    .tag("task", task_name)
236
0
                    .tag("num_scanned", num_scanned)
237
0
                    .tag("num_recycled", num_recycled);
238
0
        }
239
0
    }
240
55
    return;
241
55
}
recycler.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
228
4
                                      int64_t start_time) {
229
4
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
230
0
        int64_t cost =
231
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
232
0
        if (cost > config::recycle_task_threshold_seconds) {
233
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
234
0
                    .tag("instance_id", instance_id)
235
0
                    .tag("task", task_name)
236
0
                    .tag("num_scanned", num_scanned)
237
0
                    .tag("num_recycled", num_recycled);
238
0
        }
239
0
    }
240
4
    return;
241
4
}
recycler_test.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
228
51
                                      int64_t start_time) {
229
51
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
230
0
        int64_t cost =
231
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
232
0
        if (cost > config::recycle_task_threshold_seconds) {
233
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
234
0
                    .tag("instance_id", instance_id)
235
0
                    .tag("task", task_name)
236
0
                    .tag("num_scanned", num_scanned)
237
0
                    .tag("num_recycled", num_recycled);
238
0
        }
239
0
    }
240
51
    return;
241
51
}
242
243
6
Recycler::Recycler(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
244
6
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
245
246
6
    auto s3_producer_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
247
6
                                                               "s3_producer_pool");
248
6
    s3_producer_pool->start();
249
6
    auto recycle_tablet_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
250
6
                                                                  "recycle_tablet_pool");
251
6
    recycle_tablet_pool->start();
252
6
    auto group_recycle_function_pool = std::make_shared<SimpleThreadPool>(
253
6
            config::recycle_pool_parallelism, "group_recycle_function_pool");
254
6
    group_recycle_function_pool->start();
255
6
    _thread_pool_group =
256
6
            RecyclerThreadPoolGroup(std::move(s3_producer_pool), std::move(recycle_tablet_pool),
257
6
                                    std::move(group_recycle_function_pool));
258
259
6
    auto resource_mgr = std::make_shared<ResourceManager>(txn_kv_);
260
6
    txn_lazy_committer_ = std::make_shared<TxnLazyCommitter>(txn_kv_, std::move(resource_mgr));
261
6
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
262
6
}
263
264
6
Recycler::~Recycler() {
265
6
    if (!stopped()) {
266
0
        stop();
267
0
    }
268
6
}
269
270
5
void Recycler::instance_scanner_callback() {
271
    // sleep 60 seconds before scheduling for the launch procedure to complete:
272
    // some bad hdfs connection may cause some log to stdout stderr
273
    // which may pollute .out file and affect the script to check success
274
5
    std::this_thread::sleep_for(
275
5
            std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
276
1.36k
    while (!stopped()) {
277
1.36k
        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.36k
        } else {
300
1.36k
            LOG(WARNING) << "Skip recycler since enable_recycler is false";
301
1.36k
        }
302
1.36k
        {
303
1.36k
            std::unique_lock lock(mtx_);
304
1.36k
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
305
2.72k
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
305
2.72k
                               [&]() { return stopped(); });
306
1.36k
        }
307
1.36k
    }
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
50
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
316
50
                    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
149
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
527
528
    // Return 0 if success, 1 if schema kv not found, negative for error
529
    // For the same index_id, schema_version, res, since `get` is not completely atomic
530
    // one thread has not finished inserting, and another thread has not get the index_id and schema_version,
531
    // resulting in repeated addition and inaccuracy.
532
    // however, this approach can reduce the lock range and sacrifice a bit of meta repeated get to improve concurrency performance.
533
    // repeated addition does not affect correctness.
534
28.4k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
535
28.4k
        {
536
28.4k
            std::lock_guard lock(mtx_);
537
28.4k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
538
4.10k
                return 0;
539
4.10k
            }
540
24.3k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
541
24.3k
                it != inverted_index_id_map_.end()) {
542
18.1k
                res = it->second;
543
18.1k
                return 0;
544
18.1k
            }
545
24.3k
        }
546
        // Get schema from kv
547
        // TODO(plat1ko): Single flight
548
6.18k
        std::unique_ptr<Transaction> txn;
549
6.18k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
550
6.18k
        if (err != TxnErrorCode::TXN_OK) {
551
0
            LOG(WARNING) << "failed to create txn, err=" << err;
552
0
            return -1;
553
0
        }
554
6.18k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
555
6.18k
        ValueBuf val_buf;
556
6.18k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
557
6.18k
        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
5.68k
        doris::TabletSchemaCloudPB schema;
562
5.68k
        if (!parse_schema_value(val_buf, &schema)) {
563
0
            LOG(WARNING) << "malformed schema value, key=" << hex(schema_key);
564
0
            return -1;
565
0
        }
566
5.68k
        if (schema.index_size() > 0) {
567
4.04k
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
568
4.04k
            if (schema.has_inverted_index_storage_format()) {
569
4.04k
                index_format = schema.inverted_index_storage_format();
570
4.04k
            }
571
4.04k
            res.first = index_format;
572
4.04k
            res.second.reserve(schema.index_size());
573
10.1k
            for (auto& i : schema.index()) {
574
10.1k
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
575
10.1k
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
576
10.1k
                }
577
10.1k
            }
578
4.04k
        }
579
5.68k
        insert(index_id, schema_version, res);
580
5.68k
        return 0;
581
5.68k
    }
582
583
    // Empty `ids` means this schema has no inverted index
584
5.68k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
585
5.68k
        if (index_info.second.empty()) {
586
1.63k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
587
1.63k
            std::lock_guard lock(mtx_);
588
1.63k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
589
4.04k
        } else {
590
4.04k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
591
4.04k
            std::lock_guard lock(mtx_);
592
4.04k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
593
4.04k
        }
594
5.68k
    }
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
58.4k
        size_t operator()(const Key& key) const {
604
58.4k
            size_t seed = 0;
605
58.4k
            seed = std::hash<int64_t> {}(key.first);
606
58.4k
            seed = std::hash<int32_t> {}(key.second);
607
58.4k
            return seed;
608
58.4k
        }
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
150
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
627
150
    delete_bitmap_lock_white_list_->init();
628
150
    resource_mgr_->init();
629
630
150
    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
150
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
635
150
};
636
637
150
InstanceRecycler::~InstanceRecycler() = default;
638
639
128
int InstanceRecycler::init_obj_store_accessors() {
640
128
    for (const auto& obj_info : instance_info_.obj_info()) {
641
85
#ifdef UNIT_TEST
642
85
        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
85
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
659
85
    }
660
661
128
    return 0;
662
128
}
663
664
128
int InstanceRecycler::init_storage_vault_accessors() {
665
128
    if (instance_info_.resource_ids().empty()) {
666
121
        return 0;
667
121
    }
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
129
int InstanceRecycler::init() {
760
129
    if (instance_info_.status() == InstanceInfoPB::DELETED &&
761
129
        (instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING ||
762
4
         instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED)) {
763
1
        return 0;
764
1
    }
765
766
128
    int ret = init_obj_store_accessors();
767
128
    if (ret != 0) {
768
0
        return ret;
769
0
    }
770
771
128
    return init_storage_vault_accessors();
772
128
}
773
774
template <typename... Func>
775
119
auto task_wrapper(Func... funcs) -> std::function<int()> {
776
120
    return [funcs...]() {
777
120
        return [](std::initializer_list<int> ret_vals) {
778
120
            int i = 0;
779
140
            for (int ret : ret_vals) {
780
140
                if (ret != 0) {
781
0
                    i = ret;
782
0
                }
783
140
            }
784
120
            return i;
785
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
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
0
                    i = ret;
782
0
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
0
                    i = ret;
782
0
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
20
            for (int ret : ret_vals) {
780
20
                if (ret != 0) {
781
0
                    i = ret;
782
0
                }
783
20
            }
784
10
            return i;
785
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
0
                    i = ret;
782
0
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
0
                    i = ret;
782
0
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
0
                    i = ret;
782
0
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
20
            for (int ret : ret_vals) {
780
20
                if (ret != 0) {
781
0
                    i = ret;
782
0
                }
783
20
            }
784
10
            return i;
785
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
0
                    i = ret;
782
0
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
0
                    i = ret;
782
0
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
0
                    i = ret;
782
0
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
0
                    i = ret;
782
0
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
0
                    i = ret;
782
0
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
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
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
787
119
}
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
775
9
auto task_wrapper(Func... funcs) -> std::function<int()> {
776
9
    return [funcs...]() {
777
9
        return [](std::initializer_list<int> ret_vals) {
778
9
            int i = 0;
779
9
            for (int ret : ret_vals) {
780
9
                if (ret != 0) {
781
9
                    i = ret;
782
9
                }
783
9
            }
784
9
            return i;
785
9
        }({funcs()...});
786
9
    };
787
9
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
775
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
787
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
775
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
787
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
775
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
787
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
775
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
787
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
775
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
787
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
775
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
787
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
775
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
787
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
775
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
787
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
775
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
787
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
775
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
787
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
775
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
776
10
    return [funcs...]() {
777
10
        return [](std::initializer_list<int> ret_vals) {
778
10
            int i = 0;
779
10
            for (int ret : ret_vals) {
780
10
                if (ret != 0) {
781
10
                    i = ret;
782
10
                }
783
10
            }
784
10
            return i;
785
10
        }({funcs()...});
786
10
    };
787
10
}
788
789
11
int InstanceRecycler::do_recycle() {
790
11
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
791
11
    tablet_metrics_context_.reset();
792
11
    segment_metrics_context_.reset();
793
11
    DORIS_CLOUD_DEFER {
794
11
        tablet_metrics_context_.finish_report();
795
11
        segment_metrics_context_.finish_report();
796
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
793
11
    DORIS_CLOUD_DEFER {
794
11
        tablet_metrics_context_.finish_report();
795
11
        segment_metrics_context_.finish_report();
796
11
    };
797
11
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
798
1
        int res = recycle_cluster_snapshots();
799
1
        if (res != 0) {
800
0
            return -1;
801
0
        }
802
1
        return recycle_deleted_instance();
803
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
804
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
805
10
                                        fmt::format("instance id {}", instance_id_),
806
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
806
120
                                        [](int r) { return r != 0; });
807
10
        sync_executor
808
10
                .add(task_wrapper(
809
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
809
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
810
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
810
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
811
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
812
                                   // becase they may both recycle the same set of tablets
813
                        // recycle dropped table or idexes(mv, rollup)
814
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
814
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
815
                        // recycle dropped partitions
816
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
816
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
817
10
                .add(task_wrapper(
818
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
818
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
819
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
819
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
820
10
                .add(task_wrapper(
821
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
821
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
822
10
                .add(task_wrapper(
823
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
823
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
824
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
824
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
825
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
825
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
826
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
826
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
827
10
                .add(task_wrapper(
828
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
828
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
829
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
829
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
830
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
830
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
831
10
        bool finished = true;
832
10
        std::vector<int> rets = sync_executor.when_all(&finished);
833
120
        for (int ret : rets) {
834
120
            if (ret != 0) {
835
0
                return ret;
836
0
            }
837
120
        }
838
10
        return finished ? 0 : -1;
839
10
    } else {
840
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
841
0
                     << " instance_id=" << instance_id_;
842
0
        return -1;
843
0
    }
844
11
}
845
846
/**
847
* 1. delete all remote data
848
* 2. delete all kv
849
* 3. remove instance kv
850
*/
851
13
int InstanceRecycler::recycle_deleted_instance() {
852
13
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
853
854
13
    int ret = 0;
855
13
    auto start_time = steady_clock::now();
856
13
    const auto recycle_state = instance_info_.recycle_state();
857
858
13
    DORIS_CLOUD_DEFER {
859
13
        auto cost = duration<float>(steady_clock::now() - start_time).count();
860
13
        if (ret != 0) {
861
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
862
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
863
0
                         << "s, instance_id=" << instance_id_;
864
13
        } else if (recycle_state ==
865
13
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
866
4
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
867
4
                      << "s, instance_id=" << instance_id_;
868
9
        } else {
869
9
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
870
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
871
9
                      << "s, instance_id=" << instance_id_;
872
9
        }
873
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
858
13
    DORIS_CLOUD_DEFER {
859
13
        auto cost = duration<float>(steady_clock::now() - start_time).count();
860
13
        if (ret != 0) {
861
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
862
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
863
0
                         << "s, instance_id=" << instance_id_;
864
13
        } else if (recycle_state ==
865
13
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
866
4
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
867
4
                      << "s, instance_id=" << instance_id_;
868
9
        } else {
869
9
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
870
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
871
9
                      << "s, instance_id=" << instance_id_;
872
9
        }
873
13
    };
874
875
13
    switch (recycle_state) {
876
6
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING:
877
6
        ret = recycle_deleted_instance_data();
878
6
        break;
879
3
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING:
880
3
        ret = recycle_deleted_instance_metadata();
881
3
        break;
882
4
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED:
883
4
        ret = remove_instance_key();
884
4
        break;
885
0
    default:
886
0
        LOG_WARNING("invalid instance recycle state")
887
0
                .tag("instance_id", instance_id_)
888
0
                .tag("recycle_state", instance_info_.recycle_state());
889
0
        ret = -1;
890
0
        break;
891
13
    }
892
893
13
    return ret;
894
13
}
895
896
6
int InstanceRecycler::recycle_deleted_instance_data() {
897
6
    int ret = 0;
898
899
    // Step 1: Recycle tmp rowsets (contains ref count but txn is not committed)
900
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
901
6
        int res = recycle_tmp_rowsets();
902
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
903
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
904
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
905
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
906
            // and cannot be recycled.
907
0
            res = recycle_tmp_rowsets();
908
0
        }
909
6
        return res;
910
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
Line
Count
Source
900
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
901
6
        int res = recycle_tmp_rowsets();
902
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
903
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
904
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
905
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
906
            // and cannot be recycled.
907
0
            res = recycle_tmp_rowsets();
908
0
        }
909
6
        return res;
910
6
    };
911
912
6
    if (recycle_tmp_rowsets_with_mark_delete_enabled() != 0) {
913
0
        LOG_WARNING("failed to recycle tmp rowsets").tag("instance_id", instance_id_);
914
0
        return -1;
915
0
    }
916
917
    // Step 2: Recycle versioned rowsets in recycle space (already marked for deletion)
918
6
    if (recycle_versioned_rowsets() != 0) {
919
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
920
0
        return -1;
921
0
    }
922
923
    // Step 3: Recycle operation logs (can recycle logs not referenced by snapshots)
924
6
    if (recycle_operation_logs() != 0) {
925
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
926
0
        return -1;
927
0
    }
928
929
    // Step 4: Check if there are still cluster snapshots
930
6
    bool has_snapshots = false;
931
6
    if (has_cluster_snapshots(&has_snapshots) != 0) {
932
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
933
0
        return -1;
934
6
    } else if (has_snapshots) {
935
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
936
1
        return 0;
937
1
    }
938
939
5
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
940
5
                            instance_info().snapshot_switch_status() !=
941
1
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
942
5
    if (snapshot_enabled) {
943
1
        bool has_unrecycled_rowsets = false;
944
1
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
945
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
946
0
            return -1;
947
1
        } else if (has_unrecycled_rowsets) {
948
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
949
0
                    .tag("instance_id", instance_id_);
950
0
            return ret;
951
0
        }
952
4
    } else { // delete all remote data if snapshot is disabled
953
4
        for (auto& [_, accessor] : accessor_map_) {
954
4
            if (stopped()) {
955
0
                return ret;
956
0
            }
957
958
4
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
959
4
            int del_ret = accessor->delete_all();
960
4
            if (del_ret == 0) {
961
4
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
962
4
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
963
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
964
                // so the recycling has been successful.
965
0
                ret = -1;
966
0
            }
967
4
        }
968
969
4
        if (ret != 0) {
970
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
971
0
            return ret;
972
0
        }
973
4
    }
974
975
5
    if (update_instance_recycle_state(
976
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING,
977
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) != 0) {
978
0
        return -1;
979
0
    }
980
981
5
    return 0;
982
5
}
983
984
3
int InstanceRecycler::recycle_deleted_instance_metadata() {
985
    // Check successor instance, if exists, skip deleting kv because successor instance may still need the data in kv
986
3
    if (instance_info_.has_successor_instance_id() &&
987
3
        !instance_info_.successor_instance_id().empty()) {
988
0
        std::string key = instance_key(instance_info_.successor_instance_id());
989
0
        std::unique_ptr<Transaction> txn;
990
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
991
0
        if (err != TxnErrorCode::TXN_OK) {
992
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_
993
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
994
0
                         << " err=" << err;
995
0
            return -1;
996
0
        }
997
998
0
        std::string value;
999
0
        err = txn->get(key, &value);
1000
0
        if (err == TxnErrorCode::TXN_OK) {
1001
0
            LOG(INFO) << "instance successor instance is still exist, skip deleting kv,"
1002
0
                      << " instance_id=" << instance_id_
1003
0
                      << " successor_instance_id=" << instance_info_.successor_instance_id();
1004
0
            return 0;
1005
0
        } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1006
0
            LOG(WARNING) << "failed to get successor instance, instance_id=" << instance_id_
1007
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1008
0
                         << " err=" << err;
1009
0
            return -1;
1010
0
        }
1011
0
    }
1012
1013
    // delete all kv
1014
3
    std::unique_ptr<Transaction> txn;
1015
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1016
3
    if (err != TxnErrorCode::TXN_OK) {
1017
0
        LOG(WARNING) << "failed to create txn";
1018
0
        return -1;
1019
0
    }
1020
3
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
1021
    // delete kv before deleting objects to prevent the checker from misjudging data loss
1022
3
    std::string start_txn_key = txn_key_prefix(instance_id_);
1023
3
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
1024
3
    txn->remove(start_txn_key, end_txn_key);
1025
3
    std::string start_version_key = version_key_prefix(instance_id_);
1026
3
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
1027
3
    txn->remove(start_version_key, end_version_key);
1028
3
    std::string start_meta_key = meta_key_prefix(instance_id_);
1029
3
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
1030
3
    txn->remove(start_meta_key, end_meta_key);
1031
3
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
1032
3
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
1033
3
    txn->remove(start_recycle_key, end_recycle_key);
1034
3
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
1035
3
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1036
3
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
1037
3
    std::string start_copy_key = copy_key_prefix(instance_id_);
1038
3
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
1039
3
    txn->remove(start_copy_key, end_copy_key);
1040
    // should not remove job key range, because we need to reserve job recycle kv
1041
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
1042
3
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
1043
3
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1044
3
    txn->remove(start_job_tablet_key, end_job_tablet_key);
1045
3
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
1046
3
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
1047
3
    std::string start_vault_key = storage_vault_key(key_info0);
1048
3
    std::string end_vault_key = storage_vault_key(key_info1);
1049
3
    txn->remove(start_vault_key, end_vault_key);
1050
3
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
1051
3
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
1052
3
    txn->remove(versioned_version_key_start, versioned_version_key_end);
1053
3
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
1054
3
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
1055
3
    txn->remove(versioned_index_key_start, versioned_index_key_end);
1056
3
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
1057
3
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
1058
3
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
1059
3
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
1060
3
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
1061
3
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
1062
3
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
1063
3
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
1064
3
    txn->remove(versioned_data_key_start, versioned_data_key_end);
1065
3
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
1066
3
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
1067
3
    txn->remove(versioned_log_key_start, versioned_log_key_end);
1068
1069
    // Updating the recycle state also commits this transaction, making the metadata deletions
1070
    // and state transition atomic.
1071
3
    if (update_instance_recycle_state(
1072
3
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING,
1073
3
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED, txn.get()) != 0) {
1074
0
        return -1;
1075
0
    }
1076
1077
3
    return 0;
1078
3
}
1079
1080
4
int InstanceRecycler::remove_instance_key() {
1081
4
    std::unique_ptr<Transaction> txn;
1082
4
    std::string key = instance_key(instance_info_.instance_id());
1083
4
    std::string value;
1084
4
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1085
4
    if (err != TxnErrorCode::TXN_OK) {
1086
0
        LOG(WARNING) << "failed to create txn";
1087
0
        return -1;
1088
0
    }
1089
1090
4
    err = txn->get(key, &value);
1091
4
    if (err != TxnErrorCode::TXN_OK) {
1092
0
        LOG(WARNING) << "failed to get instance, instance_id=" << instance_info_.instance_id()
1093
0
                     << ", err=" << err;
1094
0
        return -1;
1095
0
    }
1096
1097
4
    InstanceInfoPB instance;
1098
4
    if (!instance.ParseFromString(value)) {
1099
0
        LOG(WARNING) << "malformed instance info, key=" << key;
1100
0
        return -1;
1101
0
    }
1102
1103
4
    if (instance.status() != InstanceInfoPB::DELETED) {
1104
0
        LOG(WARNING) << "failed to remove instance key, instance is not deleted, instance_id="
1105
0
                     << instance_id_ << ", status=" << instance.status();
1106
0
        return -1;
1107
0
    }
1108
1109
4
    if (instance.recycle_state() != INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1110
0
        LOG(WARNING) << "failed to remove instance key, invalid recycle state, instance_id="
1111
0
                     << instance_id_
1112
0
                     << ", current_state=" << InstanceRecycleState_Name(instance.recycle_state())
1113
0
                     << ", expected_state="
1114
0
                     << InstanceRecycleState_Name(INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1115
0
        return -1;
1116
0
    }
1117
1118
4
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1119
4
    txn->remove(key);
1120
4
    err = txn->commit();
1121
4
    if (err != TxnErrorCode::TXN_OK) {
1122
0
        LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
1123
0
                     << " err=" << err;
1124
0
        return -1;
1125
0
    }
1126
4
    return 0;
1127
4
}
1128
1129
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState expected_state,
1130
7
                                                    InstanceRecycleState target_state) {
1131
7
    std::unique_ptr<Transaction> txn;
1132
7
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1133
7
    if (err != TxnErrorCode::TXN_OK) {
1134
0
        LOG(WARNING) << "failed to create txn";
1135
0
        return -1;
1136
0
    }
1137
7
    return update_instance_recycle_state(expected_state, target_state, txn.get());
1138
7
}
1139
1140
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState current_state,
1141
                                                    InstanceRecycleState target_state,
1142
10
                                                    Transaction* txn) {
1143
10
    const bool valid_transition =
1144
10
            (current_state == INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING &&
1145
10
             target_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) ||
1146
10
            (current_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING &&
1147
4
             target_state == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1148
1149
10
    if (!valid_transition) {
1150
1
        LOG_WARNING("invalid instance recycled state transition")
1151
1
                .tag("instance_id", instance_id_)
1152
1
                .tag("current_state", InstanceRecycleState_Name(current_state))
1153
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1154
1
        return -1;
1155
1
    }
1156
1157
9
    std::string key = instance_key({instance_id_});
1158
9
    std::string value;
1159
9
    TxnErrorCode err = txn->get(key, &value);
1160
9
    if (err != TxnErrorCode::TXN_OK) {
1161
0
        LOG_WARNING("failed to get instance when updating instance recycled state")
1162
0
                .tag("instance_id", instance_id_)
1163
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1164
0
                .tag("target_state", InstanceRecycleState_Name(target_state))
1165
0
                .tag("err", err);
1166
0
        return -1;
1167
0
    }
1168
1169
9
    InstanceInfoPB instance;
1170
9
    if (!instance.ParseFromString(value)) {
1171
0
        LOG_WARNING("failed to parse InstanceInfoPB when updating instance recycled state")
1172
0
                .tag("instance_id", instance_id_)
1173
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1174
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1175
0
        return -1;
1176
0
    }
1177
9
    if (instance.status() != InstanceInfoPB::DELETED) {
1178
0
        LOG_WARNING("instance is not deleted when updating instance recycled state")
1179
0
                .tag("instance_id", instance_id_)
1180
0
                .tag("status", instance.status())
1181
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1182
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1183
0
        return -1;
1184
0
    }
1185
9
    if (instance.recycle_state() != current_state) {
1186
1
        LOG_WARNING("instance recycled state changed before update")
1187
1
                .tag("instance_id", instance_id_)
1188
1
                .tag("current_state", InstanceRecycleState_Name(instance.recycle_state()))
1189
1
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1190
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1191
1
        return -1;
1192
1
    }
1193
1194
8
    instance.set_recycle_state(target_state);
1195
8
    instance.set_recycle_state_update_time_ms(
1196
8
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count());
1197
8
    if (!instance.SerializeToString(&value)) {
1198
0
        LOG_WARNING("failed to serialize InstanceInfoPB when updating instance recycled state")
1199
0
                .tag("instance_id", instance_id_)
1200
0
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1201
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1202
0
        return -1;
1203
0
    }
1204
1205
8
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1206
8
    txn->put(key, value);
1207
8
    err = txn->commit();
1208
8
    if (err != TxnErrorCode::TXN_OK) {
1209
0
        LOG(WARNING) << "failed to commit fdb txn when updating instance recycled state, "
1210
0
                     << "instance_id=" << instance_id_ << ", err=" << err;
1211
0
        return -1;
1212
0
    }
1213
1214
8
    instance_info_.Swap(&instance);
1215
8
    LOG_INFO("updated instance recycled state")
1216
8
            .tag("instance_id", instance_id_)
1217
8
            .tag("recycle_state", InstanceRecycleState_Name(target_state));
1218
8
    return 0;
1219
8
}
1220
1221
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
1222
9
                                          bool* exists, PackedFileRecycleStats* stats) {
1223
9
    if (exists == nullptr) {
1224
0
        return -1;
1225
0
    }
1226
9
    *exists = false;
1227
1228
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
1229
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1230
9
    std::string scan_begin = begin;
1231
1232
9
    while (true) {
1233
9
        std::unique_ptr<RangeGetIterator> it_range;
1234
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
1235
9
        if (get_ret < 0) {
1236
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1237
0
                    .tag("instance_id", instance_id_)
1238
0
                    .tag("tablet_id", tablet_id)
1239
0
                    .tag("ret", get_ret);
1240
0
            return -1;
1241
0
        }
1242
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1243
6
            return 0;
1244
6
        }
1245
1246
3
        std::string last_key;
1247
3
        while (it_range->has_next()) {
1248
3
            auto [k, v] = it_range->next();
1249
3
            last_key.assign(k.data(), k.size());
1250
3
            doris::RowsetMetaCloudPB rowset_meta;
1251
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1252
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1253
0
                        .tag("instance_id", instance_id_)
1254
0
                        .tag("tablet_id", tablet_id)
1255
0
                        .tag("key", hex(k));
1256
0
                continue;
1257
0
            }
1258
3
            if (stats) {
1259
3
                ++stats->rowset_scan_count;
1260
3
            }
1261
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1262
3
                *exists = true;
1263
3
                return 0;
1264
3
            }
1265
3
        }
1266
1267
0
        if (!it_range->more()) {
1268
0
            return 0;
1269
0
        }
1270
1271
        // Continue scanning from the next key to keep each transaction short.
1272
0
        scan_begin = std::move(last_key);
1273
0
        scan_begin.push_back('\x00');
1274
0
    }
1275
9
}
1276
1277
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1278
                                                          const std::string& rowset_id,
1279
                                                          int64_t txn_id, bool* recycle_exists,
1280
11
                                                          bool* tmp_exists) {
1281
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1282
0
        return -1;
1283
0
    }
1284
11
    *recycle_exists = false;
1285
11
    *tmp_exists = false;
1286
1287
11
    if (txn_id <= 0) {
1288
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1289
0
                .tag("instance_id", instance_id_)
1290
0
                .tag("tablet_id", tablet_id)
1291
0
                .tag("rowset_id", rowset_id)
1292
0
                .tag("txn_id", txn_id);
1293
0
        return -1;
1294
0
    }
1295
1296
11
    std::unique_ptr<Transaction> txn;
1297
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1298
11
    if (err != TxnErrorCode::TXN_OK) {
1299
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1300
0
                .tag("instance_id", instance_id_)
1301
0
                .tag("tablet_id", tablet_id)
1302
0
                .tag("rowset_id", rowset_id)
1303
0
                .tag("txn_id", txn_id)
1304
0
                .tag("err", err);
1305
0
        return -1;
1306
0
    }
1307
1308
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1309
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1310
11
    if (ret == TxnErrorCode::TXN_OK) {
1311
1
        *recycle_exists = true;
1312
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1313
0
        LOG_WARNING("failed to check recycle rowset existence")
1314
0
                .tag("instance_id", instance_id_)
1315
0
                .tag("tablet_id", tablet_id)
1316
0
                .tag("rowset_id", rowset_id)
1317
0
                .tag("key", hex(recycle_key))
1318
0
                .tag("err", ret);
1319
0
        return -1;
1320
0
    }
1321
1322
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1323
11
    ret = key_exists(txn.get(), tmp_key, true);
1324
11
    if (ret == TxnErrorCode::TXN_OK) {
1325
1
        *tmp_exists = true;
1326
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1327
0
        LOG_WARNING("failed to check tmp rowset existence")
1328
0
                .tag("instance_id", instance_id_)
1329
0
                .tag("tablet_id", tablet_id)
1330
0
                .tag("txn_id", txn_id)
1331
0
                .tag("key", hex(tmp_key))
1332
0
                .tag("err", ret);
1333
0
        return -1;
1334
0
    }
1335
1336
11
    return 0;
1337
11
}
1338
1339
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1340
8
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1341
8
    if (!hint.empty()) {
1342
8
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1343
8
            return {hint, it->second};
1344
8
        }
1345
8
    }
1346
1347
0
    return {"", nullptr};
1348
8
}
1349
1350
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1351
                                               const std::string& packed_file_path,
1352
3
                                               PackedFileRecycleStats* stats) {
1353
3
    bool local_changed = false;
1354
3
    int64_t left_num = 0;
1355
3
    int64_t left_bytes = 0;
1356
3
    bool all_small_files_confirmed = true;
1357
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1358
1359
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1360
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1361
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1362
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1363
14
        LOG_INFO("packed slice correction status")
1364
14
                .tag("instance_id", instance_id_)
1365
14
                .tag("packed_file_path", packed_file_path)
1366
14
                .tag("small_file_path", file.path())
1367
14
                .tag("tablet_id", tablet_id)
1368
14
                .tag("rowset_id", rowset_id)
1369
14
                .tag("txn_id", txn_id)
1370
14
                .tag("size", file.size())
1371
14
                .tag("deleted", file.deleted())
1372
14
                .tag("corrected", file.corrected())
1373
14
                .tag("confirmed_this_round", confirmed_this_round);
1374
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
1359
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1360
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1361
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1362
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1363
14
        LOG_INFO("packed slice correction status")
1364
14
                .tag("instance_id", instance_id_)
1365
14
                .tag("packed_file_path", packed_file_path)
1366
14
                .tag("small_file_path", file.path())
1367
14
                .tag("tablet_id", tablet_id)
1368
14
                .tag("rowset_id", rowset_id)
1369
14
                .tag("txn_id", txn_id)
1370
14
                .tag("size", file.size())
1371
14
                .tag("deleted", file.deleted())
1372
14
                .tag("corrected", file.corrected())
1373
14
                .tag("confirmed_this_round", confirmed_this_round);
1374
14
    };
1375
1376
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1377
14
        auto* small_file = packed_info->mutable_slices(i);
1378
14
        if (small_file->deleted()) {
1379
3
            log_small_file_status(*small_file, small_file->corrected());
1380
3
            continue;
1381
3
        }
1382
1383
11
        if (small_file->corrected()) {
1384
0
            left_num++;
1385
0
            left_bytes += small_file->size();
1386
0
            log_small_file_status(*small_file, true);
1387
0
            continue;
1388
0
        }
1389
1390
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1391
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1392
0
                    .tag("instance_id", instance_id_)
1393
0
                    .tag("small_file_path", small_file->path())
1394
0
                    .tag("index", i);
1395
0
            return -1;
1396
0
        }
1397
1398
11
        int64_t tablet_id = small_file->tablet_id();
1399
11
        const std::string& rowset_id = small_file->rowset_id();
1400
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1401
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1402
0
                    .tag("instance_id", instance_id_)
1403
0
                    .tag("small_file_path", small_file->path())
1404
0
                    .tag("index", i)
1405
0
                    .tag("tablet_id", tablet_id)
1406
0
                    .tag("rowset_id", rowset_id)
1407
0
                    .tag("has_txn_id", small_file->has_txn_id())
1408
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1409
0
            return -1;
1410
0
        }
1411
11
        int64_t txn_id = small_file->txn_id();
1412
11
        bool recycle_exists = false;
1413
11
        bool tmp_exists = false;
1414
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1415
11
                                                &tmp_exists) != 0) {
1416
0
            return -1;
1417
0
        }
1418
1419
11
        bool small_file_confirmed = false;
1420
11
        if (tmp_exists) {
1421
1
            left_num++;
1422
1
            left_bytes += small_file->size();
1423
1
            small_file_confirmed = true;
1424
10
        } else if (recycle_exists) {
1425
1
            left_num++;
1426
1
            left_bytes += small_file->size();
1427
            // keep small_file_confirmed=false so the packed file remains uncorrected
1428
9
        } else {
1429
9
            bool rowset_exists = false;
1430
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1431
0
                return -1;
1432
0
            }
1433
1434
9
            if (!rowset_exists) {
1435
6
                if (!small_file->deleted()) {
1436
6
                    small_file->set_deleted(true);
1437
6
                    local_changed = true;
1438
6
                }
1439
6
                if (!small_file->corrected()) {
1440
6
                    small_file->set_corrected(true);
1441
6
                    local_changed = true;
1442
6
                }
1443
6
                small_file_confirmed = true;
1444
6
            } else {
1445
3
                left_num++;
1446
3
                left_bytes += small_file->size();
1447
3
                small_file_confirmed = true;
1448
3
            }
1449
9
        }
1450
1451
11
        if (!small_file_confirmed) {
1452
1
            all_small_files_confirmed = false;
1453
1
        }
1454
1455
11
        if (small_file->corrected() != small_file_confirmed) {
1456
4
            small_file->set_corrected(small_file_confirmed);
1457
4
            local_changed = true;
1458
4
        }
1459
1460
11
        log_small_file_status(*small_file, small_file_confirmed);
1461
11
    }
1462
1463
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1464
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1465
3
        local_changed = true;
1466
3
    }
1467
3
    if (packed_info->ref_cnt() != left_num) {
1468
3
        auto old_ref_cnt = packed_info->ref_cnt();
1469
3
        packed_info->set_ref_cnt(left_num);
1470
3
        LOG_INFO("corrected packed file ref count")
1471
3
                .tag("instance_id", instance_id_)
1472
3
                .tag("resource_id", packed_info->resource_id())
1473
3
                .tag("packed_file_path", packed_file_path)
1474
3
                .tag("old_ref_cnt", old_ref_cnt)
1475
3
                .tag("new_ref_cnt", left_num);
1476
3
        local_changed = true;
1477
3
    }
1478
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1479
2
        packed_info->set_corrected(all_small_files_confirmed);
1480
2
        local_changed = true;
1481
2
    }
1482
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1483
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1484
1
        local_changed = true;
1485
1
    }
1486
1487
3
    if (changed != nullptr) {
1488
3
        *changed = local_changed;
1489
3
    }
1490
3
    return 0;
1491
3
}
1492
1493
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1494
                                                 const std::string& packed_file_path,
1495
3
                                                 PackedFileRecycleStats* stats) {
1496
3
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1497
3
    bool correction_ok = false;
1498
3
    cloud::PackedFileInfoPB packed_info;
1499
1500
3
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1501
3
        if (stopped()) {
1502
0
            LOG_WARNING("recycler stopped before processing packed file")
1503
0
                    .tag("instance_id", instance_id_)
1504
0
                    .tag("packed_file_path", packed_file_path)
1505
0
                    .tag("attempt", attempt);
1506
0
            return -1;
1507
0
        }
1508
1509
3
        std::unique_ptr<Transaction> txn;
1510
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1511
3
        if (err != TxnErrorCode::TXN_OK) {
1512
0
            LOG_WARNING("failed to create txn when processing packed file")
1513
0
                    .tag("instance_id", instance_id_)
1514
0
                    .tag("packed_file_path", packed_file_path)
1515
0
                    .tag("attempt", attempt)
1516
0
                    .tag("err", err);
1517
0
            return -1;
1518
0
        }
1519
1520
3
        std::string packed_val;
1521
3
        err = txn->get(packed_key, &packed_val);
1522
3
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1523
0
            return 0;
1524
0
        }
1525
3
        if (err != TxnErrorCode::TXN_OK) {
1526
0
            LOG_WARNING("failed to get packed file kv")
1527
0
                    .tag("instance_id", instance_id_)
1528
0
                    .tag("packed_file_path", packed_file_path)
1529
0
                    .tag("attempt", attempt)
1530
0
                    .tag("err", err);
1531
0
            return -1;
1532
0
        }
1533
1534
3
        if (!packed_info.ParseFromString(packed_val)) {
1535
0
            LOG_WARNING("failed to parse packed file info")
1536
0
                    .tag("instance_id", instance_id_)
1537
0
                    .tag("packed_file_path", packed_file_path)
1538
0
                    .tag("attempt", attempt);
1539
0
            return -1;
1540
0
        }
1541
1542
3
        int64_t now_sec = ::time(nullptr);
1543
3
        bool corrected = packed_info.corrected();
1544
3
        bool due = config::force_immediate_recycle ||
1545
3
                   now_sec - packed_info.created_at_sec() >=
1546
3
                           config::packed_file_correction_delay_seconds;
1547
1548
3
        if (!corrected && due) {
1549
3
            bool changed = false;
1550
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1551
0
                LOG_WARNING("correct_packed_file_info failed")
1552
0
                        .tag("instance_id", instance_id_)
1553
0
                        .tag("packed_file_path", packed_file_path)
1554
0
                        .tag("attempt", attempt);
1555
0
                return -1;
1556
0
            }
1557
3
            if (changed) {
1558
3
                std::string updated;
1559
3
                if (!packed_info.SerializeToString(&updated)) {
1560
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1561
0
                            .tag("instance_id", instance_id_)
1562
0
                            .tag("packed_file_path", packed_file_path)
1563
0
                            .tag("attempt", attempt);
1564
0
                    return -1;
1565
0
                }
1566
3
                txn->put(packed_key, updated);
1567
3
                err = txn->commit();
1568
3
                if (err == TxnErrorCode::TXN_OK) {
1569
3
                    if (stats) {
1570
3
                        ++stats->num_corrected;
1571
3
                    }
1572
3
                } else {
1573
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1574
0
                        LOG_WARNING(
1575
0
                                "failed to commit correction for packed file due to conflict, "
1576
0
                                "retrying")
1577
0
                                .tag("instance_id", instance_id_)
1578
0
                                .tag("packed_file_path", packed_file_path)
1579
0
                                .tag("attempt", attempt);
1580
0
                        sleep_for_packed_file_retry();
1581
0
                        packed_info.Clear();
1582
0
                        continue;
1583
0
                    }
1584
0
                    LOG_WARNING("failed to commit correction for packed file")
1585
0
                            .tag("instance_id", instance_id_)
1586
0
                            .tag("packed_file_path", packed_file_path)
1587
0
                            .tag("attempt", attempt)
1588
0
                            .tag("err", err);
1589
0
                    return -1;
1590
0
                }
1591
3
            }
1592
3
        }
1593
1594
3
        correction_ok = true;
1595
3
        break;
1596
3
    }
1597
1598
3
    if (!correction_ok) {
1599
0
        return -1;
1600
0
    }
1601
1602
3
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1603
3
          packed_info.ref_cnt() == 0)) {
1604
2
        return 0;
1605
2
    }
1606
1607
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1608
0
        LOG_WARNING("packed file missing resource id when recycling")
1609
0
                .tag("instance_id", instance_id_)
1610
0
                .tag("packed_file_path", packed_file_path);
1611
0
        return -1;
1612
0
    }
1613
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1614
1
    if (!accessor) {
1615
0
        LOG_WARNING("no accessor available to delete packed file")
1616
0
                .tag("instance_id", instance_id_)
1617
0
                .tag("packed_file_path", packed_file_path)
1618
0
                .tag("resource_id", packed_info.resource_id());
1619
0
        return -1;
1620
0
    }
1621
1
    int del_ret = accessor->delete_file(packed_file_path);
1622
1
    if (del_ret != 0 && del_ret != 1) {
1623
0
        LOG_WARNING("failed to delete packed file")
1624
0
                .tag("instance_id", instance_id_)
1625
0
                .tag("packed_file_path", packed_file_path)
1626
0
                .tag("resource_id", resource_id)
1627
0
                .tag("ret", del_ret);
1628
0
        return -1;
1629
0
    }
1630
1
    if (del_ret == 1) {
1631
0
        LOG_INFO("packed file already removed")
1632
0
                .tag("instance_id", instance_id_)
1633
0
                .tag("packed_file_path", packed_file_path)
1634
0
                .tag("resource_id", resource_id);
1635
1
    } else {
1636
1
        LOG_INFO("deleted packed file")
1637
1
                .tag("instance_id", instance_id_)
1638
1
                .tag("packed_file_path", packed_file_path)
1639
1
                .tag("resource_id", resource_id);
1640
1
    }
1641
1642
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1643
1
        std::unique_ptr<Transaction> del_txn;
1644
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1645
1
        if (err != TxnErrorCode::TXN_OK) {
1646
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1647
0
                    .tag("instance_id", instance_id_)
1648
0
                    .tag("packed_file_path", packed_file_path)
1649
0
                    .tag("del_attempt", del_attempt)
1650
0
                    .tag("err", err);
1651
0
            return -1;
1652
0
        }
1653
1654
1
        std::string latest_val;
1655
1
        err = del_txn->get(packed_key, &latest_val);
1656
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1657
0
            return 0;
1658
0
        }
1659
1
        if (err != TxnErrorCode::TXN_OK) {
1660
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1661
0
                    .tag("instance_id", instance_id_)
1662
0
                    .tag("packed_file_path", packed_file_path)
1663
0
                    .tag("del_attempt", del_attempt)
1664
0
                    .tag("err", err);
1665
0
            return -1;
1666
0
        }
1667
1668
1
        cloud::PackedFileInfoPB latest_info;
1669
1
        if (!latest_info.ParseFromString(latest_val)) {
1670
0
            LOG_WARNING("failed to parse packed file info before removal")
1671
0
                    .tag("instance_id", instance_id_)
1672
0
                    .tag("packed_file_path", packed_file_path)
1673
0
                    .tag("del_attempt", del_attempt);
1674
0
            return -1;
1675
0
        }
1676
1677
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1678
1
              latest_info.ref_cnt() == 0)) {
1679
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1680
0
                    .tag("instance_id", instance_id_)
1681
0
                    .tag("packed_file_path", packed_file_path)
1682
0
                    .tag("del_attempt", del_attempt);
1683
0
            return 0;
1684
0
        }
1685
1686
1
        del_txn->remove(packed_key);
1687
1
        err = del_txn->commit();
1688
1
        if (err == TxnErrorCode::TXN_OK) {
1689
1
            if (stats) {
1690
1
                ++stats->num_deleted;
1691
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1692
1
                                        static_cast<int64_t>(latest_val.size());
1693
1
                if (del_ret == 0 || del_ret == 1) {
1694
1
                    ++stats->num_object_deleted;
1695
1
                    int64_t object_size = latest_info.total_slice_bytes();
1696
1
                    if (object_size <= 0) {
1697
0
                        object_size = packed_info.total_slice_bytes();
1698
0
                    }
1699
1
                    stats->bytes_object_deleted += object_size;
1700
1
                }
1701
1
            }
1702
1
            LOG_INFO("removed packed file metadata")
1703
1
                    .tag("instance_id", instance_id_)
1704
1
                    .tag("packed_file_path", packed_file_path);
1705
1
            return 0;
1706
1
        }
1707
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1708
0
            if (del_attempt >= max_retry_times) {
1709
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1710
0
                        .tag("instance_id", instance_id_)
1711
0
                        .tag("packed_file_path", packed_file_path)
1712
0
                        .tag("del_attempt", del_attempt);
1713
0
                return -1;
1714
0
            }
1715
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1716
0
                    .tag("instance_id", instance_id_)
1717
0
                    .tag("packed_file_path", packed_file_path)
1718
0
                    .tag("del_attempt", del_attempt);
1719
0
            sleep_for_packed_file_retry();
1720
0
            continue;
1721
0
        }
1722
0
        LOG_WARNING("failed to remove packed file kv")
1723
0
                .tag("instance_id", instance_id_)
1724
0
                .tag("packed_file_path", packed_file_path)
1725
0
                .tag("del_attempt", del_attempt)
1726
0
                .tag("err", err);
1727
0
        return -1;
1728
0
    }
1729
1730
0
    return -1;
1731
1
}
1732
1733
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view value,
1734
4
                                            PackedFileRecycleStats* stats, int* ret) {
1735
4
    if (stats) {
1736
4
        ++stats->num_scanned;
1737
4
    }
1738
4
    std::string packed_file_path;
1739
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1740
0
        LOG_WARNING("failed to decode packed file key")
1741
0
                .tag("instance_id", instance_id_)
1742
0
                .tag("key", hex(key));
1743
0
        if (stats) {
1744
0
            ++stats->num_failed;
1745
0
        }
1746
0
        if (ret) {
1747
0
            *ret = -1;
1748
0
        }
1749
0
        return 0;
1750
0
    }
1751
1752
4
    cloud::PackedFileInfoPB packed_info;
1753
4
    if (!packed_info.ParseFromArray(value.data(), value.size())) {
1754
0
        LOG_WARNING("failed to parse packed file info from scan")
1755
0
                .tag("instance_id", instance_id_)
1756
0
                .tag("packed_file_path", packed_file_path);
1757
0
        if (stats) {
1758
0
            ++stats->num_failed;
1759
0
        }
1760
0
        if (ret) {
1761
0
            *ret = -1;
1762
0
        }
1763
0
        return 0;
1764
0
    }
1765
1766
4
    const int64_t now_sec = ::time(nullptr);
1767
4
    const bool due =
1768
4
            config::force_immediate_recycle ||
1769
4
            now_sec - packed_info.created_at_sec() >= config::packed_file_correction_delay_seconds;
1770
4
    const bool need_correction = !packed_info.corrected() && due;
1771
4
    const bool need_recycle =
1772
4
            packed_info.state() == cloud::PackedFileInfoPB::RECYCLING && packed_info.ref_cnt() == 0;
1773
4
    if (!need_correction && !need_recycle) {
1774
1
        return 0;
1775
1
    }
1776
1777
3
    std::string packed_key(key);
1778
3
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1779
3
    if (process_ret != 0) {
1780
0
        if (stats) {
1781
0
            ++stats->num_failed;
1782
0
        }
1783
0
        if (ret) {
1784
0
            *ret = -1;
1785
0
        }
1786
0
    }
1787
3
    return 0;
1788
4
}
1789
1790
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1791
6.06k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1792
6.06k
    if (config::force_immediate_recycle) {
1793
15
        return 0L;
1794
15
    }
1795
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1796
6.05k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1797
6.05k
    int64_t retention_seconds = config::retention_seconds;
1798
6.05k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1799
4.74k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1800
4.74k
    }
1801
6.05k
    int64_t final_expiration = expiration + retention_seconds;
1802
6.05k
    if (*earlest_ts > final_expiration) {
1803
16
        *earlest_ts = final_expiration;
1804
16
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1805
16
    }
1806
6.05k
    return final_expiration;
1807
6.06k
}
1808
1809
int64_t calculate_partition_expired_time(
1810
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1811
11
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1812
11
    if (config::force_immediate_recycle) {
1813
5
        return 0L;
1814
5
    }
1815
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1816
6
                                                            : partition_meta_pb.creation_time();
1817
6
    int64_t retention_seconds = config::retention_seconds;
1818
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1819
6
        retention_seconds =
1820
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1821
6
    }
1822
6
    int64_t final_expiration = expiration + retention_seconds;
1823
6
    if (*earlest_ts > final_expiration) {
1824
2
        *earlest_ts = final_expiration;
1825
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1826
2
    }
1827
6
    return final_expiration;
1828
11
}
1829
1830
int64_t calculate_index_expired_time(const std::string& instance_id_,
1831
                                     const RecycleIndexPB& index_meta_pb,
1832
14
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1833
14
    if (config::force_immediate_recycle) {
1834
8
        return 0L;
1835
8
    }
1836
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1837
6
                                                        : index_meta_pb.creation_time();
1838
6
    int64_t retention_seconds = config::retention_seconds;
1839
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1840
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1841
6
    }
1842
6
    int64_t final_expiration = expiration + retention_seconds;
1843
6
    if (*earlest_ts > final_expiration) {
1844
2
        *earlest_ts = final_expiration;
1845
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1846
2
    }
1847
6
    return final_expiration;
1848
14
}
1849
1850
int64_t calculate_tmp_rowset_expired_time(
1851
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1852
53.0k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1853
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1854
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1855
    //  duration or timeout always < `retention_time` in practice.
1856
53.0k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1857
53.0k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1858
53.0k
                                 : tmp_rowset_meta_pb.creation_time();
1859
53.0k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1860
53.0k
    int64_t final_expiration = expiration + config::retention_seconds;
1861
53.0k
    if (*earlest_ts > final_expiration) {
1862
18
        *earlest_ts = final_expiration;
1863
18
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1864
18
    }
1865
53.0k
    return final_expiration;
1866
53.0k
}
1867
1868
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1869
30.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1870
30.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1871
30.0k
    if (*earlest_ts > final_expiration / 1000) {
1872
8
        *earlest_ts = final_expiration / 1000;
1873
8
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1874
8
    }
1875
30.0k
    return final_expiration;
1876
30.0k
}
1877
1878
int64_t calculate_restore_job_expired_time(
1879
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1880
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1881
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1882
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1883
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1884
        // final state, recycle immediately
1885
41
        return 0L;
1886
41
    }
1887
    // not final state, wait much longer than the FE's timeout(1 day)
1888
0
    int64_t last_modified_s =
1889
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1890
0
    int64_t expiration = restore_job.expired_at_s() > 0
1891
0
                                 ? last_modified_s + restore_job.expired_at_s()
1892
0
                                 : last_modified_s;
1893
0
    int64_t final_expiration = expiration + config::retention_seconds;
1894
0
    if (*earlest_ts > final_expiration) {
1895
0
        *earlest_ts = final_expiration;
1896
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1897
0
    }
1898
0
    return final_expiration;
1899
41
}
1900
1901
2
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1902
2
    AbortTxnRequest req;
1903
2
    TxnInfoPB txn_info;
1904
2
    MetaServiceCode code = MetaServiceCode::OK;
1905
2
    std::string msg;
1906
2
    std::stringstream ss;
1907
2
    std::unique_ptr<Transaction> txn;
1908
2
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1909
2
    if (err != TxnErrorCode::TXN_OK) {
1910
0
        LOG_WARNING("failed to create txn").tag("err", err);
1911
0
        return -1;
1912
0
    }
1913
1914
    // get txn index
1915
2
    TxnIndexPB txn_idx_pb;
1916
2
    auto index_key = txn_index_key({instance_id_, txn_id});
1917
2
    std::string index_val;
1918
2
    err = txn->get(index_key, &index_val);
1919
2
    if (err != TxnErrorCode::TXN_OK) {
1920
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1921
            // maybe recycled
1922
0
            LOG_INFO("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1923
0
                    .tag("key", hex(index_key))
1924
0
                    .tag("txn_id", txn_id);
1925
0
            return 0;
1926
0
        }
1927
0
        LOG_WARNING("failed to get txn index")
1928
0
                .tag("err", err)
1929
0
                .tag("key", hex(index_key))
1930
0
                .tag("txn_id", txn_id);
1931
0
        return -1;
1932
0
    }
1933
2
    if (!txn_idx_pb.ParseFromString(index_val)) {
1934
0
        LOG_WARNING("failed to parse txn index")
1935
0
                .tag("err", err)
1936
0
                .tag("key", hex(index_key))
1937
0
                .tag("txn_id", txn_id);
1938
0
        return -1;
1939
0
    }
1940
1941
2
    auto info_key = txn_info_key({instance_id_, txn_idx_pb.tablet_index().db_id(), txn_id});
1942
2
    std::string info_val;
1943
2
    err = txn->get(info_key, &info_val);
1944
2
    if (err != TxnErrorCode::TXN_OK) {
1945
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1946
            // maybe recycled
1947
0
            LOG_INFO("txn info not found, txn_id={} instance_id={}", txn_id, instance_id_)
1948
0
                    .tag("key", hex(info_key))
1949
0
                    .tag("txn_id", txn_id);
1950
0
            return 0;
1951
0
        }
1952
0
        LOG_WARNING("failed to get txn info")
1953
0
                .tag("err", err)
1954
0
                .tag("key", hex(info_key))
1955
0
                .tag("txn_id", txn_id);
1956
0
        return -1;
1957
0
    }
1958
2
    if (!txn_info.ParseFromString(info_val)) {
1959
0
        LOG_WARNING("failed to parse txn info")
1960
0
                .tag("err", err)
1961
0
                .tag("key", hex(info_key))
1962
0
                .tag("txn_id", txn_id);
1963
0
        return -1;
1964
0
    }
1965
1966
2
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
1967
0
        LOG_INFO("txn is not prepared status, txn_id={} status={}", txn_id, txn_info.status())
1968
0
                .tag("key", hex(info_key))
1969
0
                .tag("txn_id", txn_id);
1970
0
        return 0;
1971
0
    }
1972
1973
2
    req.set_txn_id(txn_id);
1974
1975
2
    LOG(INFO) << "begin abort txn for related rowset, txn_id=" << txn_id
1976
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString();
1977
1978
2
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
1979
2
    err = txn->commit();
1980
2
    if (err != TxnErrorCode::TXN_OK) {
1981
0
        code = cast_as<ErrCategory::COMMIT>(err);
1982
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
1983
0
        msg = ss.str();
1984
0
        return -1;
1985
0
    }
1986
1987
2
    LOG(INFO) << "finish abort txn for related rowset, txn_id=" << txn_id
1988
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString()
1989
2
              << " code=" << code << " msg=" << msg;
1990
1991
2
    return 0;
1992
2
}
1993
1994
4
int InstanceRecycler::abort_job_for_related_rowset(const RowsetMetaCloudPB& rowset_meta) {
1995
4
    FinishTabletJobRequest req;
1996
4
    FinishTabletJobResponse res;
1997
4
    req.set_action(FinishTabletJobRequest::ABORT);
1998
4
    MetaServiceCode code = MetaServiceCode::OK;
1999
4
    std::string msg;
2000
4
    std::stringstream ss;
2001
2002
4
    TabletIndexPB tablet_idx;
2003
4
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, rowset_meta.tablet_id(), tablet_idx);
2004
4
    if (ret == 1) {
2005
        // tablet maybe recycled, directly return 0
2006
1
        return 0;
2007
3
    } else if (ret != 0) {
2008
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << rowset_meta.tablet_id()
2009
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
2010
0
        return ret;
2011
0
    }
2012
2013
3
    std::unique_ptr<Transaction> txn;
2014
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2015
3
    if (err != TxnErrorCode::TXN_OK) {
2016
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
2017
0
        return -1;
2018
0
    }
2019
2020
3
    std::string job_key =
2021
3
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
2022
3
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
2023
3
    std::string job_val;
2024
3
    err = txn->get(job_key, &job_val);
2025
3
    if (err != TxnErrorCode::TXN_OK) {
2026
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2027
0
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
2028
0
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2029
0
            return 0;
2030
0
        }
2031
0
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
2032
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
2033
0
                     << " key=" << hex(job_key);
2034
0
        return -1;
2035
0
    }
2036
2037
3
    TabletJobInfoPB job_pb;
2038
3
    if (!job_pb.ParseFromString(job_val)) {
2039
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
2040
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2041
0
        return -1;
2042
0
    }
2043
2044
3
    std::string job_id {};
2045
3
    if (!job_pb.compaction().empty()) {
2046
2
        for (const auto& c : job_pb.compaction()) {
2047
2
            if (c.id() == rowset_meta.job_id()) {
2048
2
                job_id = c.id();
2049
2
                break;
2050
2
            }
2051
2
        }
2052
2
    } else if (job_pb.has_schema_change()) {
2053
1
        job_id = job_pb.schema_change().id();
2054
1
    }
2055
2056
3
    if (!job_id.empty() && rowset_meta.job_id() == job_id) {
2057
3
        LOG(INFO) << "begin to abort job for related rowset, job_id=" << rowset_meta.job_id()
2058
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
2059
3
        req.mutable_job()->CopyFrom(job_pb);
2060
3
        req.set_action(FinishTabletJobRequest::ABORT);
2061
3
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
2062
3
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
2063
3
                           ss);
2064
3
        if (code != MetaServiceCode::OK) {
2065
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
2066
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
2067
0
                         << " msg=" << msg;
2068
0
            return -1;
2069
0
        }
2070
3
        LOG(INFO) << "finish abort job for related rowset, job_id=" << rowset_meta.job_id()
2071
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
2072
3
                  << " code=" << code << " msg=" << msg;
2073
3
    } else {
2074
        // clang-format off
2075
0
        LOG(INFO) << "there is no job for related rowset, directly recycle rowset data"
2076
0
                  << ", instance_id=" << instance_id_ 
2077
0
                  << ", tablet_id=" << tablet_idx.tablet_id() 
2078
0
                  << ", job_id=" << job_id
2079
0
                  << ", rowset_id=" << rowset_meta.rowset_id_v2();
2080
        // clang-format on
2081
0
    }
2082
2083
3
    return 0;
2084
3
}
2085
2086
template <typename T>
2087
13
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2088
13
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2089
9
        return rowset_meta_pb.mutable_rowset_meta();
2090
9
    } else {
2091
9
        return &rowset_meta_pb;
2092
9
    }
2093
13
}
_ZN5doris5cloud19mutable_rowset_metaINS0_15RecycleRowsetPBEEEPNS_17RowsetMetaCloudPBERT_
Line
Count
Source
2087
4
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2088
4
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2089
4
        return rowset_meta_pb.mutable_rowset_meta();
2090
4
    } else {
2091
4
        return &rowset_meta_pb;
2092
4
    }
2093
4
}
_ZN5doris5cloud19mutable_rowset_metaINS_17RowsetMetaCloudPBEEEPS2_RT_
Line
Count
Source
2087
9
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2088
9
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2089
9
        return rowset_meta_pb.mutable_rowset_meta();
2090
9
    } else {
2091
9
        return &rowset_meta_pb;
2092
9
    }
2093
9
}
2094
2095
template <typename T>
2096
51
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2097
51
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2098
35
        return rowset_meta_pb.rowset_meta();
2099
35
    } else {
2100
35
        return rowset_meta_pb;
2101
35
    }
2102
51
}
_ZN5doris5cloud11rowset_metaINS0_15RecycleRowsetPBEEERKNS_17RowsetMetaCloudPBERKT_
Line
Count
Source
2096
16
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2097
16
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2098
16
        return rowset_meta_pb.rowset_meta();
2099
16
    } else {
2100
16
        return rowset_meta_pb;
2101
16
    }
2102
16
}
_ZN5doris5cloud11rowset_metaINS_17RowsetMetaCloudPBEEERKS2_RKT_
Line
Count
Source
2096
35
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2097
35
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2098
35
        return rowset_meta_pb.rowset_meta();
2099
35
    } else {
2100
35
        return rowset_meta_pb;
2101
35
    }
2102
35
}
2103
2104
struct DeferredRecycleAbortTask {
2105
    enum class Type : uint8_t {
2106
        TXN,
2107
        JOB,
2108
    };
2109
2110
    Type type = Type::TXN;
2111
    int64_t txn_id = 0;
2112
    int64_t tablet_id = 0;
2113
    int64_t start_version = 0;
2114
    int64_t end_version = 0;
2115
    std::string rowset_id;
2116
    std::string job_id;
2117
};
2118
2119
struct DeferredRecyclePrepareDeleteTask {
2120
    std::string key;
2121
    std::string resource_id;
2122
    std::string rowset_id;
2123
    int64_t tablet_id = 0;
2124
};
2125
2126
template <typename T>
2127
14
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
2128
14
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2129
4
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2130
0
            return std::nullopt;
2131
0
        }
2132
4
    }
2133
2134
4
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2135
4
    DeferredRecycleAbortTask task;
2136
4
    task.tablet_id = rs_meta.tablet_id();
2137
4
    task.start_version = rs_meta.start_version();
2138
4
    task.end_version = rs_meta.end_version();
2139
14
    if (rs_meta.has_load_id()) {
2140
4
        task.type = DeferredRecycleAbortTask::Type::TXN;
2141
4
        task.txn_id = rs_meta.txn_id();
2142
4
        return task;
2143
4
    }
2144
10
    if (rs_meta.has_job_id()) {
2145
6
        task.type = DeferredRecycleAbortTask::Type::JOB;
2146
6
        task.rowset_id = rs_meta.rowset_id_v2();
2147
6
        task.job_id = rs_meta.job_id();
2148
6
        return task;
2149
6
    }
2150
4
    return std::nullopt;
2151
10
}
_ZN5doris5cloud24make_deferred_abort_taskINS0_15RecycleRowsetPBEEESt8optionalINS0_24DeferredRecycleAbortTaskEERKT_
Line
Count
Source
2127
4
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
2128
4
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2129
4
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2130
0
            return std::nullopt;
2131
0
        }
2132
4
    }
2133
2134
4
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2135
4
    DeferredRecycleAbortTask task;
2136
4
    task.tablet_id = rs_meta.tablet_id();
2137
4
    task.start_version = rs_meta.start_version();
2138
4
    task.end_version = rs_meta.end_version();
2139
4
    if (rs_meta.has_load_id()) {
2140
2
        task.type = DeferredRecycleAbortTask::Type::TXN;
2141
2
        task.txn_id = rs_meta.txn_id();
2142
2
        return task;
2143
2
    }
2144
2
    if (rs_meta.has_job_id()) {
2145
2
        task.type = DeferredRecycleAbortTask::Type::JOB;
2146
2
        task.rowset_id = rs_meta.rowset_id_v2();
2147
2
        task.job_id = rs_meta.job_id();
2148
2
        return task;
2149
2
    }
2150
0
    return std::nullopt;
2151
2
}
_ZN5doris5cloud24make_deferred_abort_taskINS_17RowsetMetaCloudPBEEESt8optionalINS0_24DeferredRecycleAbortTaskEERKT_
Line
Count
Source
2127
10
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
2128
10
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2129
10
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2130
10
            return std::nullopt;
2131
10
        }
2132
10
    }
2133
2134
10
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2135
10
    DeferredRecycleAbortTask task;
2136
10
    task.tablet_id = rs_meta.tablet_id();
2137
10
    task.start_version = rs_meta.start_version();
2138
10
    task.end_version = rs_meta.end_version();
2139
10
    if (rs_meta.has_load_id()) {
2140
2
        task.type = DeferredRecycleAbortTask::Type::TXN;
2141
2
        task.txn_id = rs_meta.txn_id();
2142
2
        return task;
2143
2
    }
2144
8
    if (rs_meta.has_job_id()) {
2145
4
        task.type = DeferredRecycleAbortTask::Type::JOB;
2146
4
        task.rowset_id = rs_meta.rowset_id_v2();
2147
4
        task.job_id = rs_meta.job_id();
2148
4
        return task;
2149
4
    }
2150
4
    return std::nullopt;
2151
8
}
2152
2153
template <typename T>
2154
35
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
2155
35
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2156
35
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
2157
35
}
_ZN5doris5cloud28need_mark_rowset_as_recycledINS0_15RecycleRowsetPBEEEbRKT_
Line
Count
Source
2154
10
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
2155
10
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2156
10
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
2157
10
}
_ZN5doris5cloud28need_mark_rowset_as_recycledINS_17RowsetMetaCloudPBEEEbRKT_
Line
Count
Source
2154
25
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
2155
25
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2156
25
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
2157
25
}
2158
2159
template <typename T>
2160
int batch_mark_rowsets_as_recycled(TxnKv* txn_kv, const std::string& instance_id,
2161
11
                                   const std::vector<std::string>& keys) {
2162
11
    std::unique_ptr<Transaction> txn;
2163
11
    TxnErrorCode err = txn_kv->create_txn(&txn);
2164
11
    if (err != TxnErrorCode::TXN_OK) {
2165
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2166
0
        return -1;
2167
0
    }
2168
11
    std::vector<std::optional<std::string>> values;
2169
11
    err = txn->batch_get(&values, keys);
2170
11
    if (err != TxnErrorCode::TXN_OK) {
2171
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2172
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
2173
0
        return -1;
2174
0
    }
2175
11
    size_t total_keys = keys.size();
2176
24
    for (size_t i = 0; i < total_keys; i++) {
2177
13
        if (!values[i].has_value()) {
2178
            // has already been removed by commit_rowset
2179
0
            continue;
2180
0
        }
2181
13
        auto key = keys[i];
2182
13
        auto val = values[i].value();
2183
13
        T rowset_meta_pb;
2184
13
        if (!rowset_meta_pb.ParseFromString(val)) {
2185
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2186
0
                         << " key=" << hex(key);
2187
0
            return -1;
2188
0
        }
2189
13
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
2190
0
            continue;
2191
0
        }
2192
13
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2193
13
        val.clear();
2194
13
        rowset_meta_pb.SerializeToString(&val);
2195
13
        txn->put(key, val);
2196
13
    }
2197
11
    err = txn->commit();
2198
11
    if (err != TxnErrorCode::TXN_OK) {
2199
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2200
0
        return -1;
2201
0
    }
2202
2203
11
    return 0;
2204
11
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2161
4
                                   const std::vector<std::string>& keys) {
2162
4
    std::unique_ptr<Transaction> txn;
2163
4
    TxnErrorCode err = txn_kv->create_txn(&txn);
2164
4
    if (err != TxnErrorCode::TXN_OK) {
2165
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2166
0
        return -1;
2167
0
    }
2168
4
    std::vector<std::optional<std::string>> values;
2169
4
    err = txn->batch_get(&values, keys);
2170
4
    if (err != TxnErrorCode::TXN_OK) {
2171
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2172
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
2173
0
        return -1;
2174
0
    }
2175
4
    size_t total_keys = keys.size();
2176
8
    for (size_t i = 0; i < total_keys; i++) {
2177
4
        if (!values[i].has_value()) {
2178
            // has already been removed by commit_rowset
2179
0
            continue;
2180
0
        }
2181
4
        auto key = keys[i];
2182
4
        auto val = values[i].value();
2183
4
        T rowset_meta_pb;
2184
4
        if (!rowset_meta_pb.ParseFromString(val)) {
2185
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2186
0
                         << " key=" << hex(key);
2187
0
            return -1;
2188
0
        }
2189
4
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
2190
0
            continue;
2191
0
        }
2192
4
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2193
4
        val.clear();
2194
4
        rowset_meta_pb.SerializeToString(&val);
2195
4
        txn->put(key, val);
2196
4
    }
2197
4
    err = txn->commit();
2198
4
    if (err != TxnErrorCode::TXN_OK) {
2199
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2200
0
        return -1;
2201
0
    }
2202
2203
4
    return 0;
2204
4
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2161
7
                                   const std::vector<std::string>& keys) {
2162
7
    std::unique_ptr<Transaction> txn;
2163
7
    TxnErrorCode err = txn_kv->create_txn(&txn);
2164
7
    if (err != TxnErrorCode::TXN_OK) {
2165
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2166
0
        return -1;
2167
0
    }
2168
7
    std::vector<std::optional<std::string>> values;
2169
7
    err = txn->batch_get(&values, keys);
2170
7
    if (err != TxnErrorCode::TXN_OK) {
2171
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2172
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
2173
0
        return -1;
2174
0
    }
2175
7
    size_t total_keys = keys.size();
2176
16
    for (size_t i = 0; i < total_keys; i++) {
2177
9
        if (!values[i].has_value()) {
2178
            // has already been removed by commit_rowset
2179
0
            continue;
2180
0
        }
2181
9
        auto key = keys[i];
2182
9
        auto val = values[i].value();
2183
9
        T rowset_meta_pb;
2184
9
        if (!rowset_meta_pb.ParseFromString(val)) {
2185
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2186
0
                         << " key=" << hex(key);
2187
0
            return -1;
2188
0
        }
2189
9
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
2190
0
            continue;
2191
0
        }
2192
9
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2193
9
        val.clear();
2194
9
        rowset_meta_pb.SerializeToString(&val);
2195
9
        txn->put(key, val);
2196
9
    }
2197
7
    err = txn->commit();
2198
7
    if (err != TxnErrorCode::TXN_OK) {
2199
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2200
0
        return -1;
2201
0
    }
2202
2203
7
    return 0;
2204
7
}
2205
2206
template <typename T>
2207
int collect_deferred_abort_tasks(TxnKv* txn_kv, const std::string& instance_id,
2208
                                 const std::vector<std::string>& keys,
2209
                                 std::vector<DeferredRecycleAbortTask>* abort_tasks,
2210
5
                                 bool skip_base_version) {
2211
5
    constexpr size_t kAbortCheckBatchSize = 256;
2212
10
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2213
5
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2214
5
        std::unique_ptr<Transaction> txn;
2215
5
        TxnErrorCode err = txn_kv->create_txn(&txn);
2216
5
        if (err != TxnErrorCode::TXN_OK) {
2217
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2218
0
            return -1;
2219
0
        }
2220
10
        for (size_t idx = offset; idx < limit; ++idx) {
2221
5
            const std::string& key = keys[idx];
2222
5
            std::string val;
2223
5
            err = txn->get(key, &val);
2224
5
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2225
                // has already been removed
2226
0
                continue;
2227
0
            }
2228
5
            if (err != TxnErrorCode::TXN_OK) {
2229
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2230
0
                             << " key=" << hex(key);
2231
0
                return -1;
2232
0
            }
2233
5
            T rowset_meta_pb;
2234
5
            if (!rowset_meta_pb.ParseFromString(val)) {
2235
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2236
0
                             << " key=" << hex(key);
2237
0
                return -1;
2238
0
            }
2239
5
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2240
0
                continue;
2241
0
            }
2242
5
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2243
5
                abort_task.has_value()) {
2244
5
                abort_tasks->emplace_back(std::move(*abort_task));
2245
5
            }
2246
5
        }
2247
5
    }
2248
5
    return 0;
2249
5
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24DeferredRecycleAbortTaskESaISI_EEb
Line
Count
Source
2210
2
                                 bool skip_base_version) {
2211
2
    constexpr size_t kAbortCheckBatchSize = 256;
2212
4
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2213
2
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2214
2
        std::unique_ptr<Transaction> txn;
2215
2
        TxnErrorCode err = txn_kv->create_txn(&txn);
2216
2
        if (err != TxnErrorCode::TXN_OK) {
2217
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2218
0
            return -1;
2219
0
        }
2220
4
        for (size_t idx = offset; idx < limit; ++idx) {
2221
2
            const std::string& key = keys[idx];
2222
2
            std::string val;
2223
2
            err = txn->get(key, &val);
2224
2
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2225
                // has already been removed
2226
0
                continue;
2227
0
            }
2228
2
            if (err != TxnErrorCode::TXN_OK) {
2229
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2230
0
                             << " key=" << hex(key);
2231
0
                return -1;
2232
0
            }
2233
2
            T rowset_meta_pb;
2234
2
            if (!rowset_meta_pb.ParseFromString(val)) {
2235
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2236
0
                             << " key=" << hex(key);
2237
0
                return -1;
2238
0
            }
2239
2
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2240
0
                continue;
2241
0
            }
2242
2
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2243
2
                abort_task.has_value()) {
2244
2
                abort_tasks->emplace_back(std::move(*abort_task));
2245
2
            }
2246
2
        }
2247
2
    }
2248
2
    return 0;
2249
2
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24DeferredRecycleAbortTaskESaISI_EEb
Line
Count
Source
2210
3
                                 bool skip_base_version) {
2211
3
    constexpr size_t kAbortCheckBatchSize = 256;
2212
6
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2213
3
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2214
3
        std::unique_ptr<Transaction> txn;
2215
3
        TxnErrorCode err = txn_kv->create_txn(&txn);
2216
3
        if (err != TxnErrorCode::TXN_OK) {
2217
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2218
0
            return -1;
2219
0
        }
2220
6
        for (size_t idx = offset; idx < limit; ++idx) {
2221
3
            const std::string& key = keys[idx];
2222
3
            std::string val;
2223
3
            err = txn->get(key, &val);
2224
3
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2225
                // has already been removed
2226
0
                continue;
2227
0
            }
2228
3
            if (err != TxnErrorCode::TXN_OK) {
2229
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2230
0
                             << " key=" << hex(key);
2231
0
                return -1;
2232
0
            }
2233
3
            T rowset_meta_pb;
2234
3
            if (!rowset_meta_pb.ParseFromString(val)) {
2235
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2236
0
                             << " key=" << hex(key);
2237
0
                return -1;
2238
0
            }
2239
3
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2240
0
                continue;
2241
0
            }
2242
3
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2243
3
                abort_task.has_value()) {
2244
3
                abort_tasks->emplace_back(std::move(*abort_task));
2245
3
            }
2246
3
        }
2247
3
    }
2248
3
    return 0;
2249
3
}
2250
2251
template <typename T>
2252
int InstanceRecycler::batch_abort_txn_or_job_for_recycle(const std::vector<std::string>& keys,
2253
5
                                                         bool skip_base_version) {
2254
5
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2255
5
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2256
5
                                        skip_base_version) != 0) {
2257
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2258
0
        return -1;
2259
0
    }
2260
5
    for (const auto& abort_task : abort_tasks) {
2261
5
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2262
5
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2263
5
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2264
5
        int abort_ret = 0;
2265
5
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2266
2
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2267
3
        } else {
2268
3
            RowsetMetaCloudPB rowset_meta;
2269
3
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2270
3
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2271
3
            rowset_meta.set_job_id(abort_task.job_id);
2272
3
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2273
3
        }
2274
5
        if (abort_ret != 0) {
2275
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2276
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2277
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2278
0
            return abort_ret;
2279
0
        }
2280
5
    }
2281
5
    return 0;
2282
5
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEb
Line
Count
Source
2253
2
                                                         bool skip_base_version) {
2254
2
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2255
2
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2256
2
                                        skip_base_version) != 0) {
2257
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2258
0
        return -1;
2259
0
    }
2260
2
    for (const auto& abort_task : abort_tasks) {
2261
2
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2262
2
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2263
2
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2264
2
        int abort_ret = 0;
2265
2
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2266
1
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2267
1
        } else {
2268
1
            RowsetMetaCloudPB rowset_meta;
2269
1
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2270
1
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2271
1
            rowset_meta.set_job_id(abort_task.job_id);
2272
1
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2273
1
        }
2274
2
        if (abort_ret != 0) {
2275
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2276
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2277
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2278
0
            return abort_ret;
2279
0
        }
2280
2
    }
2281
2
    return 0;
2282
2
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEb
Line
Count
Source
2253
3
                                                         bool skip_base_version) {
2254
3
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2255
3
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2256
3
                                        skip_base_version) != 0) {
2257
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2258
0
        return -1;
2259
0
    }
2260
3
    for (const auto& abort_task : abort_tasks) {
2261
3
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2262
3
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2263
3
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2264
3
        int abort_ret = 0;
2265
3
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2266
1
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2267
2
        } else {
2268
2
            RowsetMetaCloudPB rowset_meta;
2269
2
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2270
2
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2271
2
            rowset_meta.set_job_id(abort_task.job_id);
2272
2
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2273
2
        }
2274
3
        if (abort_ret != 0) {
2275
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2276
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2277
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2278
0
            return abort_ret;
2279
0
        }
2280
3
    }
2281
3
    return 0;
2282
3
}
2283
2284
int collect_prepare_delete_tasks(TxnKv* txn_kv, const std::string& instance_id,
2285
                                 const std::vector<std::string>& keys,
2286
0
                                 std::vector<DeferredRecyclePrepareDeleteTask>* delete_tasks) {
2287
0
    constexpr size_t kPrepareCheckBatchSize = 256;
2288
0
    for (size_t offset = 0; offset < keys.size(); offset += kPrepareCheckBatchSize) {
2289
0
        size_t limit = std::min(keys.size(), offset + kPrepareCheckBatchSize);
2290
0
        std::unique_ptr<Transaction> txn;
2291
0
        TxnErrorCode err = txn_kv->create_txn(&txn);
2292
0
        if (err != TxnErrorCode::TXN_OK) {
2293
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2294
0
            return -1;
2295
0
        }
2296
0
        for (size_t idx = offset; idx < limit; ++idx) {
2297
0
            const std::string& key = keys[idx];
2298
0
            std::string val;
2299
0
            err = txn->get(key, &val);
2300
0
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2301
                // has already been removed
2302
0
                continue;
2303
0
            }
2304
0
            if (err != TxnErrorCode::TXN_OK) {
2305
0
                LOG(WARNING) << "failed to get recycle rowset, instance_id=" << instance_id
2306
0
                             << " key=" << hex(key);
2307
0
                return -1;
2308
0
            }
2309
0
            RecycleRowsetPB rowset;
2310
0
            if (!rowset.ParseFromString(val)) {
2311
0
                LOG(WARNING) << "failed to parse recycle rowset, instance_id=" << instance_id
2312
0
                             << " key=" << hex(key);
2313
0
                return -1;
2314
0
            }
2315
0
            if (rowset.type() != RecycleRowsetPB::PREPARE) {
2316
0
                continue;
2317
0
            }
2318
0
            const auto& rs_meta = rowset.rowset_meta();
2319
0
            delete_tasks->push_back(
2320
0
                    {key, rs_meta.resource_id(), rs_meta.rowset_id_v2(), rs_meta.tablet_id()});
2321
0
        }
2322
0
    }
2323
0
    return 0;
2324
0
}
2325
2326
1
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
2327
1
    const std::string task_name = "recycle_ref_rowsets";
2328
1
    *has_unrecycled_rowsets = false;
2329
2330
1
    std::string data_rowset_ref_count_key_start =
2331
1
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
2332
1
    std::string data_rowset_ref_count_key_end =
2333
1
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
2334
2335
1
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
2336
2337
1
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2338
1
    register_recycle_task(task_name, start_time);
2339
2340
1
    DORIS_CLOUD_DEFER {
2341
1
        unregister_recycle_task(task_name);
2342
1
        int64_t cost =
2343
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2344
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2345
1
                .tag("instance_id", instance_id_);
2346
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Line
Count
Source
2340
1
    DORIS_CLOUD_DEFER {
2341
1
        unregister_recycle_task(task_name);
2342
1
        int64_t cost =
2343
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2344
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2345
1
                .tag("instance_id", instance_id_);
2346
1
    };
2347
2348
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
2349
1
    std::set<int64_t> tablets_with_refs;
2350
1
    int64_t num_scanned = 0;
2351
2352
1
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
2353
0
        ++num_scanned;
2354
0
        int64_t tablet_id;
2355
0
        std::string rowset_id;
2356
0
        std::string_view key(k);
2357
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
2358
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
2359
0
            return 0; // Continue scanning
2360
0
        }
2361
2362
0
        tablets_with_refs.insert(tablet_id);
2363
0
        return 0;
2364
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
2365
2366
1
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
2367
1
                         std::move(scan_func)) != 0) {
2368
0
        LOG_WARNING("failed to scan data rowset ref count keys");
2369
0
        return -1;
2370
0
    }
2371
2372
1
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
2373
1
             tablets_with_refs.size(), num_scanned)
2374
1
            .tag("instance_id", instance_id_);
2375
2376
    // Phase 2: Recycle each tablet
2377
1
    int64_t num_recycled_tablets = 0;
2378
1
    for (int64_t tablet_id : tablets_with_refs) {
2379
0
        if (stopped()) {
2380
0
            LOG_INFO("recycler stopped, skip remaining tablets")
2381
0
                    .tag("instance_id", instance_id_)
2382
0
                    .tag("tablets_processed", num_recycled_tablets)
2383
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
2384
0
            break;
2385
0
        }
2386
2387
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
2388
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
2389
0
            LOG_WARNING("failed to recycle tablet")
2390
0
                    .tag("instance_id", instance_id_)
2391
0
                    .tag("tablet_id", tablet_id);
2392
0
            return -1;
2393
0
        }
2394
0
        ++num_recycled_tablets;
2395
0
    }
2396
2397
1
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
2398
1
            .tag("instance_id", instance_id_)
2399
1
            .tag("total_tablets", tablets_with_refs.size());
2400
2401
    // Phase 3: Scan again to check if any ref count keys still exist
2402
1
    std::unique_ptr<Transaction> txn;
2403
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2404
1
    if (err != TxnErrorCode::TXN_OK) {
2405
0
        LOG_WARNING("failed to create txn for final check")
2406
0
                .tag("instance_id", instance_id_)
2407
0
                .tag("err", err);
2408
0
        return -1;
2409
0
    }
2410
2411
1
    std::unique_ptr<RangeGetIterator> iter;
2412
1
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2413
1
    if (err != TxnErrorCode::TXN_OK) {
2414
0
        LOG_WARNING("failed to create range iterator for final check")
2415
0
                .tag("instance_id", instance_id_)
2416
0
                .tag("err", err);
2417
0
        return -1;
2418
0
    }
2419
2420
1
    *has_unrecycled_rowsets = iter->has_next();
2421
1
    if (*has_unrecycled_rowsets) {
2422
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2423
0
                .tag("instance_id", instance_id_);
2424
0
    }
2425
2426
1
    return 0;
2427
1
}
2428
2429
int InstanceRecycler::recycle_table_stream_offset_prefix(std::string prefix,
2430
6
                                                         RecyclerMetricsContext* metrics_context) {
2431
6
    std::string end = prefix;
2432
6
    end.push_back('\xff');
2433
6
    std::vector<std::string_view> keys;
2434
8
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2435
8
        keys.push_back(key);
2436
8
        return 0;
2437
8
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_1clESt17basic_string_viewIcS5_ESC_
Line
Count
Source
2434
2
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2435
2
        keys.push_back(key);
2436
2
        return 0;
2437
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_1clESt17basic_string_viewIcS5_ESC_
Line
Count
Source
2434
6
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2435
6
        keys.push_back(key);
2436
6
        return 0;
2437
6
    };
2438
6
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2439
4
        if (keys.empty()) {
2440
0
            return 0;
2441
0
        }
2442
4
        DORIS_CLOUD_DEFER {
2443
4
            keys.clear();
2444
4
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlvE_clEv
Line
Count
Source
2442
2
        DORIS_CLOUD_DEFER {
2443
2
            keys.clear();
2444
2
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlvE_clEv
Line
Count
Source
2442
2
        DORIS_CLOUD_DEFER {
2443
2
            keys.clear();
2444
2
        };
2445
4
        const size_t num_keys = keys.size();
2446
4
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2447
0
            LOG_WARNING("failed to delete table stream offsets")
2448
0
                    .tag("instance_id", instance_id_)
2449
0
                    .tag("num_keys", num_keys);
2450
0
            return -1;
2451
0
        }
2452
4
        metrics_context->total_recycled_num += num_keys;
2453
4
        metrics_context->report();
2454
4
        return 0;
2455
4
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2438
2
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2439
2
        if (keys.empty()) {
2440
0
            return 0;
2441
0
        }
2442
2
        DORIS_CLOUD_DEFER {
2443
2
            keys.clear();
2444
2
        };
2445
2
        const size_t num_keys = keys.size();
2446
2
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2447
0
            LOG_WARNING("failed to delete table stream offsets")
2448
0
                    .tag("instance_id", instance_id_)
2449
0
                    .tag("num_keys", num_keys);
2450
0
            return -1;
2451
0
        }
2452
2
        metrics_context->total_recycled_num += num_keys;
2453
2
        metrics_context->report();
2454
2
        return 0;
2455
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2438
2
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2439
2
        if (keys.empty()) {
2440
0
            return 0;
2441
0
        }
2442
2
        DORIS_CLOUD_DEFER {
2443
2
            keys.clear();
2444
2
        };
2445
2
        const size_t num_keys = keys.size();
2446
2
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2447
0
            LOG_WARNING("failed to delete table stream offsets")
2448
0
                    .tag("instance_id", instance_id_)
2449
0
                    .tag("num_keys", num_keys);
2450
0
            return -1;
2451
0
        }
2452
2
        metrics_context->total_recycled_num += num_keys;
2453
2
        metrics_context->report();
2454
2
        return 0;
2455
2
    };
2456
6
    return scan_and_recycle(std::move(prefix), end, std::move(collect_key), std::move(remove_keys));
2457
6
}
2458
2459
int InstanceRecycler::finalize_recycle_stream(int64_t stream_id,
2460
                                              const RecycleIndexPB& recycle_index,
2461
3
                                              std::string_view recycle_key) {
2462
3
    std::unique_ptr<Transaction> txn;
2463
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2464
3
    if (err != TxnErrorCode::TXN_OK) {
2465
0
        LOG_WARNING("failed to create transaction for final table stream cleanup")
2466
0
                .tag("instance_id", instance_id_)
2467
0
                .tag("stream_id", stream_id)
2468
0
                .tag("err", err);
2469
0
        return -1;
2470
0
    }
2471
2472
3
    std::string current_recycle_value;
2473
3
    err = txn->get(recycle_key, &current_recycle_value);
2474
3
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2475
0
        return 0;
2476
0
    }
2477
3
    if (err != TxnErrorCode::TXN_OK) {
2478
0
        LOG_WARNING("failed to read table stream recycle index")
2479
0
                .tag("instance_id", instance_id_)
2480
0
                .tag("stream_id", stream_id)
2481
0
                .tag("err", err);
2482
0
        return -1;
2483
0
    }
2484
3
    RecycleIndexPB current_recycle_index;
2485
3
    if (!current_recycle_index.ParseFromString(current_recycle_value) ||
2486
3
        current_recycle_index.state() != RecycleIndexPB::RECYCLING ||
2487
3
        current_recycle_index.object_type() != IndexObjectTypePB::TABLE_STREAM ||
2488
3
        current_recycle_index.db_id() != recycle_index.db_id() ||
2489
3
        current_recycle_index.table_id() != recycle_index.table_id() ||
2490
3
        current_recycle_index.stream_db_id() != recycle_index.stream_db_id()) {
2491
0
        LOG_WARNING("table stream recycle index changed during recycling")
2492
0
                .tag("instance_id", instance_id_)
2493
0
                .tag("stream_id", stream_id);
2494
0
        return -1;
2495
0
    }
2496
2497
3
    txn->remove(recycle_key);
2498
3
    err = txn->commit();
2499
3
    if (err != TxnErrorCode::TXN_OK) {
2500
0
        LOG_WARNING("failed to commit final table stream cleanup")
2501
0
                .tag("instance_id", instance_id_)
2502
0
                .tag("stream_id", stream_id)
2503
0
                .tag("err", err);
2504
0
        return -1;
2505
0
    }
2506
3
    return 0;
2507
3
}
2508
2509
int InstanceRecycler::recycle_stream(int64_t stream_id, const RecycleIndexPB& recycle_index,
2510
3
                                     std::string_view recycle_key) {
2511
3
    if (!recycle_index.has_db_id() || !recycle_index.has_stream_db_id()) {
2512
0
        LOG_WARNING("table stream recycle index is missing binding")
2513
0
                .tag("instance_id", instance_id_)
2514
0
                .tag("stream_id", stream_id);
2515
0
        return -1;
2516
0
    }
2517
2518
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stream");
2519
3
    DORIS_CLOUD_DEFER {
2520
3
        metrics_context.finish_report();
2521
3
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_streamElRKNS0_14RecycleIndexPBESt17basic_string_viewIcSt11char_traitsIcEEENK3$_0clEv
Line
Count
Source
2519
2
    DORIS_CLOUD_DEFER {
2520
2
        metrics_context.finish_report();
2521
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_streamElRKNS0_14RecycleIndexPBESt17basic_string_viewIcSt11char_traitsIcEEENK3$_0clEv
Line
Count
Source
2519
1
    DORIS_CLOUD_DEFER {
2520
1
        metrics_context.finish_report();
2521
1
    };
2522
3
    const std::string latest_offset_prefix = table_stream_offset_key_prefix(
2523
3
            instance_id_, recycle_index.db_id(), recycle_index.table_id(),
2524
3
            recycle_index.stream_db_id(), stream_id);
2525
3
    if (recycle_table_stream_offset_prefix(latest_offset_prefix, &metrics_context) != 0) {
2526
0
        return -1;
2527
0
    }
2528
3
    const std::string versioned_offset_prefix = versioned::table_stream_offset_key_prefix(
2529
3
            instance_id_, recycle_index.db_id(), recycle_index.table_id(),
2530
3
            recycle_index.stream_db_id(), stream_id);
2531
3
    if (recycle_table_stream_offset_prefix(versioned_offset_prefix, &metrics_context) != 0 ||
2532
3
        stopped()) {
2533
0
        return -1;
2534
0
    }
2535
3
    return finalize_recycle_stream(stream_id, recycle_index, recycle_key);
2536
3
}
2537
2538
int InstanceRecycler::recycle_partition_table_stream_offsets(
2539
        int64_t db_id, int64_t table_id, int64_t partition_id,
2540
10
        const google::protobuf::RepeatedPtrField<TableStreamIdentityPB>& table_streams) {
2541
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stream_partition_offsets");
2542
10
    DORIS_CLOUD_DEFER {
2543
10
        metrics_context.finish_report();
2544
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler38recycle_partition_table_stream_offsetsElllRKN6google8protobuf16RepeatedPtrFieldINS0_21TableStreamIdentityPBEEEENK3$_0clEv
Line
Count
Source
2542
1
    DORIS_CLOUD_DEFER {
2543
1
        metrics_context.finish_report();
2544
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler38recycle_partition_table_stream_offsetsElllRKN6google8protobuf16RepeatedPtrFieldINS0_21TableStreamIdentityPBEEEENK3$_0clEv
Line
Count
Source
2542
9
    DORIS_CLOUD_DEFER {
2543
9
        metrics_context.finish_report();
2544
9
    };
2545
10
    const size_t batch_size = std::max(1, config::recycler_max_tasks_per_batch);
2546
12
    for (size_t begin_index = 0; begin_index < table_streams.size(); begin_index += batch_size) {
2547
2
        const size_t end_index =
2548
2
                std::min(static_cast<size_t>(table_streams.size()), begin_index + batch_size);
2549
2
        std::unique_ptr<Transaction> txn;
2550
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2551
2
        if (err != TxnErrorCode::TXN_OK) {
2552
0
            LOG_WARNING("failed to create transaction for partition stream offset cleanup")
2553
0
                    .tag("instance_id", instance_id_)
2554
0
                    .tag("partition_id", partition_id)
2555
0
                    .tag("err", err);
2556
0
            return -1;
2557
0
        }
2558
4
        for (size_t i = begin_index; i < end_index; ++i) {
2559
2
            const TableStreamIdentityPB& stream = table_streams.Get(i);
2560
2
            if (stream.base_db_id() != db_id || stream.base_table_id() != table_id ||
2561
2
                stream.stream_db_id() <= 0 || stream.stream_id() <= 0) {
2562
0
                LOG_WARNING("invalid table stream binding in recycle partition")
2563
0
                        .tag("instance_id", instance_id_)
2564
0
                        .tag("partition_id", partition_id)
2565
0
                        .tag("stream_id", stream.stream_id());
2566
0
                return -1;
2567
0
            }
2568
2
            txn->remove(table_stream_offset_key({instance_id_, stream.base_db_id(),
2569
2
                                                 stream.base_table_id(), stream.stream_db_id(),
2570
2
                                                 stream.stream_id(), partition_id}));
2571
2
            versioned_remove_all(
2572
2
                    txn.get(), versioned::table_stream_offset_key(
2573
2
                                       {instance_id_, stream.base_db_id(), stream.base_table_id(),
2574
2
                                        stream.stream_db_id(), stream.stream_id(), partition_id}));
2575
2
        }
2576
2
        err = txn->commit();
2577
2
        if (err != TxnErrorCode::TXN_OK) {
2578
0
            LOG_WARNING("failed to commit partition stream offset cleanup")
2579
0
                    .tag("instance_id", instance_id_)
2580
0
                    .tag("partition_id", partition_id)
2581
0
                    .tag("err", err);
2582
0
            return -1;
2583
0
        }
2584
2
        metrics_context.total_recycled_num += end_index - begin_index;
2585
2
        metrics_context.report();
2586
2
    }
2587
10
    return 0;
2588
10
}
2589
2590
19
int InstanceRecycler::recycle_indexes() {
2591
19
    const std::string task_name = "recycle_indexes";
2592
19
    int64_t num_scanned = 0;
2593
19
    int64_t num_expired = 0;
2594
19
    int64_t num_recycled = 0;
2595
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2596
2597
19
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2598
19
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2599
19
    std::string index_key0;
2600
19
    std::string index_key1;
2601
19
    recycle_index_key(index_key_info0, &index_key0);
2602
19
    recycle_index_key(index_key_info1, &index_key1);
2603
2604
19
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2605
2606
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2607
19
    register_recycle_task(task_name, start_time);
2608
2609
19
    DORIS_CLOUD_DEFER {
2610
19
        unregister_recycle_task(task_name);
2611
19
        int64_t cost =
2612
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2613
19
        metrics_context.finish_report();
2614
19
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2615
19
                .tag("instance_id", instance_id_)
2616
19
                .tag("num_scanned", num_scanned)
2617
19
                .tag("num_expired", num_expired)
2618
19
                .tag("num_recycled", num_recycled);
2619
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2609
3
    DORIS_CLOUD_DEFER {
2610
3
        unregister_recycle_task(task_name);
2611
3
        int64_t cost =
2612
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2613
3
        metrics_context.finish_report();
2614
3
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2615
3
                .tag("instance_id", instance_id_)
2616
3
                .tag("num_scanned", num_scanned)
2617
3
                .tag("num_expired", num_expired)
2618
3
                .tag("num_recycled", num_recycled);
2619
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2609
16
    DORIS_CLOUD_DEFER {
2610
16
        unregister_recycle_task(task_name);
2611
16
        int64_t cost =
2612
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2613
16
        metrics_context.finish_report();
2614
16
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2615
16
                .tag("instance_id", instance_id_)
2616
16
                .tag("num_scanned", num_scanned)
2617
16
                .tag("num_expired", num_expired)
2618
16
                .tag("num_recycled", num_recycled);
2619
16
    };
2620
2621
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2622
2623
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2624
19
    std::vector<std::string_view> index_keys;
2625
19
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2626
13
        ++num_scanned;
2627
13
        RecycleIndexPB index_pb;
2628
13
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2629
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2630
0
            return -1;
2631
0
        }
2632
13
        int64_t current_time = ::time(nullptr);
2633
13
        if (current_time <
2634
13
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2635
0
            return 0;
2636
0
        }
2637
13
        ++num_expired;
2638
        // decode index_id
2639
13
        auto k1 = k;
2640
13
        k1.remove_prefix(1);
2641
13
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2642
13
        decode_key(&k1, &out);
2643
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2644
13
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2645
13
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2646
13
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2647
13
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2648
        // Change state to RECYCLING
2649
13
        std::unique_ptr<Transaction> txn;
2650
13
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2651
13
        if (err != TxnErrorCode::TXN_OK) {
2652
0
            LOG_WARNING("failed to create txn").tag("err", err);
2653
0
            return -1;
2654
0
        }
2655
13
        std::string val;
2656
13
        err = txn->get(k, &val);
2657
13
        if (err ==
2658
13
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2659
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2660
0
            return 0;
2661
0
        }
2662
13
        if (err != TxnErrorCode::TXN_OK) {
2663
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2664
0
            return -1;
2665
0
        }
2666
13
        index_pb.Clear();
2667
13
        if (!index_pb.ParseFromString(val)) {
2668
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2669
0
            return -1;
2670
0
        }
2671
13
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2672
12
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2673
12
            txn->put(k, index_pb.SerializeAsString());
2674
12
            err = txn->commit();
2675
12
            if (err != TxnErrorCode::TXN_OK) {
2676
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2677
0
                return -1;
2678
0
            }
2679
12
        }
2680
13
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
2681
3
            if (recycle_stream(index_id, index_pb, k) != 0) {
2682
0
                LOG_WARNING("failed to recycle table stream")
2683
0
                        .tag("instance_id", instance_id_)
2684
0
                        .tag("stream_id", index_id);
2685
0
                return -1;
2686
0
            }
2687
3
            metrics_context.total_recycled_num = ++num_recycled;
2688
3
            metrics_context.report();
2689
3
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2690
3
            return 0;
2691
3
        }
2692
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2693
1
            LOG_WARNING("failed to recycle tablets under index")
2694
1
                    .tag("table_id", index_pb.table_id())
2695
1
                    .tag("instance_id", instance_id_)
2696
1
                    .tag("index_id", index_id);
2697
1
            return -1;
2698
1
        }
2699
2700
9
        if (index_pb.has_db_id()) {
2701
            // Recycle the versioned keys
2702
3
            std::unique_ptr<Transaction> txn;
2703
3
            err = txn_kv_->create_txn(&txn);
2704
3
            if (err != TxnErrorCode::TXN_OK) {
2705
0
                LOG_WARNING("failed to create txn").tag("err", err);
2706
0
                return -1;
2707
0
            }
2708
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2709
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2710
3
            std::string index_inverted_key = versioned::index_inverted_key(
2711
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2712
3
            versioned_remove_all(txn.get(), meta_key);
2713
3
            txn->remove(index_key);
2714
3
            txn->remove(index_inverted_key);
2715
3
            err = txn->commit();
2716
3
            if (err != TxnErrorCode::TXN_OK) {
2717
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2718
0
                return -1;
2719
0
            }
2720
3
        }
2721
2722
9
        metrics_context.total_recycled_num = ++num_recycled;
2723
9
        metrics_context.report();
2724
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2725
9
        index_keys.push_back(k);
2726
9
        return 0;
2727
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2625
4
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2626
4
        ++num_scanned;
2627
4
        RecycleIndexPB index_pb;
2628
4
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2629
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2630
0
            return -1;
2631
0
        }
2632
4
        int64_t current_time = ::time(nullptr);
2633
4
        if (current_time <
2634
4
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2635
0
            return 0;
2636
0
        }
2637
4
        ++num_expired;
2638
        // decode index_id
2639
4
        auto k1 = k;
2640
4
        k1.remove_prefix(1);
2641
4
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2642
4
        decode_key(&k1, &out);
2643
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2644
4
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2645
4
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2646
4
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2647
4
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2648
        // Change state to RECYCLING
2649
4
        std::unique_ptr<Transaction> txn;
2650
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2651
4
        if (err != TxnErrorCode::TXN_OK) {
2652
0
            LOG_WARNING("failed to create txn").tag("err", err);
2653
0
            return -1;
2654
0
        }
2655
4
        std::string val;
2656
4
        err = txn->get(k, &val);
2657
4
        if (err ==
2658
4
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2659
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2660
0
            return 0;
2661
0
        }
2662
4
        if (err != TxnErrorCode::TXN_OK) {
2663
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2664
0
            return -1;
2665
0
        }
2666
4
        index_pb.Clear();
2667
4
        if (!index_pb.ParseFromString(val)) {
2668
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2669
0
            return -1;
2670
0
        }
2671
4
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2672
3
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2673
3
            txn->put(k, index_pb.SerializeAsString());
2674
3
            err = txn->commit();
2675
3
            if (err != TxnErrorCode::TXN_OK) {
2676
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2677
0
                return -1;
2678
0
            }
2679
3
        }
2680
4
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
2681
2
            if (recycle_stream(index_id, index_pb, k) != 0) {
2682
0
                LOG_WARNING("failed to recycle table stream")
2683
0
                        .tag("instance_id", instance_id_)
2684
0
                        .tag("stream_id", index_id);
2685
0
                return -1;
2686
0
            }
2687
2
            metrics_context.total_recycled_num = ++num_recycled;
2688
2
            metrics_context.report();
2689
2
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2690
2
            return 0;
2691
2
        }
2692
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2693
1
            LOG_WARNING("failed to recycle tablets under index")
2694
1
                    .tag("table_id", index_pb.table_id())
2695
1
                    .tag("instance_id", instance_id_)
2696
1
                    .tag("index_id", index_id);
2697
1
            return -1;
2698
1
        }
2699
2700
1
        if (index_pb.has_db_id()) {
2701
            // Recycle the versioned keys
2702
1
            std::unique_ptr<Transaction> txn;
2703
1
            err = txn_kv_->create_txn(&txn);
2704
1
            if (err != TxnErrorCode::TXN_OK) {
2705
0
                LOG_WARNING("failed to create txn").tag("err", err);
2706
0
                return -1;
2707
0
            }
2708
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2709
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2710
1
            std::string index_inverted_key = versioned::index_inverted_key(
2711
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2712
1
            versioned_remove_all(txn.get(), meta_key);
2713
1
            txn->remove(index_key);
2714
1
            txn->remove(index_inverted_key);
2715
1
            err = txn->commit();
2716
1
            if (err != TxnErrorCode::TXN_OK) {
2717
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2718
0
                return -1;
2719
0
            }
2720
1
        }
2721
2722
1
        metrics_context.total_recycled_num = ++num_recycled;
2723
1
        metrics_context.report();
2724
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2725
1
        index_keys.push_back(k);
2726
1
        return 0;
2727
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2625
9
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2626
9
        ++num_scanned;
2627
9
        RecycleIndexPB index_pb;
2628
9
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2629
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2630
0
            return -1;
2631
0
        }
2632
9
        int64_t current_time = ::time(nullptr);
2633
9
        if (current_time <
2634
9
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2635
0
            return 0;
2636
0
        }
2637
9
        ++num_expired;
2638
        // decode index_id
2639
9
        auto k1 = k;
2640
9
        k1.remove_prefix(1);
2641
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2642
9
        decode_key(&k1, &out);
2643
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2644
9
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2645
9
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2646
9
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2647
9
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2648
        // Change state to RECYCLING
2649
9
        std::unique_ptr<Transaction> txn;
2650
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2651
9
        if (err != TxnErrorCode::TXN_OK) {
2652
0
            LOG_WARNING("failed to create txn").tag("err", err);
2653
0
            return -1;
2654
0
        }
2655
9
        std::string val;
2656
9
        err = txn->get(k, &val);
2657
9
        if (err ==
2658
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2659
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2660
0
            return 0;
2661
0
        }
2662
9
        if (err != TxnErrorCode::TXN_OK) {
2663
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2664
0
            return -1;
2665
0
        }
2666
9
        index_pb.Clear();
2667
9
        if (!index_pb.ParseFromString(val)) {
2668
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2669
0
            return -1;
2670
0
        }
2671
9
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2672
9
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2673
9
            txn->put(k, index_pb.SerializeAsString());
2674
9
            err = txn->commit();
2675
9
            if (err != TxnErrorCode::TXN_OK) {
2676
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2677
0
                return -1;
2678
0
            }
2679
9
        }
2680
9
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
2681
1
            if (recycle_stream(index_id, index_pb, k) != 0) {
2682
0
                LOG_WARNING("failed to recycle table stream")
2683
0
                        .tag("instance_id", instance_id_)
2684
0
                        .tag("stream_id", index_id);
2685
0
                return -1;
2686
0
            }
2687
1
            metrics_context.total_recycled_num = ++num_recycled;
2688
1
            metrics_context.report();
2689
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2690
1
            return 0;
2691
1
        }
2692
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2693
0
            LOG_WARNING("failed to recycle tablets under index")
2694
0
                    .tag("table_id", index_pb.table_id())
2695
0
                    .tag("instance_id", instance_id_)
2696
0
                    .tag("index_id", index_id);
2697
0
            return -1;
2698
0
        }
2699
2700
8
        if (index_pb.has_db_id()) {
2701
            // Recycle the versioned keys
2702
2
            std::unique_ptr<Transaction> txn;
2703
2
            err = txn_kv_->create_txn(&txn);
2704
2
            if (err != TxnErrorCode::TXN_OK) {
2705
0
                LOG_WARNING("failed to create txn").tag("err", err);
2706
0
                return -1;
2707
0
            }
2708
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2709
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2710
2
            std::string index_inverted_key = versioned::index_inverted_key(
2711
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2712
2
            versioned_remove_all(txn.get(), meta_key);
2713
2
            txn->remove(index_key);
2714
2
            txn->remove(index_inverted_key);
2715
2
            err = txn->commit();
2716
2
            if (err != TxnErrorCode::TXN_OK) {
2717
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2718
0
                return -1;
2719
0
            }
2720
2
        }
2721
2722
8
        metrics_context.total_recycled_num = ++num_recycled;
2723
8
        metrics_context.report();
2724
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2725
8
        index_keys.push_back(k);
2726
8
        return 0;
2727
8
    };
2728
2729
19
    auto loop_done = [&index_keys, this]() -> int {
2730
8
        if (index_keys.empty()) return 0;
2731
5
        DORIS_CLOUD_DEFER {
2732
5
            index_keys.clear();
2733
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2731
1
        DORIS_CLOUD_DEFER {
2732
1
            index_keys.clear();
2733
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2731
4
        DORIS_CLOUD_DEFER {
2732
4
            index_keys.clear();
2733
4
        };
2734
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2735
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2736
0
            return -1;
2737
0
        }
2738
5
        return 0;
2739
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2729
3
    auto loop_done = [&index_keys, this]() -> int {
2730
3
        if (index_keys.empty()) return 0;
2731
1
        DORIS_CLOUD_DEFER {
2732
1
            index_keys.clear();
2733
1
        };
2734
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2735
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2736
0
            return -1;
2737
0
        }
2738
1
        return 0;
2739
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2729
5
    auto loop_done = [&index_keys, this]() -> int {
2730
5
        if (index_keys.empty()) return 0;
2731
4
        DORIS_CLOUD_DEFER {
2732
4
            index_keys.clear();
2733
4
        };
2734
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2735
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2736
0
            return -1;
2737
0
        }
2738
4
        return 0;
2739
4
    };
2740
2741
19
    if (config::enable_recycler_stats_metrics) {
2742
0
        scan_and_statistics_indexes();
2743
0
    }
2744
    // recycle_func and loop_done for scan and recycle
2745
19
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
2746
19
}
2747
2748
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
2749
8.25k
                             int64_t tablet_id) {
2750
8.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
2751
2752
8.25k
    std::unique_ptr<Transaction> txn;
2753
8.25k
    TxnErrorCode err = txn_kv->create_txn(&txn);
2754
8.25k
    if (err != TxnErrorCode::TXN_OK) {
2755
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
2756
0
                     << " tablet_id=" << tablet_id << " err=" << err;
2757
0
        return false;
2758
0
    }
2759
2760
8.25k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
2761
8.25k
    std::string tablet_idx_val;
2762
8.25k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
2763
8.25k
    if (TxnErrorCode::TXN_OK != err) {
2764
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
2765
0
                     << " tablet_id=" << tablet_id << " err=" << err
2766
0
                     << " key=" << hex(tablet_idx_key);
2767
0
        return false;
2768
0
    }
2769
2770
8.25k
    TabletIndexPB tablet_idx_pb;
2771
8.25k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
2772
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
2773
0
                     << " tablet_id=" << tablet_id;
2774
0
        return false;
2775
0
    }
2776
2777
8.25k
    if (!tablet_idx_pb.has_db_id()) {
2778
        // In the previous version, the db_id was not set in the index_pb.
2779
        // If updating to the version which enable txn lazy commit, the db_id will be set.
2780
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
2781
0
                  << " instance_id=" << instance_id
2782
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
2783
0
        return true;
2784
0
    }
2785
2786
8.25k
    std::string ver_val;
2787
8.25k
    std::string ver_key =
2788
8.25k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
2789
8.25k
                                   tablet_idx_pb.partition_id()});
2790
8.25k
    err = txn->get(ver_key, &ver_val);
2791
2792
8.25k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
2793
214
        LOG(INFO) << ""
2794
214
                     "partition version not found, instance_id="
2795
214
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
2796
214
                  << " table_id=" << tablet_idx_pb.table_id()
2797
214
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
2798
214
                  << " key=" << hex(ver_key);
2799
214
        return true;
2800
214
    }
2801
2802
8.03k
    if (TxnErrorCode::TXN_OK != err) {
2803
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
2804
0
                     << " db_id=" << tablet_idx_pb.db_id()
2805
0
                     << " table_id=" << tablet_idx_pb.table_id()
2806
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2807
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
2808
0
        return false;
2809
0
    }
2810
2811
8.03k
    VersionPB version_pb;
2812
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
2813
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
2814
0
                     << " db_id=" << tablet_idx_pb.db_id()
2815
0
                     << " table_id=" << tablet_idx_pb.table_id()
2816
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2817
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
2818
0
        return false;
2819
0
    }
2820
2821
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
2822
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
2823
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
2824
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
2825
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
2826
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
2827
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
2828
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
2829
4.00k
                     << " key=" << hex(ver_key);
2830
4.00k
        return false;
2831
4.00k
    }
2832
4.03k
    return true;
2833
8.03k
}
2834
2835
17
int InstanceRecycler::recycle_partitions() {
2836
17
    const std::string task_name = "recycle_partitions";
2837
17
    int64_t num_scanned = 0;
2838
17
    int64_t num_expired = 0;
2839
17
    int64_t num_recycled = 0;
2840
17
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2841
2842
17
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
2843
17
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
2844
17
    std::string part_key0;
2845
17
    std::string part_key1;
2846
17
    recycle_partition_key(part_key_info0, &part_key0);
2847
17
    recycle_partition_key(part_key_info1, &part_key1);
2848
2849
17
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
2850
2851
17
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2852
17
    register_recycle_task(task_name, start_time);
2853
2854
17
    DORIS_CLOUD_DEFER {
2855
17
        unregister_recycle_task(task_name);
2856
17
        int64_t cost =
2857
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2858
17
        metrics_context.finish_report();
2859
17
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2860
17
                .tag("instance_id", instance_id_)
2861
17
                .tag("num_scanned", num_scanned)
2862
17
                .tag("num_expired", num_expired)
2863
17
                .tag("num_recycled", num_recycled);
2864
17
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2854
2
    DORIS_CLOUD_DEFER {
2855
2
        unregister_recycle_task(task_name);
2856
2
        int64_t cost =
2857
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2858
2
        metrics_context.finish_report();
2859
2
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2860
2
                .tag("instance_id", instance_id_)
2861
2
                .tag("num_scanned", num_scanned)
2862
2
                .tag("num_expired", num_expired)
2863
2
                .tag("num_recycled", num_recycled);
2864
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2854
15
    DORIS_CLOUD_DEFER {
2855
15
        unregister_recycle_task(task_name);
2856
15
        int64_t cost =
2857
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2858
15
        metrics_context.finish_report();
2859
15
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2860
15
                .tag("instance_id", instance_id_)
2861
15
                .tag("num_scanned", num_scanned)
2862
15
                .tag("num_expired", num_expired)
2863
15
                .tag("num_recycled", num_recycled);
2864
15
    };
2865
2866
17
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2867
2868
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
2869
17
    std::vector<std::string_view> partition_keys;
2870
17
    std::vector<std::string> partition_version_keys;
2871
17
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2872
11
        ++num_scanned;
2873
11
        RecyclePartitionPB part_pb;
2874
11
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2875
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2876
0
            return -1;
2877
0
        }
2878
11
        int64_t current_time = ::time(nullptr);
2879
11
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2880
11
                                                            &earlest_ts)) { // not expired
2881
0
            return 0;
2882
0
        }
2883
11
        ++num_expired;
2884
        // decode partition_id
2885
11
        auto k1 = k;
2886
11
        k1.remove_prefix(1);
2887
11
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2888
11
        decode_key(&k1, &out);
2889
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2890
11
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2891
11
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2892
11
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2893
11
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2894
        // Change state to RECYCLING
2895
11
        std::unique_ptr<Transaction> txn;
2896
11
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2897
11
        if (err != TxnErrorCode::TXN_OK) {
2898
0
            LOG_WARNING("failed to create txn").tag("err", err);
2899
0
            return -1;
2900
0
        }
2901
11
        std::string val;
2902
11
        err = txn->get(k, &val);
2903
11
        if (err ==
2904
11
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2905
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2906
0
            return 0;
2907
0
        }
2908
11
        if (err != TxnErrorCode::TXN_OK) {
2909
0
            LOG_WARNING("failed to get kv");
2910
0
            return -1;
2911
0
        }
2912
11
        part_pb.Clear();
2913
11
        if (!part_pb.ParseFromString(val)) {
2914
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2915
0
            return -1;
2916
0
        }
2917
        // Partitions with PREPARED state MUST have no data
2918
11
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2919
10
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2920
10
            txn->put(k, part_pb.SerializeAsString());
2921
10
            err = txn->commit();
2922
10
            if (err != TxnErrorCode::TXN_OK) {
2923
0
                LOG_WARNING("failed to commit txn: {}", err);
2924
0
                return -1;
2925
0
            }
2926
10
        }
2927
2928
11
        int ret = 0;
2929
35
        for (int64_t index_id : part_pb.index_id()) {
2930
35
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2931
1
                LOG_WARNING("failed to recycle tablets under partition")
2932
1
                        .tag("table_id", part_pb.table_id())
2933
1
                        .tag("instance_id", instance_id_)
2934
1
                        .tag("index_id", index_id)
2935
1
                        .tag("partition_id", partition_id);
2936
1
                ret = -1;
2937
1
            }
2938
35
        }
2939
11
        if (ret == 0 && part_pb.has_db_id() &&
2940
11
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
2941
10
                                                   partition_id, part_pb.table_streams()) != 0) {
2942
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
2943
0
                    .tag("instance_id", instance_id_)
2944
0
                    .tag("table_id", part_pb.table_id())
2945
0
                    .tag("partition_id", partition_id);
2946
0
            ret = -1;
2947
0
        }
2948
11
        if (ret == 0 && part_pb.has_db_id()) {
2949
            // Recycle the versioned keys
2950
10
            std::unique_ptr<Transaction> txn;
2951
10
            err = txn_kv_->create_txn(&txn);
2952
10
            if (err != TxnErrorCode::TXN_OK) {
2953
0
                LOG_WARNING("failed to create txn").tag("err", err);
2954
0
                return -1;
2955
0
            }
2956
10
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2957
10
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2958
10
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2959
10
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2960
10
            std::string partition_version_key =
2961
10
                    versioned::partition_version_key({instance_id_, partition_id});
2962
10
            versioned_remove_all(txn.get(), meta_key);
2963
10
            txn->remove(index_key);
2964
10
            txn->remove(inverted_index_key);
2965
10
            versioned_remove_all(txn.get(), partition_version_key);
2966
10
            err = txn->commit();
2967
10
            if (err != TxnErrorCode::TXN_OK) {
2968
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2969
0
                return -1;
2970
0
            }
2971
10
        }
2972
2973
11
        if (ret == 0) {
2974
10
            ++num_recycled;
2975
10
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2976
10
            partition_keys.push_back(k);
2977
10
            if (part_pb.db_id() > 0) {
2978
10
                partition_version_keys.push_back(partition_version_key(
2979
10
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2980
10
            }
2981
10
            metrics_context.total_recycled_num = num_recycled;
2982
10
            metrics_context.report();
2983
10
        }
2984
11
        return ret;
2985
11
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2871
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2872
2
        ++num_scanned;
2873
2
        RecyclePartitionPB part_pb;
2874
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2875
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2876
0
            return -1;
2877
0
        }
2878
2
        int64_t current_time = ::time(nullptr);
2879
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2880
2
                                                            &earlest_ts)) { // not expired
2881
0
            return 0;
2882
0
        }
2883
2
        ++num_expired;
2884
        // decode partition_id
2885
2
        auto k1 = k;
2886
2
        k1.remove_prefix(1);
2887
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2888
2
        decode_key(&k1, &out);
2889
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2890
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2891
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2892
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2893
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2894
        // Change state to RECYCLING
2895
2
        std::unique_ptr<Transaction> txn;
2896
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2897
2
        if (err != TxnErrorCode::TXN_OK) {
2898
0
            LOG_WARNING("failed to create txn").tag("err", err);
2899
0
            return -1;
2900
0
        }
2901
2
        std::string val;
2902
2
        err = txn->get(k, &val);
2903
2
        if (err ==
2904
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2905
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2906
0
            return 0;
2907
0
        }
2908
2
        if (err != TxnErrorCode::TXN_OK) {
2909
0
            LOG_WARNING("failed to get kv");
2910
0
            return -1;
2911
0
        }
2912
2
        part_pb.Clear();
2913
2
        if (!part_pb.ParseFromString(val)) {
2914
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2915
0
            return -1;
2916
0
        }
2917
        // Partitions with PREPARED state MUST have no data
2918
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2919
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2920
1
            txn->put(k, part_pb.SerializeAsString());
2921
1
            err = txn->commit();
2922
1
            if (err != TxnErrorCode::TXN_OK) {
2923
0
                LOG_WARNING("failed to commit txn: {}", err);
2924
0
                return -1;
2925
0
            }
2926
1
        }
2927
2928
2
        int ret = 0;
2929
2
        for (int64_t index_id : part_pb.index_id()) {
2930
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2931
1
                LOG_WARNING("failed to recycle tablets under partition")
2932
1
                        .tag("table_id", part_pb.table_id())
2933
1
                        .tag("instance_id", instance_id_)
2934
1
                        .tag("index_id", index_id)
2935
1
                        .tag("partition_id", partition_id);
2936
1
                ret = -1;
2937
1
            }
2938
2
        }
2939
2
        if (ret == 0 && part_pb.has_db_id() &&
2940
2
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
2941
1
                                                   partition_id, part_pb.table_streams()) != 0) {
2942
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
2943
0
                    .tag("instance_id", instance_id_)
2944
0
                    .tag("table_id", part_pb.table_id())
2945
0
                    .tag("partition_id", partition_id);
2946
0
            ret = -1;
2947
0
        }
2948
2
        if (ret == 0 && part_pb.has_db_id()) {
2949
            // Recycle the versioned keys
2950
1
            std::unique_ptr<Transaction> txn;
2951
1
            err = txn_kv_->create_txn(&txn);
2952
1
            if (err != TxnErrorCode::TXN_OK) {
2953
0
                LOG_WARNING("failed to create txn").tag("err", err);
2954
0
                return -1;
2955
0
            }
2956
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2957
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2958
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2959
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2960
1
            std::string partition_version_key =
2961
1
                    versioned::partition_version_key({instance_id_, partition_id});
2962
1
            versioned_remove_all(txn.get(), meta_key);
2963
1
            txn->remove(index_key);
2964
1
            txn->remove(inverted_index_key);
2965
1
            versioned_remove_all(txn.get(), partition_version_key);
2966
1
            err = txn->commit();
2967
1
            if (err != TxnErrorCode::TXN_OK) {
2968
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2969
0
                return -1;
2970
0
            }
2971
1
        }
2972
2973
2
        if (ret == 0) {
2974
1
            ++num_recycled;
2975
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2976
1
            partition_keys.push_back(k);
2977
1
            if (part_pb.db_id() > 0) {
2978
1
                partition_version_keys.push_back(partition_version_key(
2979
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2980
1
            }
2981
1
            metrics_context.total_recycled_num = num_recycled;
2982
1
            metrics_context.report();
2983
1
        }
2984
2
        return ret;
2985
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2871
9
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2872
9
        ++num_scanned;
2873
9
        RecyclePartitionPB part_pb;
2874
9
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2875
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2876
0
            return -1;
2877
0
        }
2878
9
        int64_t current_time = ::time(nullptr);
2879
9
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2880
9
                                                            &earlest_ts)) { // not expired
2881
0
            return 0;
2882
0
        }
2883
9
        ++num_expired;
2884
        // decode partition_id
2885
9
        auto k1 = k;
2886
9
        k1.remove_prefix(1);
2887
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2888
9
        decode_key(&k1, &out);
2889
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2890
9
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2891
9
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2892
9
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2893
9
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2894
        // Change state to RECYCLING
2895
9
        std::unique_ptr<Transaction> txn;
2896
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2897
9
        if (err != TxnErrorCode::TXN_OK) {
2898
0
            LOG_WARNING("failed to create txn").tag("err", err);
2899
0
            return -1;
2900
0
        }
2901
9
        std::string val;
2902
9
        err = txn->get(k, &val);
2903
9
        if (err ==
2904
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2905
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2906
0
            return 0;
2907
0
        }
2908
9
        if (err != TxnErrorCode::TXN_OK) {
2909
0
            LOG_WARNING("failed to get kv");
2910
0
            return -1;
2911
0
        }
2912
9
        part_pb.Clear();
2913
9
        if (!part_pb.ParseFromString(val)) {
2914
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2915
0
            return -1;
2916
0
        }
2917
        // Partitions with PREPARED state MUST have no data
2918
9
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2919
9
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2920
9
            txn->put(k, part_pb.SerializeAsString());
2921
9
            err = txn->commit();
2922
9
            if (err != TxnErrorCode::TXN_OK) {
2923
0
                LOG_WARNING("failed to commit txn: {}", err);
2924
0
                return -1;
2925
0
            }
2926
9
        }
2927
2928
9
        int ret = 0;
2929
33
        for (int64_t index_id : part_pb.index_id()) {
2930
33
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2931
0
                LOG_WARNING("failed to recycle tablets under partition")
2932
0
                        .tag("table_id", part_pb.table_id())
2933
0
                        .tag("instance_id", instance_id_)
2934
0
                        .tag("index_id", index_id)
2935
0
                        .tag("partition_id", partition_id);
2936
0
                ret = -1;
2937
0
            }
2938
33
        }
2939
9
        if (ret == 0 && part_pb.has_db_id() &&
2940
9
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
2941
9
                                                   partition_id, part_pb.table_streams()) != 0) {
2942
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
2943
0
                    .tag("instance_id", instance_id_)
2944
0
                    .tag("table_id", part_pb.table_id())
2945
0
                    .tag("partition_id", partition_id);
2946
0
            ret = -1;
2947
0
        }
2948
9
        if (ret == 0 && part_pb.has_db_id()) {
2949
            // Recycle the versioned keys
2950
9
            std::unique_ptr<Transaction> txn;
2951
9
            err = txn_kv_->create_txn(&txn);
2952
9
            if (err != TxnErrorCode::TXN_OK) {
2953
0
                LOG_WARNING("failed to create txn").tag("err", err);
2954
0
                return -1;
2955
0
            }
2956
9
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2957
9
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2958
9
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2959
9
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2960
9
            std::string partition_version_key =
2961
9
                    versioned::partition_version_key({instance_id_, partition_id});
2962
9
            versioned_remove_all(txn.get(), meta_key);
2963
9
            txn->remove(index_key);
2964
9
            txn->remove(inverted_index_key);
2965
9
            versioned_remove_all(txn.get(), partition_version_key);
2966
9
            err = txn->commit();
2967
9
            if (err != TxnErrorCode::TXN_OK) {
2968
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2969
0
                return -1;
2970
0
            }
2971
9
        }
2972
2973
9
        if (ret == 0) {
2974
9
            ++num_recycled;
2975
9
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2976
9
            partition_keys.push_back(k);
2977
9
            if (part_pb.db_id() > 0) {
2978
9
                partition_version_keys.push_back(partition_version_key(
2979
9
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2980
9
            }
2981
9
            metrics_context.total_recycled_num = num_recycled;
2982
9
            metrics_context.report();
2983
9
        }
2984
9
        return ret;
2985
9
    };
2986
2987
17
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2988
7
        if (partition_keys.empty()) return 0;
2989
6
        DORIS_CLOUD_DEFER {
2990
6
            partition_keys.clear();
2991
6
            partition_version_keys.clear();
2992
6
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2989
1
        DORIS_CLOUD_DEFER {
2990
1
            partition_keys.clear();
2991
1
            partition_version_keys.clear();
2992
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2989
5
        DORIS_CLOUD_DEFER {
2990
5
            partition_keys.clear();
2991
5
            partition_version_keys.clear();
2992
5
        };
2993
6
        std::unique_ptr<Transaction> txn;
2994
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2995
6
        if (err != TxnErrorCode::TXN_OK) {
2996
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2997
0
            return -1;
2998
0
        }
2999
10
        for (auto& k : partition_keys) {
3000
10
            txn->remove(k);
3001
10
        }
3002
10
        for (auto& k : partition_version_keys) {
3003
10
            txn->remove(k);
3004
10
        }
3005
6
        err = txn->commit();
3006
6
        if (err != TxnErrorCode::TXN_OK) {
3007
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3008
0
                         << " err=" << err;
3009
0
            return -1;
3010
0
        }
3011
6
        return 0;
3012
6
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2987
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2988
2
        if (partition_keys.empty()) return 0;
2989
1
        DORIS_CLOUD_DEFER {
2990
1
            partition_keys.clear();
2991
1
            partition_version_keys.clear();
2992
1
        };
2993
1
        std::unique_ptr<Transaction> txn;
2994
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2995
1
        if (err != TxnErrorCode::TXN_OK) {
2996
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2997
0
            return -1;
2998
0
        }
2999
1
        for (auto& k : partition_keys) {
3000
1
            txn->remove(k);
3001
1
        }
3002
1
        for (auto& k : partition_version_keys) {
3003
1
            txn->remove(k);
3004
1
        }
3005
1
        err = txn->commit();
3006
1
        if (err != TxnErrorCode::TXN_OK) {
3007
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3008
0
                         << " err=" << err;
3009
0
            return -1;
3010
0
        }
3011
1
        return 0;
3012
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2987
5
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2988
5
        if (partition_keys.empty()) return 0;
2989
5
        DORIS_CLOUD_DEFER {
2990
5
            partition_keys.clear();
2991
5
            partition_version_keys.clear();
2992
5
        };
2993
5
        std::unique_ptr<Transaction> txn;
2994
5
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2995
5
        if (err != TxnErrorCode::TXN_OK) {
2996
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2997
0
            return -1;
2998
0
        }
2999
9
        for (auto& k : partition_keys) {
3000
9
            txn->remove(k);
3001
9
        }
3002
9
        for (auto& k : partition_version_keys) {
3003
9
            txn->remove(k);
3004
9
        }
3005
5
        err = txn->commit();
3006
5
        if (err != TxnErrorCode::TXN_OK) {
3007
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3008
0
                         << " err=" << err;
3009
0
            return -1;
3010
0
        }
3011
5
        return 0;
3012
5
    };
3013
3014
17
    if (config::enable_recycler_stats_metrics) {
3015
0
        scan_and_statistics_partitions();
3016
0
    }
3017
    // recycle_func and loop_done for scan and recycle
3018
17
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
3019
17
}
3020
3021
14
int InstanceRecycler::recycle_versions() {
3022
14
    if (should_recycle_versioned_keys()) {
3023
2
        return recycle_orphan_partitions();
3024
2
    }
3025
3026
12
    int64_t num_scanned = 0;
3027
12
    int64_t num_recycled = 0;
3028
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
3029
3030
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
3031
3032
12
    auto start_time = steady_clock::now();
3033
3034
12
    DORIS_CLOUD_DEFER {
3035
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3036
12
        metrics_context.finish_report();
3037
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3038
12
                .tag("instance_id", instance_id_)
3039
12
                .tag("num_scanned", num_scanned)
3040
12
                .tag("num_recycled", num_recycled);
3041
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
3034
12
    DORIS_CLOUD_DEFER {
3035
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3036
12
        metrics_context.finish_report();
3037
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3038
12
                .tag("instance_id", instance_id_)
3039
12
                .tag("num_scanned", num_scanned)
3040
12
                .tag("num_recycled", num_recycled);
3041
12
    };
3042
3043
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
3044
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
3045
12
    int64_t last_scanned_table_id = 0;
3046
12
    bool is_recycled = false; // Is last scanned kv recycled
3047
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
3048
12
                         &metrics_context, this](std::string_view k, std::string_view) {
3049
2
        ++num_scanned;
3050
2
        auto k1 = k;
3051
2
        k1.remove_prefix(1);
3052
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3053
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3054
2
        decode_key(&k1, &out);
3055
2
        DCHECK_EQ(out.size(), 6) << k;
3056
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3057
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3058
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3059
0
            return 0;
3060
0
        }
3061
2
        last_scanned_table_id = table_id;
3062
2
        is_recycled = false;
3063
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3064
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3065
2
        std::unique_ptr<Transaction> txn;
3066
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3067
2
        if (err != TxnErrorCode::TXN_OK) {
3068
0
            return -1;
3069
0
        }
3070
2
        std::unique_ptr<RangeGetIterator> iter;
3071
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3072
2
        if (err != TxnErrorCode::TXN_OK) {
3073
0
            return -1;
3074
0
        }
3075
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3076
1
            return 0;
3077
1
        }
3078
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3079
        // 1. Remove all partition version kvs of this table
3080
1
        auto partition_version_key_begin =
3081
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3082
1
        auto partition_version_key_end =
3083
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3084
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3085
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3086
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3087
1
                     << " table_id=" << table_id;
3088
        // 2. Remove the table version kv of this table
3089
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3090
1
        txn->remove(tbl_version_key);
3091
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3092
        // 3. Remove mow delete bitmap update lock and tablet job lock
3093
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3094
1
        txn->remove(lock_key);
3095
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3096
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3097
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3098
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3099
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3100
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3101
1
                     << " table_id=" << table_id;
3102
1
        err = txn->commit();
3103
1
        if (err != TxnErrorCode::TXN_OK) {
3104
0
            return -1;
3105
0
        }
3106
1
        metrics_context.total_recycled_num = ++num_recycled;
3107
1
        metrics_context.report();
3108
1
        is_recycled = true;
3109
1
        return 0;
3110
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3048
2
                         &metrics_context, this](std::string_view k, std::string_view) {
3049
2
        ++num_scanned;
3050
2
        auto k1 = k;
3051
2
        k1.remove_prefix(1);
3052
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3053
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3054
2
        decode_key(&k1, &out);
3055
2
        DCHECK_EQ(out.size(), 6) << k;
3056
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3057
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3058
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3059
0
            return 0;
3060
0
        }
3061
2
        last_scanned_table_id = table_id;
3062
2
        is_recycled = false;
3063
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3064
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3065
2
        std::unique_ptr<Transaction> txn;
3066
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3067
2
        if (err != TxnErrorCode::TXN_OK) {
3068
0
            return -1;
3069
0
        }
3070
2
        std::unique_ptr<RangeGetIterator> iter;
3071
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3072
2
        if (err != TxnErrorCode::TXN_OK) {
3073
0
            return -1;
3074
0
        }
3075
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3076
1
            return 0;
3077
1
        }
3078
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3079
        // 1. Remove all partition version kvs of this table
3080
1
        auto partition_version_key_begin =
3081
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3082
1
        auto partition_version_key_end =
3083
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3084
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3085
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3086
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3087
1
                     << " table_id=" << table_id;
3088
        // 2. Remove the table version kv of this table
3089
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3090
1
        txn->remove(tbl_version_key);
3091
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3092
        // 3. Remove mow delete bitmap update lock and tablet job lock
3093
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3094
1
        txn->remove(lock_key);
3095
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3096
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3097
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3098
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3099
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3100
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3101
1
                     << " table_id=" << table_id;
3102
1
        err = txn->commit();
3103
1
        if (err != TxnErrorCode::TXN_OK) {
3104
0
            return -1;
3105
0
        }
3106
1
        metrics_context.total_recycled_num = ++num_recycled;
3107
1
        metrics_context.report();
3108
1
        is_recycled = true;
3109
1
        return 0;
3110
1
    };
3111
3112
12
    if (config::enable_recycler_stats_metrics) {
3113
0
        scan_and_statistics_versions();
3114
0
    }
3115
    // recycle_func and loop_done for scan and recycle
3116
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
3117
14
}
3118
3119
3
int InstanceRecycler::recycle_orphan_partitions() {
3120
3
    int64_t num_scanned = 0;
3121
3
    int64_t num_recycled = 0;
3122
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
3123
3124
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
3125
3
            .tag("instance_id", instance_id_);
3126
3127
3
    auto start_time = steady_clock::now();
3128
3129
3
    DORIS_CLOUD_DEFER {
3130
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3131
3
        metrics_context.finish_report();
3132
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3133
3
                .tag("instance_id", instance_id_)
3134
3
                .tag("num_scanned", num_scanned)
3135
3
                .tag("num_recycled", num_recycled);
3136
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
3129
3
    DORIS_CLOUD_DEFER {
3130
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3131
3
        metrics_context.finish_report();
3132
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3133
3
                .tag("instance_id", instance_id_)
3134
3
                .tag("num_scanned", num_scanned)
3135
3
                .tag("num_recycled", num_recycled);
3136
3
    };
3137
3138
3
    bool is_empty_table = false;        // whether the table has no indexes
3139
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
3140
3
    int64_t current_table_id = 0;       // current scanning table id
3141
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
3142
3
                         &current_table_id, &is_table_kvs_recycled,
3143
3
                         this](std::string_view k, std::string_view) {
3144
2
        ++num_scanned;
3145
3146
2
        std::string_view k1(k);
3147
2
        int64_t db_id, table_id, partition_id;
3148
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3149
2
                                                            &partition_id)) {
3150
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3151
0
            return -1;
3152
2
        } else if (table_id != current_table_id) {
3153
2
            current_table_id = table_id;
3154
2
            is_table_kvs_recycled = false;
3155
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3156
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3157
2
            if (err != TxnErrorCode::TXN_OK) {
3158
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3159
0
                             << " table_id=" << table_id << " err=" << err;
3160
0
                return -1;
3161
0
            }
3162
2
        }
3163
3164
2
        if (!is_empty_table) {
3165
            // table is not empty, skip recycle
3166
1
            return 0;
3167
1
        }
3168
3169
1
        std::unique_ptr<Transaction> txn;
3170
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3171
1
        if (err != TxnErrorCode::TXN_OK) {
3172
0
            return -1;
3173
0
        }
3174
3175
        // 1. Remove all partition related kvs
3176
1
        std::string partition_meta_key =
3177
1
                versioned::meta_partition_key({instance_id_, partition_id});
3178
1
        std::string partition_index_key =
3179
1
                versioned::partition_index_key({instance_id_, partition_id});
3180
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3181
1
                {instance_id_, db_id, table_id, partition_id});
3182
1
        std::string partition_version_key =
3183
1
                versioned::partition_version_key({instance_id_, partition_id});
3184
1
        txn->remove(partition_index_key);
3185
1
        txn->remove(partition_inverted_key);
3186
1
        versioned_remove_all(txn.get(), partition_meta_key);
3187
1
        versioned_remove_all(txn.get(), partition_version_key);
3188
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3189
1
                     << " table_id=" << table_id << " db_id=" << db_id
3190
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3191
1
                     << " partition_version_key=" << hex(partition_version_key);
3192
3193
1
        if (!is_table_kvs_recycled) {
3194
1
            is_table_kvs_recycled = true;
3195
3196
            // 2. Remove the table version kv of this table
3197
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3198
1
            versioned_remove_all(txn.get(), table_version_key);
3199
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3200
            // 3. Remove mow delete bitmap update lock and tablet job lock
3201
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3202
1
            txn->remove(lock_key);
3203
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3204
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3205
1
            std::string tablet_job_key_end =
3206
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3207
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3208
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3209
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3210
1
                         << " table_id=" << table_id;
3211
1
        }
3212
3213
1
        err = txn->commit();
3214
1
        if (err != TxnErrorCode::TXN_OK) {
3215
0
            return -1;
3216
0
        }
3217
1
        metrics_context.total_recycled_num = ++num_recycled;
3218
1
        metrics_context.report();
3219
1
        return 0;
3220
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
3143
2
                         this](std::string_view k, std::string_view) {
3144
2
        ++num_scanned;
3145
3146
2
        std::string_view k1(k);
3147
2
        int64_t db_id, table_id, partition_id;
3148
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3149
2
                                                            &partition_id)) {
3150
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3151
0
            return -1;
3152
2
        } else if (table_id != current_table_id) {
3153
2
            current_table_id = table_id;
3154
2
            is_table_kvs_recycled = false;
3155
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3156
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3157
2
            if (err != TxnErrorCode::TXN_OK) {
3158
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3159
0
                             << " table_id=" << table_id << " err=" << err;
3160
0
                return -1;
3161
0
            }
3162
2
        }
3163
3164
2
        if (!is_empty_table) {
3165
            // table is not empty, skip recycle
3166
1
            return 0;
3167
1
        }
3168
3169
1
        std::unique_ptr<Transaction> txn;
3170
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3171
1
        if (err != TxnErrorCode::TXN_OK) {
3172
0
            return -1;
3173
0
        }
3174
3175
        // 1. Remove all partition related kvs
3176
1
        std::string partition_meta_key =
3177
1
                versioned::meta_partition_key({instance_id_, partition_id});
3178
1
        std::string partition_index_key =
3179
1
                versioned::partition_index_key({instance_id_, partition_id});
3180
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3181
1
                {instance_id_, db_id, table_id, partition_id});
3182
1
        std::string partition_version_key =
3183
1
                versioned::partition_version_key({instance_id_, partition_id});
3184
1
        txn->remove(partition_index_key);
3185
1
        txn->remove(partition_inverted_key);
3186
1
        versioned_remove_all(txn.get(), partition_meta_key);
3187
1
        versioned_remove_all(txn.get(), partition_version_key);
3188
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3189
1
                     << " table_id=" << table_id << " db_id=" << db_id
3190
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3191
1
                     << " partition_version_key=" << hex(partition_version_key);
3192
3193
1
        if (!is_table_kvs_recycled) {
3194
1
            is_table_kvs_recycled = true;
3195
3196
            // 2. Remove the table version kv of this table
3197
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3198
1
            versioned_remove_all(txn.get(), table_version_key);
3199
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3200
            // 3. Remove mow delete bitmap update lock and tablet job lock
3201
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3202
1
            txn->remove(lock_key);
3203
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3204
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3205
1
            std::string tablet_job_key_end =
3206
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3207
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3208
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3209
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3210
1
                         << " table_id=" << table_id;
3211
1
        }
3212
3213
1
        err = txn->commit();
3214
1
        if (err != TxnErrorCode::TXN_OK) {
3215
0
            return -1;
3216
0
        }
3217
1
        metrics_context.total_recycled_num = ++num_recycled;
3218
1
        metrics_context.report();
3219
1
        return 0;
3220
1
    };
3221
3222
    // recycle_func and loop_done for scan and recycle
3223
3
    return scan_and_recycle(
3224
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
3225
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
3226
3
            std::move(recycle_func));
3227
3
}
3228
3229
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
3230
                                      RecyclerMetricsContext& metrics_context,
3231
54
                                      int64_t partition_id) {
3232
54
    bool is_multi_version =
3233
54
            instance_info_.has_multi_version_status() &&
3234
54
            instance_info_.multi_version_status() != MultiVersionStatus::MULTI_VERSION_DISABLED;
3235
54
    int64_t num_scanned = 0;
3236
54
    std::atomic_long num_recycled = 0;
3237
3238
54
    std::string tablet_key_begin, tablet_key_end;
3239
54
    std::string stats_key_begin, stats_key_end;
3240
54
    std::string job_key_begin, job_key_end;
3241
3242
54
    std::string tablet_belongs;
3243
54
    if (partition_id > 0) {
3244
        // recycle tablets in a partition belonging to the index
3245
35
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
3246
35
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
3247
35
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
3248
35
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
3249
35
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
3250
35
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
3251
35
        tablet_belongs = "partition";
3252
35
    } else {
3253
        // recycle tablets in the index
3254
19
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
3255
19
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
3256
19
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
3257
19
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
3258
19
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
3259
19
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
3260
19
        tablet_belongs = "index";
3261
19
    }
3262
3263
54
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
3264
54
            .tag("table_id", table_id)
3265
54
            .tag("index_id", index_id)
3266
54
            .tag("partition_id", partition_id);
3267
3268
54
    auto start_time = steady_clock::now();
3269
3270
54
    DORIS_CLOUD_DEFER {
3271
54
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3272
54
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3273
54
                .tag("instance_id", instance_id_)
3274
54
                .tag("table_id", table_id)
3275
54
                .tag("index_id", index_id)
3276
54
                .tag("partition_id", partition_id)
3277
54
                .tag("num_scanned", num_scanned)
3278
54
                .tag("num_recycled", num_recycled);
3279
54
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3270
4
    DORIS_CLOUD_DEFER {
3271
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3272
4
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3273
4
                .tag("instance_id", instance_id_)
3274
4
                .tag("table_id", table_id)
3275
4
                .tag("index_id", index_id)
3276
4
                .tag("partition_id", partition_id)
3277
4
                .tag("num_scanned", num_scanned)
3278
4
                .tag("num_recycled", num_recycled);
3279
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3270
50
    DORIS_CLOUD_DEFER {
3271
50
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3272
50
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3273
50
                .tag("instance_id", instance_id_)
3274
50
                .tag("table_id", table_id)
3275
50
                .tag("index_id", index_id)
3276
50
                .tag("partition_id", partition_id)
3277
50
                .tag("num_scanned", num_scanned)
3278
50
                .tag("num_recycled", num_recycled);
3279
50
    };
3280
3281
    // The tablet key and id which have been recycled.
3282
54
    struct TabletInfo {
3283
54
        std::string_view tablet_meta_key;
3284
54
        int64_t tablet_id;
3285
54
    };
3286
54
    SyncExecutor<TabletInfo> sync_executor(
3287
54
            _thread_pool_group.recycle_tablet_pool,
3288
54
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
3289
54
                        index_id, partition_id),
3290
4.24k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3290
4.00k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3290
241
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
3291
3292
    // Elements in `tablets_info` has the same lifetime as `it` in `scan_and_recycle`
3293
54
    std::vector<std::string> init_rs_keys;
3294
54
    bool has_failure = false;
3295
8.25k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3296
8.25k
        ++num_scanned;
3297
8.25k
        doris::TabletMetaCloudPB tablet_meta_pb;
3298
8.25k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3299
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3300
0
            has_failure = true;
3301
0
            return -1;
3302
0
        }
3303
8.25k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3304
3305
8.25k
        if (config::enable_recycler_check_lazy_txn_finished &&
3306
8.25k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3307
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3308
4.00k
            has_failure = true;
3309
4.00k
            return -1;
3310
4.00k
        }
3311
3312
4.25k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3313
4.25k
        sync_executor.add(
3314
4.25k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3315
4.25k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3316
2
                        LOG_WARNING("failed to recycle tablet")
3317
2
                                .tag("instance_id", instance_id_)
3318
2
                                .tag("tablet_id", tid);
3319
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3320
2
                    }
3321
4.25k
                    ++num_recycled;
3322
4.25k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3323
4.25k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3324
4.25k
                });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3314
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3315
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3316
0
                        LOG_WARNING("failed to recycle tablet")
3317
0
                                .tag("instance_id", instance_id_)
3318
0
                                .tag("tablet_id", tid);
3319
0
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3320
0
                    }
3321
4.00k
                    ++num_recycled;
3322
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3323
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3324
4.00k
                });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3314
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3315
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3316
2
                        LOG_WARNING("failed to recycle tablet")
3317
2
                                .tag("instance_id", instance_id_)
3318
2
                                .tag("tablet_id", tid);
3319
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3320
2
                    }
3321
248
                    ++num_recycled;
3322
248
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3323
248
                    return {.tablet_meta_key = k, .tablet_id = tid};
3324
250
                });
3325
4.25k
        return 0;
3326
4.25k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3295
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3296
8.00k
        ++num_scanned;
3297
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
3298
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3299
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3300
0
            has_failure = true;
3301
0
            return -1;
3302
0
        }
3303
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3304
3305
8.00k
        if (config::enable_recycler_check_lazy_txn_finished &&
3306
8.00k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3307
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3308
4.00k
            has_failure = true;
3309
4.00k
            return -1;
3310
4.00k
        }
3311
3312
4.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3313
4.00k
        sync_executor.add(
3314
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3315
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3316
4.00k
                        LOG_WARNING("failed to recycle tablet")
3317
4.00k
                                .tag("instance_id", instance_id_)
3318
4.00k
                                .tag("tablet_id", tid);
3319
4.00k
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3320
4.00k
                    }
3321
4.00k
                    ++num_recycled;
3322
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3323
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3324
4.00k
                });
3325
4.00k
        return 0;
3326
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3295
251
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3296
251
        ++num_scanned;
3297
251
        doris::TabletMetaCloudPB tablet_meta_pb;
3298
251
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3299
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3300
0
            has_failure = true;
3301
0
            return -1;
3302
0
        }
3303
251
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3304
3305
251
        if (config::enable_recycler_check_lazy_txn_finished &&
3306
251
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3307
1
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3308
1
            has_failure = true;
3309
1
            return -1;
3310
1
        }
3311
3312
250
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3313
250
        sync_executor.add(
3314
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3315
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3316
250
                        LOG_WARNING("failed to recycle tablet")
3317
250
                                .tag("instance_id", instance_id_)
3318
250
                                .tag("tablet_id", tid);
3319
250
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3320
250
                    }
3321
250
                    ++num_recycled;
3322
250
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3323
250
                    return {.tablet_meta_key = k, .tablet_id = tid};
3324
250
                });
3325
250
        return 0;
3326
250
    };
3327
3328
54
    auto loop_done = [&, this]() -> int {
3329
52
        int ret = 0;
3330
52
        bool finished = true;
3331
52
        bool has_empty_key = false;
3332
52
        DORIS_CLOUD_DEFER {
3333
52
            init_rs_keys.clear();
3334
52
            has_failure = false;
3335
52
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3332
4
        DORIS_CLOUD_DEFER {
3333
4
            init_rs_keys.clear();
3334
4
            has_failure = false;
3335
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3332
48
        DORIS_CLOUD_DEFER {
3333
48
            init_rs_keys.clear();
3334
48
            has_failure = false;
3335
48
        };
3336
52
        auto tablets_info = sync_executor.when_all(&finished);
3337
52
        if (!finished) {
3338
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3339
1
            return -1;
3340
1
        }
3341
3342
51
        size_t size_before_erase = tablets_info.size();
3343
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
3343
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
3343
249
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3344
51
        if (tablets_info.empty()) {
3345
2
            return size_before_erase == 0 ? 0 : -1;
3346
49
        } else if (size_before_erase != tablets_info.size()) {
3347
1
            has_empty_key = true;
3348
1
        }
3349
3350
49
        ret = has_empty_key ? -1 : 0;
3351
        // sort the vector using key's order
3352
49.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3353
49.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3354
49.4k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3352
48.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3353
48.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3354
48.4k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3352
958
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3353
958
            return prev.tablet_meta_key < last.tablet_meta_key;
3354
958
        });
3355
49
        std::unique_ptr<Transaction> txn;
3356
49
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3357
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3358
0
            return -1;
3359
0
        }
3360
49
        std::string tablet_key_end;
3361
49
        if (!tablets_info.empty()) {
3362
49
            if (!has_empty_key && !has_failure) {
3363
47
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3364
47
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3365
47
            } else {
3366
8
                for (auto& tablet_info : tablets_info) {
3367
8
                    txn->remove(tablet_info.tablet_meta_key);
3368
8
                }
3369
2
            }
3370
49
        }
3371
49
        if (is_multi_version) {
3372
6
            for (auto& tablet_info : tablets_info) {
3373
                // Remove all versions of tablet compact stats for recycled tablet
3374
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3375
6
                LOG_INFO("remove versioned tablet compact stats key")
3376
6
                        .tag("compact_stats_key", hex(k));
3377
6
                versioned_remove_all(txn.get(), k);
3378
6
            }
3379
6
            for (auto& tablet_info : tablets_info) {
3380
                // Remove all versions of tablet load stats for recycled tablet
3381
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3382
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3383
6
                versioned_remove_all(txn.get(), k);
3384
6
            }
3385
6
            for (auto& tablet_info : tablets_info) {
3386
                // Remove all versions of meta tablet for recycled tablet
3387
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3388
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3389
6
                versioned_remove_all(txn.get(), k);
3390
6
            }
3391
5
        }
3392
4.25k
        for (auto& tablet_info : tablets_info) {
3393
4.25k
            std::string k;
3394
4.25k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3395
4.25k
            txn->remove(k);
3396
4.25k
        }
3397
4.25k
        for (auto& tablet_info : tablets_info) {
3398
4.25k
            std::string k;
3399
4.25k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3400
4.25k
            txn->remove(k);
3401
4.25k
        }
3402
49
        for (auto& k : init_rs_keys) {
3403
0
            txn->remove(k);
3404
0
        }
3405
49
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3406
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3407
0
                         << ", err=" << err;
3408
0
            return -1;
3409
0
        }
3410
49
        return ret;
3411
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
3328
4
    auto loop_done = [&, this]() -> int {
3329
4
        int ret = 0;
3330
4
        bool finished = true;
3331
4
        bool has_empty_key = false;
3332
4
        DORIS_CLOUD_DEFER {
3333
4
            init_rs_keys.clear();
3334
4
            has_failure = false;
3335
4
        };
3336
4
        auto tablets_info = sync_executor.when_all(&finished);
3337
4
        if (!finished) {
3338
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3339
0
            return -1;
3340
0
        }
3341
3342
4
        size_t size_before_erase = tablets_info.size();
3343
4
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3344
4
        if (tablets_info.empty()) {
3345
2
            return size_before_erase == 0 ? 0 : -1;
3346
2
        } else if (size_before_erase != tablets_info.size()) {
3347
0
            has_empty_key = true;
3348
0
        }
3349
3350
2
        ret = has_empty_key ? -1 : 0;
3351
        // sort the vector using key's order
3352
2
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3353
2
            return prev.tablet_meta_key < last.tablet_meta_key;
3354
2
        });
3355
2
        std::unique_ptr<Transaction> txn;
3356
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3357
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3358
0
            return -1;
3359
0
        }
3360
2
        std::string tablet_key_end;
3361
2
        if (!tablets_info.empty()) {
3362
2
            if (!has_empty_key && !has_failure) {
3363
2
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3364
2
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3365
2
            } else {
3366
0
                for (auto& tablet_info : tablets_info) {
3367
0
                    txn->remove(tablet_info.tablet_meta_key);
3368
0
                }
3369
0
            }
3370
2
        }
3371
2
        if (is_multi_version) {
3372
0
            for (auto& tablet_info : tablets_info) {
3373
                // Remove all versions of tablet compact stats for recycled tablet
3374
0
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3375
0
                LOG_INFO("remove versioned tablet compact stats key")
3376
0
                        .tag("compact_stats_key", hex(k));
3377
0
                versioned_remove_all(txn.get(), k);
3378
0
            }
3379
0
            for (auto& tablet_info : tablets_info) {
3380
                // Remove all versions of tablet load stats for recycled tablet
3381
0
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3382
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3383
0
                versioned_remove_all(txn.get(), k);
3384
0
            }
3385
0
            for (auto& tablet_info : tablets_info) {
3386
                // Remove all versions of meta tablet for recycled tablet
3387
0
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3388
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3389
0
                versioned_remove_all(txn.get(), k);
3390
0
            }
3391
0
        }
3392
4.00k
        for (auto& tablet_info : tablets_info) {
3393
4.00k
            std::string k;
3394
4.00k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3395
4.00k
            txn->remove(k);
3396
4.00k
        }
3397
4.00k
        for (auto& tablet_info : tablets_info) {
3398
4.00k
            std::string k;
3399
4.00k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3400
4.00k
            txn->remove(k);
3401
4.00k
        }
3402
2
        for (auto& k : init_rs_keys) {
3403
0
            txn->remove(k);
3404
0
        }
3405
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3406
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3407
0
                         << ", err=" << err;
3408
0
            return -1;
3409
0
        }
3410
2
        return ret;
3411
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
3328
48
    auto loop_done = [&, this]() -> int {
3329
48
        int ret = 0;
3330
48
        bool finished = true;
3331
48
        bool has_empty_key = false;
3332
48
        DORIS_CLOUD_DEFER {
3333
48
            init_rs_keys.clear();
3334
48
            has_failure = false;
3335
48
        };
3336
48
        auto tablets_info = sync_executor.when_all(&finished);
3337
48
        if (!finished) {
3338
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3339
1
            return -1;
3340
1
        }
3341
3342
47
        size_t size_before_erase = tablets_info.size();
3343
47
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3344
47
        if (tablets_info.empty()) {
3345
0
            return size_before_erase == 0 ? 0 : -1;
3346
47
        } else if (size_before_erase != tablets_info.size()) {
3347
1
            has_empty_key = true;
3348
1
        }
3349
3350
47
        ret = has_empty_key ? -1 : 0;
3351
        // sort the vector using key's order
3352
47
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3353
47
            return prev.tablet_meta_key < last.tablet_meta_key;
3354
47
        });
3355
47
        std::unique_ptr<Transaction> txn;
3356
47
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3357
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3358
0
            return -1;
3359
0
        }
3360
47
        std::string tablet_key_end;
3361
47
        if (!tablets_info.empty()) {
3362
47
            if (!has_empty_key && !has_failure) {
3363
45
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3364
45
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3365
45
            } else {
3366
8
                for (auto& tablet_info : tablets_info) {
3367
8
                    txn->remove(tablet_info.tablet_meta_key);
3368
8
                }
3369
2
            }
3370
47
        }
3371
47
        if (is_multi_version) {
3372
6
            for (auto& tablet_info : tablets_info) {
3373
                // Remove all versions of tablet compact stats for recycled tablet
3374
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3375
6
                LOG_INFO("remove versioned tablet compact stats key")
3376
6
                        .tag("compact_stats_key", hex(k));
3377
6
                versioned_remove_all(txn.get(), k);
3378
6
            }
3379
6
            for (auto& tablet_info : tablets_info) {
3380
                // Remove all versions of tablet load stats for recycled tablet
3381
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3382
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3383
6
                versioned_remove_all(txn.get(), k);
3384
6
            }
3385
6
            for (auto& tablet_info : tablets_info) {
3386
                // Remove all versions of meta tablet for recycled tablet
3387
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3388
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3389
6
                versioned_remove_all(txn.get(), k);
3390
6
            }
3391
5
        }
3392
248
        for (auto& tablet_info : tablets_info) {
3393
248
            std::string k;
3394
248
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3395
248
            txn->remove(k);
3396
248
        }
3397
248
        for (auto& tablet_info : tablets_info) {
3398
248
            std::string k;
3399
248
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3400
248
            txn->remove(k);
3401
248
        }
3402
47
        for (auto& k : init_rs_keys) {
3403
0
            txn->remove(k);
3404
0
        }
3405
47
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3406
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3407
0
                         << ", err=" << err;
3408
0
            return -1;
3409
0
        }
3410
47
        return ret;
3411
47
    };
3412
3413
54
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
3414
54
                               std::move(loop_done));
3415
54
    if (ret != 0) {
3416
5
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
3417
5
        return ret;
3418
5
    }
3419
3420
    // directly remove tablet stats and tablet jobs of these dropped index or partition
3421
49
    std::unique_ptr<Transaction> txn;
3422
49
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3423
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
3424
0
        return -1;
3425
0
    }
3426
49
    txn->remove(stats_key_begin, stats_key_end);
3427
49
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
3428
49
                 << " end=" << hex(stats_key_end);
3429
49
    txn->remove(job_key_begin, job_key_end);
3430
49
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
3431
49
    std::string schema_key_begin, schema_key_end;
3432
49
    std::string schema_dict_key;
3433
49
    std::string versioned_schema_key_begin, versioned_schema_key_end;
3434
49
    if (partition_id <= 0) {
3435
        // Delete schema kv of this index
3436
15
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
3437
15
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
3438
15
        txn->remove(schema_key_begin, schema_key_end);
3439
15
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
3440
15
                     << " end=" << hex(schema_key_end);
3441
15
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
3442
15
        txn->remove(schema_dict_key);
3443
15
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
3444
15
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
3445
15
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
3446
15
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
3447
15
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
3448
15
                     << " end=" << hex(versioned_schema_key_end);
3449
15
    }
3450
3451
49
    TxnErrorCode err = txn->commit();
3452
49
    if (err != TxnErrorCode::TXN_OK) {
3453
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
3454
0
                     << " err=" << err;
3455
0
        return -1;
3456
0
    }
3457
3458
49
    return ret;
3459
49
}
3460
3461
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
3462
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
3463
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
3464
5.61k
    if (num_segments <= 0) return 0;
3465
3466
5.61k
    std::vector<std::string> file_paths;
3467
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
3468
0
        return -1;
3469
0
    }
3470
3471
    // Process inverted indexes
3472
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
3473
    // default format as v1.
3474
5.61k
    InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
3475
5.61k
    bool delete_rowset_data_by_prefix = false;
3476
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3477
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3478
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3479
0
        delete_rowset_data_by_prefix = true;
3480
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
3481
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
3482
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3483
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3484
10.0k
            }
3485
10.0k
        }
3486
4.80k
        if (rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
3487
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
3488
2.00k
        }
3489
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
3490
        // schema version and index id are not found, delete rowset data by prefix directly.
3491
0
        delete_rowset_data_by_prefix = true;
3492
809
    } else {
3493
        // otherwise, try to get schema kv
3494
809
        InvertedIndexInfo index_info;
3495
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
3496
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
3497
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3498
809
                                 &inverted_index_get_ret);
3499
809
        if (inverted_index_get_ret == 0) {
3500
809
            index_format = index_info.first;
3501
809
            index_ids = index_info.second;
3502
809
        } else if (inverted_index_get_ret == 1) {
3503
            // 1. Schema kv not found means tablet has been recycled
3504
            // Maybe some tablet recycle failed by some bugs
3505
            // We need to delete again to double check
3506
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3507
            // because we are uncertain about the inverted index information.
3508
            // If there are inverted indexes, some data might not be deleted,
3509
            // but this is acceptable as we have made our best effort to delete the data.
3510
0
            LOG_INFO(
3511
0
                    "delete rowset data schema kv not found, need to delete again to double "
3512
0
                    "check")
3513
0
                    .tag("instance_id", instance_id_)
3514
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3515
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
3516
            // Currently index_ids is guaranteed to be empty,
3517
            // but we clear it again here as a safeguard against future code changes
3518
            // that might cause index_ids to no longer be empty
3519
0
            index_format = InvertedIndexStorageFormatPB::V2;
3520
0
            index_ids.clear();
3521
0
        } else {
3522
            // failed to get schema kv, delete rowset data by prefix directly.
3523
0
            delete_rowset_data_by_prefix = true;
3524
0
        }
3525
809
    }
3526
3527
5.61k
    if (delete_rowset_data_by_prefix) {
3528
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
3529
0
                                  rs_meta_pb.rowset_id_v2());
3530
0
    }
3531
3532
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
3533
5.61k
    if (it == accessor_map_.end()) {
3534
1.60k
        LOG_WARNING("instance has no such resource id")
3535
1.60k
                .tag("instance_id", instance_id_)
3536
1.60k
                .tag("resource_id", rs_meta_pb.resource_id());
3537
1.60k
        return -1;
3538
1.60k
    }
3539
4.01k
    auto& accessor = it->second;
3540
3541
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
3542
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
3543
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
3544
20.0k
        add_file_to_delete_if_not_packed(rs_meta_pb, segment_path(tablet_id, rowset_id, i),
3545
20.0k
                                         &file_paths);
3546
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
3547
40.0k
            for (const auto& index_id : index_ids) {
3548
40.0k
                add_file_to_delete_if_not_packed(
3549
40.0k
                        rs_meta_pb,
3550
40.0k
                        inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
3551
40.0k
                                               index_id.second),
3552
40.0k
                        &file_paths);
3553
40.0k
            }
3554
20.0k
        } else if (!index_ids.empty()) {
3555
0
            add_file_to_delete_if_not_packed(
3556
0
                    rs_meta_pb, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
3557
0
        }
3558
20.0k
    }
3559
3560
    // Process delete bitmap - check where it's stored.
3561
4.01k
    DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3562
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3563
4.01k
                                                       &delete_bitmap_storage_type) != 0) {
3564
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3565
0
                .tag("instance_id", instance_id_)
3566
0
                .tag("tablet_id", tablet_id)
3567
0
                .tag("rowset_id", rowset_id);
3568
0
        return -1;
3569
0
    }
3570
4.01k
    if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3571
2.00k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3572
2.00k
    }
3573
    // TODO(AlexYue): seems could do do batch
3574
4.01k
    return accessor->delete_files(file_paths);
3575
4.01k
}
3576
3577
62.3k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3578
62.3k
    LOG_INFO("begin process_packed_file_location_index")
3579
62.3k
            .tag("instance_id", instance_id_)
3580
62.3k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3581
62.3k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3582
62.3k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3583
62.3k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3584
62.3k
    if (index_map.empty()) {
3585
62.3k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3586
62.3k
                .tag("instance_id", instance_id_)
3587
62.3k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3588
62.3k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3589
62.3k
        return 0;
3590
62.3k
    }
3591
3592
18
    struct PackedSmallFileInfo {
3593
18
        std::string small_file_path;
3594
18
    };
3595
18
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3596
18
    packed_file_updates.reserve(index_map.size());
3597
27
    for (const auto& [small_path, index_pb] : index_map) {
3598
27
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3599
0
            continue;
3600
0
        }
3601
27
        packed_file_updates[index_pb.packed_file_path()].push_back(
3602
27
                PackedSmallFileInfo {small_path});
3603
27
    }
3604
18
    if (packed_file_updates.empty()) {
3605
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3606
0
                .tag("instance_id", instance_id_)
3607
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3608
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3609
0
                .tag("index_map_size", index_map.size());
3610
0
        return 0;
3611
0
    }
3612
3613
18
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3614
18
    int ret = 0;
3615
24
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3616
24
        if (small_files.empty()) {
3617
0
            continue;
3618
0
        }
3619
3620
24
        bool success = false;
3621
24
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3622
24
            std::unique_ptr<Transaction> txn;
3623
24
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3624
24
            if (err != TxnErrorCode::TXN_OK) {
3625
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3626
0
                        .tag("instance_id", instance_id_)
3627
0
                        .tag("packed_file_path", packed_file_path)
3628
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3629
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3630
0
                        .tag("err", err);
3631
0
                ret = -1;
3632
0
                break;
3633
0
            }
3634
3635
24
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3636
24
            std::string packed_val;
3637
24
            err = txn->get(packed_key, &packed_val);
3638
24
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3639
0
                LOG_WARNING("packed file info not found when recycling rowset")
3640
0
                        .tag("instance_id", instance_id_)
3641
0
                        .tag("packed_file_path", packed_file_path)
3642
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3643
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3644
0
                        .tag("key", hex(packed_key))
3645
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3646
                // Skip this packed file entry and continue with others
3647
0
                success = true;
3648
0
                break;
3649
0
            }
3650
24
            if (err != TxnErrorCode::TXN_OK) {
3651
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
3652
0
                        .tag("instance_id", instance_id_)
3653
0
                        .tag("packed_file_path", packed_file_path)
3654
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3655
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3656
0
                        .tag("err", err);
3657
0
                ret = -1;
3658
0
                break;
3659
0
            }
3660
3661
24
            cloud::PackedFileInfoPB packed_info;
3662
24
            if (!packed_info.ParseFromString(packed_val)) {
3663
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
3664
0
                        .tag("instance_id", instance_id_)
3665
0
                        .tag("packed_file_path", packed_file_path)
3666
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3667
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3668
0
                ret = -1;
3669
0
                break;
3670
0
            }
3671
3672
24
            LOG_INFO("packed file update check")
3673
24
                    .tag("instance_id", instance_id_)
3674
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3675
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3676
24
                    .tag("merged_file_path", packed_file_path)
3677
24
                    .tag("requested_small_files", small_files.size())
3678
24
                    .tag("merge_entries", packed_info.slices_size());
3679
3680
24
            auto* small_file_entries = packed_info.mutable_slices();
3681
24
            int64_t changed_files = 0;
3682
24
            int64_t missing_entries = 0;
3683
24
            int64_t already_deleted = 0;
3684
27
            for (const auto& small_file_info : small_files) {
3685
27
                bool found = false;
3686
87
                for (auto& small_file_entry : *small_file_entries) {
3687
87
                    if (small_file_entry.path() == small_file_info.small_file_path) {
3688
27
                        if (!small_file_entry.deleted()) {
3689
27
                            small_file_entry.set_deleted(true);
3690
27
                            if (!small_file_entry.corrected()) {
3691
27
                                small_file_entry.set_corrected(true);
3692
27
                            }
3693
27
                            ++changed_files;
3694
27
                        } else {
3695
0
                            ++already_deleted;
3696
0
                        }
3697
27
                        found = true;
3698
27
                        break;
3699
27
                    }
3700
87
                }
3701
27
                if (!found) {
3702
0
                    ++missing_entries;
3703
0
                    LOG_WARNING("packed file info missing small file entry")
3704
0
                            .tag("instance_id", instance_id_)
3705
0
                            .tag("packed_file_path", packed_file_path)
3706
0
                            .tag("small_file_path", small_file_info.small_file_path)
3707
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3708
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
3709
0
                }
3710
27
            }
3711
3712
24
            if (changed_files == 0) {
3713
0
                LOG_INFO("skip merge file update: no merge entries changed")
3714
0
                        .tag("instance_id", instance_id_)
3715
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3716
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3717
0
                        .tag("merged_file_path", packed_file_path)
3718
0
                        .tag("missing_entries", missing_entries)
3719
0
                        .tag("already_deleted", already_deleted)
3720
0
                        .tag("requested_small_files", small_files.size())
3721
0
                        .tag("merge_entries", packed_info.slices_size());
3722
0
                success = true;
3723
0
                break;
3724
0
            }
3725
3726
            // Calculate remaining files
3727
24
            int64_t left_file_count = 0;
3728
24
            int64_t left_file_bytes = 0;
3729
141
            for (const auto& small_file_entry : packed_info.slices()) {
3730
141
                if (!small_file_entry.deleted()) {
3731
57
                    ++left_file_count;
3732
57
                    left_file_bytes += small_file_entry.size();
3733
57
                }
3734
141
            }
3735
24
            packed_info.set_remaining_slice_bytes(left_file_bytes);
3736
24
            packed_info.set_ref_cnt(left_file_count);
3737
24
            LOG_INFO("updated packed file reference info")
3738
24
                    .tag("instance_id", instance_id_)
3739
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3740
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3741
24
                    .tag("packed_file_path", packed_file_path)
3742
24
                    .tag("ref_cnt", left_file_count)
3743
24
                    .tag("left_file_bytes", left_file_bytes);
3744
3745
24
            if (left_file_count == 0) {
3746
7
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3747
7
            }
3748
3749
24
            std::string updated_val;
3750
24
            if (!packed_info.SerializeToString(&updated_val)) {
3751
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
3752
0
                        .tag("instance_id", instance_id_)
3753
0
                        .tag("packed_file_path", packed_file_path)
3754
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3755
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3756
0
                ret = -1;
3757
0
                break;
3758
0
            }
3759
3760
24
            txn->put(packed_key, updated_val);
3761
24
            err = txn->commit();
3762
24
            if (err == TxnErrorCode::TXN_OK) {
3763
24
                success = true;
3764
24
                if (left_file_count == 0) {
3765
7
                    LOG_INFO("packed file ready to delete, deleting immediately")
3766
7
                            .tag("instance_id", instance_id_)
3767
7
                            .tag("packed_file_path", packed_file_path);
3768
7
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3769
0
                        ret = -1;
3770
0
                    }
3771
7
                }
3772
24
                break;
3773
24
            }
3774
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
3775
0
                if (attempt >= max_retry_times) {
3776
0
                    LOG_WARNING("packed file info update conflict after max retry")
3777
0
                            .tag("instance_id", instance_id_)
3778
0
                            .tag("packed_file_path", packed_file_path)
3779
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3780
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
3781
0
                            .tag("changed_files", changed_files)
3782
0
                            .tag("attempt", attempt);
3783
0
                    ret = -1;
3784
0
                    break;
3785
0
                }
3786
0
                LOG_WARNING("packed file info update conflict, retrying")
3787
0
                        .tag("instance_id", instance_id_)
3788
0
                        .tag("packed_file_path", packed_file_path)
3789
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3790
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3791
0
                        .tag("changed_files", changed_files)
3792
0
                        .tag("attempt", attempt);
3793
0
                sleep_for_packed_file_retry();
3794
0
                continue;
3795
0
            }
3796
3797
0
            LOG_WARNING("failed to commit packed file info update")
3798
0
                    .tag("instance_id", instance_id_)
3799
0
                    .tag("packed_file_path", packed_file_path)
3800
0
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3801
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3802
0
                    .tag("err", err)
3803
0
                    .tag("changed_files", changed_files);
3804
0
            ret = -1;
3805
0
            break;
3806
0
        }
3807
3808
24
        if (!success) {
3809
0
            ret = -1;
3810
0
        }
3811
24
    }
3812
3813
18
    return ret;
3814
18
}
3815
3816
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(
3817
        int64_t tablet_id, const std::string& rowset_id,
3818
58.2k
        DeleteBitmapStorageType* out_storage_type) {
3819
58.2k
    if (out_storage_type) {
3820
58.2k
        *out_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3821
58.2k
    }
3822
3823
    // Get delete bitmap storage info from FDB
3824
58.2k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
3825
58.2k
    std::unique_ptr<Transaction> txn;
3826
58.2k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
3827
58.2k
    if (err != TxnErrorCode::TXN_OK) {
3828
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
3829
0
                .tag("instance_id", instance_id_)
3830
0
                .tag("tablet_id", tablet_id)
3831
0
                .tag("rowset_id", rowset_id)
3832
0
                .tag("err", err);
3833
0
        return -1;
3834
0
    }
3835
3836
58.2k
    std::string dbm_val;
3837
58.2k
    err = txn->get(dbm_key, &dbm_val);
3838
58.2k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3839
        // No delete bitmap for this rowset, nothing to do
3840
4.66k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
3841
4.66k
                .tag("instance_id", instance_id_)
3842
4.66k
                .tag("tablet_id", tablet_id)
3843
4.66k
                .tag("rowset_id", rowset_id);
3844
4.66k
        return 0;
3845
4.66k
    }
3846
53.5k
    if (err != TxnErrorCode::TXN_OK) {
3847
0
        LOG_WARNING("failed to get delete bitmap storage")
3848
0
                .tag("instance_id", instance_id_)
3849
0
                .tag("tablet_id", tablet_id)
3850
0
                .tag("rowset_id", rowset_id)
3851
0
                .tag("err", err);
3852
0
        return -1;
3853
0
    }
3854
3855
53.5k
    DeleteBitmapStoragePB storage;
3856
53.5k
    if (!storage.ParseFromString(dbm_val)) {
3857
0
        LOG_WARNING("failed to parse delete bitmap storage")
3858
0
                .tag("instance_id", instance_id_)
3859
0
                .tag("tablet_id", tablet_id)
3860
0
                .tag("rowset_id", rowset_id);
3861
0
        return -1;
3862
0
    }
3863
3864
53.5k
    if (storage.store_in_fdb()) {
3865
0
        if (out_storage_type) {
3866
0
            *out_storage_type = DeleteBitmapStorageType::IN_FDB;
3867
0
        }
3868
0
        return 0;
3869
0
    }
3870
3871
    // Check if delete bitmap is stored in standalone file.
3872
53.5k
    if (!storage.has_packed_slice_location() ||
3873
53.5k
        storage.packed_slice_location().packed_file_path().empty()) {
3874
53.5k
        if (out_storage_type) {
3875
53.5k
            *out_storage_type = DeleteBitmapStorageType::STANDALONE_FILE;
3876
53.5k
        }
3877
53.5k
        return 0;
3878
53.5k
    }
3879
3880
18.4E
    if (out_storage_type) {
3881
0
        *out_storage_type = DeleteBitmapStorageType::PACKED_FILE;
3882
0
    }
3883
3884
18.4E
    const auto& packed_loc = storage.packed_slice_location();
3885
18.4E
    const std::string& packed_file_path = packed_loc.packed_file_path();
3886
3887
18.4E
    LOG_INFO("decrementing delete bitmap packed file ref count")
3888
18.4E
            .tag("instance_id", instance_id_)
3889
18.4E
            .tag("tablet_id", tablet_id)
3890
18.4E
            .tag("rowset_id", rowset_id)
3891
18.4E
            .tag("packed_file_path", packed_file_path);
3892
3893
18.4E
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3894
18.4E
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3895
0
        std::unique_ptr<Transaction> update_txn;
3896
0
        err = txn_kv_->create_txn(&update_txn);
3897
0
        if (err != TxnErrorCode::TXN_OK) {
3898
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
3899
0
                    .tag("instance_id", instance_id_)
3900
0
                    .tag("tablet_id", tablet_id)
3901
0
                    .tag("rowset_id", rowset_id)
3902
0
                    .tag("err", err);
3903
0
            return -1;
3904
0
        }
3905
3906
0
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3907
0
        std::string packed_val;
3908
0
        err = update_txn->get(packed_key, &packed_val);
3909
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3910
0
            LOG_WARNING("packed file info not found for delete bitmap")
3911
0
                    .tag("instance_id", instance_id_)
3912
0
                    .tag("tablet_id", tablet_id)
3913
0
                    .tag("rowset_id", rowset_id)
3914
0
                    .tag("packed_file_path", packed_file_path);
3915
0
            return 0;
3916
0
        }
3917
0
        if (err != TxnErrorCode::TXN_OK) {
3918
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
3919
0
                    .tag("instance_id", instance_id_)
3920
0
                    .tag("tablet_id", tablet_id)
3921
0
                    .tag("rowset_id", rowset_id)
3922
0
                    .tag("packed_file_path", packed_file_path)
3923
0
                    .tag("err", err);
3924
0
            return -1;
3925
0
        }
3926
3927
0
        cloud::PackedFileInfoPB packed_info;
3928
0
        if (!packed_info.ParseFromString(packed_val)) {
3929
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
3930
0
                    .tag("instance_id", instance_id_)
3931
0
                    .tag("tablet_id", tablet_id)
3932
0
                    .tag("rowset_id", rowset_id)
3933
0
                    .tag("packed_file_path", packed_file_path);
3934
0
            return -1;
3935
0
        }
3936
3937
        // Find and mark the small file entry as deleted
3938
        // Use tablet_id and rowset_id to match entry instead of path,
3939
        // because path format may vary with path_version (with or without shard prefix)
3940
0
        auto* entries = packed_info.mutable_slices();
3941
0
        bool found = false;
3942
0
        bool already_deleted = false;
3943
0
        for (auto& entry : *entries) {
3944
0
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
3945
0
                if (!entry.deleted()) {
3946
0
                    entry.set_deleted(true);
3947
0
                    if (!entry.corrected()) {
3948
0
                        entry.set_corrected(true);
3949
0
                    }
3950
0
                } else {
3951
0
                    already_deleted = true;
3952
0
                }
3953
0
                found = true;
3954
0
                break;
3955
0
            }
3956
0
        }
3957
3958
0
        if (!found) {
3959
0
            LOG_WARNING("delete bitmap entry not found in packed file")
3960
0
                    .tag("instance_id", instance_id_)
3961
0
                    .tag("tablet_id", tablet_id)
3962
0
                    .tag("rowset_id", rowset_id)
3963
0
                    .tag("packed_file_path", packed_file_path);
3964
0
            return 0;
3965
0
        }
3966
3967
0
        if (already_deleted) {
3968
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
3969
0
                    .tag("instance_id", instance_id_)
3970
0
                    .tag("tablet_id", tablet_id)
3971
0
                    .tag("rowset_id", rowset_id)
3972
0
                    .tag("packed_file_path", packed_file_path);
3973
0
            return 0;
3974
0
        }
3975
3976
        // Calculate remaining files
3977
0
        int64_t left_file_count = 0;
3978
0
        int64_t left_file_bytes = 0;
3979
0
        for (const auto& entry : packed_info.slices()) {
3980
0
            if (!entry.deleted()) {
3981
0
                ++left_file_count;
3982
0
                left_file_bytes += entry.size();
3983
0
            }
3984
0
        }
3985
0
        packed_info.set_remaining_slice_bytes(left_file_bytes);
3986
0
        packed_info.set_ref_cnt(left_file_count);
3987
3988
0
        if (left_file_count == 0) {
3989
0
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3990
0
        }
3991
3992
0
        std::string updated_val;
3993
0
        if (!packed_info.SerializeToString(&updated_val)) {
3994
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
3995
0
                    .tag("instance_id", instance_id_)
3996
0
                    .tag("tablet_id", tablet_id)
3997
0
                    .tag("rowset_id", rowset_id)
3998
0
                    .tag("packed_file_path", packed_file_path);
3999
0
            return -1;
4000
0
        }
4001
4002
0
        update_txn->put(packed_key, updated_val);
4003
0
        err = update_txn->commit();
4004
0
        if (err == TxnErrorCode::TXN_OK) {
4005
0
            LOG_INFO("delete bitmap packed file ref count decremented")
4006
0
                    .tag("instance_id", instance_id_)
4007
0
                    .tag("tablet_id", tablet_id)
4008
0
                    .tag("rowset_id", rowset_id)
4009
0
                    .tag("packed_file_path", packed_file_path)
4010
0
                    .tag("left_file_count", left_file_count);
4011
0
            if (left_file_count == 0) {
4012
0
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4013
0
                    return -1;
4014
0
                }
4015
0
            }
4016
0
            return 0;
4017
0
        }
4018
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4019
0
            if (attempt >= max_retry_times) {
4020
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
4021
0
                        .tag("instance_id", instance_id_)
4022
0
                        .tag("tablet_id", tablet_id)
4023
0
                        .tag("rowset_id", rowset_id)
4024
0
                        .tag("packed_file_path", packed_file_path)
4025
0
                        .tag("attempt", attempt);
4026
0
                return -1;
4027
0
            }
4028
0
            sleep_for_packed_file_retry();
4029
0
            continue;
4030
0
        }
4031
4032
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
4033
0
                .tag("instance_id", instance_id_)
4034
0
                .tag("tablet_id", tablet_id)
4035
0
                .tag("rowset_id", rowset_id)
4036
0
                .tag("packed_file_path", packed_file_path)
4037
0
                .tag("err", err);
4038
0
        return -1;
4039
0
    }
4040
4041
18.4E
    return -1;
4042
18.4E
}
4043
4044
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
4045
                                                const std::string& packed_key,
4046
7
                                                const cloud::PackedFileInfoPB& packed_info) {
4047
7
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
4048
0
        LOG_WARNING("packed file missing resource id when recycling")
4049
0
                .tag("instance_id", instance_id_)
4050
0
                .tag("packed_file_path", packed_file_path);
4051
0
        return -1;
4052
0
    }
4053
4054
7
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
4055
7
    if (!accessor) {
4056
0
        LOG_WARNING("no accessor available to delete packed file")
4057
0
                .tag("instance_id", instance_id_)
4058
0
                .tag("packed_file_path", packed_file_path)
4059
0
                .tag("resource_id", packed_info.resource_id());
4060
0
        return -1;
4061
0
    }
4062
4063
7
    int del_ret = accessor->delete_file(packed_file_path);
4064
7
    if (del_ret != 0 && del_ret != 1) {
4065
0
        LOG_WARNING("failed to delete packed file")
4066
0
                .tag("instance_id", instance_id_)
4067
0
                .tag("packed_file_path", packed_file_path)
4068
0
                .tag("resource_id", resource_id)
4069
0
                .tag("ret", del_ret);
4070
0
        return -1;
4071
0
    }
4072
7
    if (del_ret == 1) {
4073
0
        LOG_INFO("packed file already removed")
4074
0
                .tag("instance_id", instance_id_)
4075
0
                .tag("packed_file_path", packed_file_path)
4076
0
                .tag("resource_id", resource_id);
4077
7
    } else {
4078
7
        LOG_INFO("deleted packed file")
4079
7
                .tag("instance_id", instance_id_)
4080
7
                .tag("packed_file_path", packed_file_path)
4081
7
                .tag("resource_id", resource_id);
4082
7
    }
4083
4084
7
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
4085
7
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4086
7
        std::unique_ptr<Transaction> del_txn;
4087
7
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
4088
7
        if (err != TxnErrorCode::TXN_OK) {
4089
0
            LOG_WARNING("failed to create txn when removing packed file kv")
4090
0
                    .tag("instance_id", instance_id_)
4091
0
                    .tag("packed_file_path", packed_file_path)
4092
0
                    .tag("attempt", attempt)
4093
0
                    .tag("err", err);
4094
0
            return -1;
4095
0
        }
4096
4097
7
        std::string latest_val;
4098
7
        err = del_txn->get(packed_key, &latest_val);
4099
7
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4100
0
            return 0;
4101
0
        }
4102
7
        if (err != TxnErrorCode::TXN_OK) {
4103
0
            LOG_WARNING("failed to re-read packed file kv before removal")
4104
0
                    .tag("instance_id", instance_id_)
4105
0
                    .tag("packed_file_path", packed_file_path)
4106
0
                    .tag("attempt", attempt)
4107
0
                    .tag("err", err);
4108
0
            return -1;
4109
0
        }
4110
4111
7
        cloud::PackedFileInfoPB latest_info;
4112
7
        if (!latest_info.ParseFromString(latest_val)) {
4113
0
            LOG_WARNING("failed to parse packed file info before removal")
4114
0
                    .tag("instance_id", instance_id_)
4115
0
                    .tag("packed_file_path", packed_file_path)
4116
0
                    .tag("attempt", attempt);
4117
0
            return -1;
4118
0
        }
4119
4120
7
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
4121
7
              latest_info.ref_cnt() == 0)) {
4122
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
4123
0
                    .tag("instance_id", instance_id_)
4124
0
                    .tag("packed_file_path", packed_file_path)
4125
0
                    .tag("attempt", attempt);
4126
0
            return 0;
4127
0
        }
4128
4129
7
        del_txn->remove(packed_key);
4130
7
        err = del_txn->commit();
4131
7
        if (err == TxnErrorCode::TXN_OK) {
4132
7
            LOG_INFO("removed packed file metadata")
4133
7
                    .tag("instance_id", instance_id_)
4134
7
                    .tag("packed_file_path", packed_file_path);
4135
7
            return 0;
4136
7
        }
4137
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4138
0
            if (attempt >= max_retry_times) {
4139
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
4140
0
                        .tag("instance_id", instance_id_)
4141
0
                        .tag("packed_file_path", packed_file_path)
4142
0
                        .tag("attempt", attempt);
4143
0
                return -1;
4144
0
            }
4145
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
4146
0
                    .tag("instance_id", instance_id_)
4147
0
                    .tag("packed_file_path", packed_file_path)
4148
0
                    .tag("attempt", attempt);
4149
0
            sleep_for_packed_file_retry();
4150
0
            continue;
4151
0
        }
4152
0
        LOG_WARNING("failed to remove packed file kv")
4153
0
                .tag("instance_id", instance_id_)
4154
0
                .tag("packed_file_path", packed_file_path)
4155
0
                .tag("attempt", attempt)
4156
0
                .tag("err", err);
4157
0
        return -1;
4158
0
    }
4159
0
    return -1;
4160
7
}
4161
4162
int InstanceRecycler::delete_rowset_data(
4163
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
4164
56
        RecyclerMetricsContext& metrics_context) {
4165
56
    int ret = 0;
4166
    // resource_id -> file_paths
4167
56
    std::map<std::string, std::vector<std::string>> resource_file_paths;
4168
    // (resource_id, tablet_id, rowset_id)
4169
56
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
4170
56
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
4171
4172
56.2k
    for (const auto& [_, rs] : rowsets) {
4173
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
4174
        // due to aborted schema change.
4175
56.2k
        if (is_formal_rowset) {
4176
3.19k
            std::lock_guard lock(recycled_tablets_mtx_);
4177
3.19k
            if (recycled_tablets_.count(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
4178
                // Tablet has been recycled and this rowset has no packed slices, so file data
4179
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
4180
                // slice info must still run to decrement packed file ref counts.
4181
0
                continue;
4182
0
            }
4183
3.19k
        }
4184
4185
56.2k
        int64_t num_segments = rs.num_segments();
4186
        // Check num_segments before accessor lookup, because empty rowsets
4187
        // (e.g. base compaction output of empty rowsets) may have no resource_id
4188
        // set. Skipping them early avoids a spurious "no such resource id" error
4189
        // that marks the entire batch as failed and prevents txn_remove from
4190
        // cleaning up recycle KV keys.
4191
56.2k
        if (num_segments <= 0) {
4192
0
            metrics_context.total_recycled_num++;
4193
0
            metrics_context.total_recycled_data_size += rs.total_disk_size();
4194
0
            continue;
4195
0
        }
4196
4197
56.2k
        auto it = accessor_map_.find(rs.resource_id());
4198
        // possible if the accessor is not initilized correctly
4199
56.2k
        if (it == accessor_map_.end()) [[unlikely]] {
4200
2.00k
            LOG_WARNING("instance has no such resource id")
4201
2.00k
                    .tag("instance_id", instance_id_)
4202
2.00k
                    .tag("resource_id", rs.resource_id());
4203
2.00k
            ret = -1;
4204
2.00k
            continue;
4205
2.00k
        }
4206
4207
54.2k
        auto& file_paths = resource_file_paths[rs.resource_id()];
4208
54.2k
        const auto& rowset_id = rs.rowset_id_v2();
4209
54.2k
        int64_t tablet_id = rs.tablet_id();
4210
54.2k
        LOG_INFO("recycle rowset merge index size")
4211
54.2k
                .tag("instance_id", instance_id_)
4212
54.2k
                .tag("tablet_id", tablet_id)
4213
54.2k
                .tag("rowset_id", rowset_id)
4214
54.2k
                .tag("merge_index_size", rs.packed_slice_locations_size());
4215
54.2k
        if (decrement_packed_file_ref_counts(rs) != 0) {
4216
0
            ret = -1;
4217
0
            continue;
4218
0
        }
4219
4220
        // Process delete bitmap - check where it's stored.
4221
54.2k
        DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4222
54.2k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
4223
54.2k
                                                           &delete_bitmap_storage_type) != 0) {
4224
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
4225
0
                    .tag("instance_id", instance_id_)
4226
0
                    .tag("tablet_id", tablet_id)
4227
0
                    .tag("rowset_id", rowset_id);
4228
0
            ret = -1;
4229
0
            continue;
4230
0
        }
4231
54.2k
        if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
4232
51.5k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
4233
51.5k
        }
4234
4235
        // Process inverted indexes
4236
54.2k
        std::vector<std::pair<int64_t, std::string>> index_ids;
4237
        // default format as v1.
4238
54.2k
        InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
4239
54.2k
        int inverted_index_get_ret = 0;
4240
54.2k
        if (rs.has_tablet_schema()) {
4241
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
4242
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
4243
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
4244
53.5k
                }
4245
53.5k
            }
4246
26.6k
            if (rs.tablet_schema().has_inverted_index_storage_format()) {
4247
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
4248
26.5k
            }
4249
27.6k
        } else {
4250
27.6k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
4251
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
4252
0
                                "instance_id="
4253
0
                             << instance_id_ << " tablet_id=" << tablet_id
4254
0
                             << " rowset_id=" << rowset_id;
4255
0
                ret = -1;
4256
0
                continue;
4257
0
            }
4258
27.6k
            InvertedIndexInfo index_info;
4259
27.6k
            inverted_index_get_ret =
4260
27.6k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
4261
27.6k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
4262
27.6k
                                     &inverted_index_get_ret);
4263
27.6k
            if (inverted_index_get_ret == 0) {
4264
27.1k
                index_format = index_info.first;
4265
27.1k
                index_ids = index_info.second;
4266
27.1k
            } else if (inverted_index_get_ret == 1) {
4267
                // 1. Schema kv not found means tablet has been recycled
4268
                // Maybe some tablet recycle failed by some bugs
4269
                // We need to delete again to double check
4270
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
4271
                // because we are uncertain about the inverted index information.
4272
                // If there are inverted indexes, some data might not be deleted,
4273
                // but this is acceptable as we have made our best effort to delete the data.
4274
507
                LOG_INFO(
4275
507
                        "delete rowset data schema kv not found, need to delete again to "
4276
507
                        "double "
4277
507
                        "check")
4278
507
                        .tag("instance_id", instance_id_)
4279
507
                        .tag("tablet_id", tablet_id)
4280
507
                        .tag("rowset", rs.ShortDebugString());
4281
                // Currently index_ids is guaranteed to be empty,
4282
                // but we clear it again here as a safeguard against future code changes
4283
                // that might cause index_ids to no longer be empty
4284
507
                index_format = InvertedIndexStorageFormatPB::V2;
4285
507
                index_ids.clear();
4286
18.4E
            } else {
4287
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
4288
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4289
18.4E
                ret = -1;
4290
18.4E
                continue;
4291
18.4E
            }
4292
27.6k
        }
4293
54.2k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
4294
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
4295
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
4296
10
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
4297
10
            continue;
4298
10
        }
4299
324k
        for (int64_t i = 0; i < num_segments; ++i) {
4300
269k
            add_file_to_delete_if_not_packed(rs, segment_path(tablet_id, rowset_id, i),
4301
269k
                                             &file_paths);
4302
269k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
4303
535k
                for (const auto& index_id : index_ids) {
4304
535k
                    add_file_to_delete_if_not_packed(
4305
535k
                            rs,
4306
535k
                            inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
4307
535k
                                                   index_id.second),
4308
535k
                            &file_paths);
4309
535k
                }
4310
267k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
4311
                // try to recycle inverted index v2 when get_ret == 1
4312
                // we treat schema not found as if it has a v2 format inverted index
4313
                // to reduce chance of data leakage
4314
2.50k
                if (inverted_index_get_ret == 1) {
4315
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
4316
2.50k
                            .tag("instance_id", instance_id_)
4317
2.50k
                            .tag("inverted index v2 path",
4318
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, i));
4319
2.50k
                }
4320
2.50k
                add_file_to_delete_if_not_packed(
4321
2.50k
                        rs, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
4322
2.50k
            }
4323
269k
        }
4324
54.2k
    }
4325
4326
56
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
4327
56
                                                 "delete_rowset_data",
4328
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
4328
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
4328
52
                                                 [](const int& ret) { return ret != 0; });
4329
56
    for (auto& [resource_id, file_paths] : resource_file_paths) {
4330
47
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4331
47
            DCHECK(accessor_map_.count(*rid))
4332
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4333
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4334
47
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4335
47
                                     &accessor_map_);
4336
47
            if (!accessor_map_.contains(*rid)) {
4337
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4338
0
                        .tag("resource_id", resource_id)
4339
0
                        .tag("instance_id", instance_id_);
4340
0
                return -1;
4341
0
            }
4342
47
            auto& accessor = accessor_map_[*rid];
4343
47
            int ret = accessor->delete_files(*paths);
4344
47
            if (!ret) {
4345
                // deduplication of different files with the same rowset id
4346
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4347
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4348
47
                std::set<std::string> deleted_rowset_id;
4349
4350
47
                std::for_each(paths->begin(), paths->end(),
4351
47
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4352
855k
                               this](const std::string& path) {
4353
855k
                                  std::vector<std::string> str;
4354
855k
                                  butil::SplitString(path, '/', &str);
4355
855k
                                  std::string rowset_id;
4356
855k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4357
852k
                                      rowset_id = str.back().substr(0, pos);
4358
852k
                                  } else {
4359
3.50k
                                      if (path.find("packed_file/") != std::string::npos) {
4360
0
                                          return; // packed files do not have rowset_id encoded
4361
0
                                      }
4362
3.50k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4363
3.50k
                                      return;
4364
3.50k
                                  }
4365
852k
                                  auto rs_meta = rowsets.find(rowset_id);
4366
852k
                                  if (rs_meta != rowsets.end() &&
4367
855k
                                      !deleted_rowset_id.contains(rowset_id)) {
4368
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
4369
54.1k
                                      metrics_context.total_recycled_data_size +=
4370
54.1k
                                              rs_meta->second.total_disk_size();
4371
54.1k
                                      segment_metrics_context_.total_recycled_num +=
4372
54.1k
                                              rs_meta->second.num_segments();
4373
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
4374
54.1k
                                              rs_meta->second.total_disk_size();
4375
54.1k
                                      metrics_context.total_recycled_num++;
4376
54.1k
                                  }
4377
852k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
4352
7
                               this](const std::string& path) {
4353
7
                                  std::vector<std::string> str;
4354
7
                                  butil::SplitString(path, '/', &str);
4355
7
                                  std::string rowset_id;
4356
7
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4357
7
                                      rowset_id = str.back().substr(0, pos);
4358
7
                                  } else {
4359
0
                                      if (path.find("packed_file/") != std::string::npos) {
4360
0
                                          return; // packed files do not have rowset_id encoded
4361
0
                                      }
4362
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4363
0
                                      return;
4364
0
                                  }
4365
7
                                  auto rs_meta = rowsets.find(rowset_id);
4366
7
                                  if (rs_meta != rowsets.end() &&
4367
7
                                      !deleted_rowset_id.contains(rowset_id)) {
4368
7
                                      deleted_rowset_id.emplace(rowset_id);
4369
7
                                      metrics_context.total_recycled_data_size +=
4370
7
                                              rs_meta->second.total_disk_size();
4371
7
                                      segment_metrics_context_.total_recycled_num +=
4372
7
                                              rs_meta->second.num_segments();
4373
7
                                      segment_metrics_context_.total_recycled_data_size +=
4374
7
                                              rs_meta->second.total_disk_size();
4375
7
                                      metrics_context.total_recycled_num++;
4376
7
                                  }
4377
7
                              });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
4352
855k
                               this](const std::string& path) {
4353
855k
                                  std::vector<std::string> str;
4354
855k
                                  butil::SplitString(path, '/', &str);
4355
855k
                                  std::string rowset_id;
4356
855k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4357
852k
                                      rowset_id = str.back().substr(0, pos);
4358
852k
                                  } else {
4359
3.50k
                                      if (path.find("packed_file/") != std::string::npos) {
4360
0
                                          return; // packed files do not have rowset_id encoded
4361
0
                                      }
4362
3.50k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4363
3.50k
                                      return;
4364
3.50k
                                  }
4365
852k
                                  auto rs_meta = rowsets.find(rowset_id);
4366
852k
                                  if (rs_meta != rowsets.end() &&
4367
855k
                                      !deleted_rowset_id.contains(rowset_id)) {
4368
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
4369
54.1k
                                      metrics_context.total_recycled_data_size +=
4370
54.1k
                                              rs_meta->second.total_disk_size();
4371
54.1k
                                      segment_metrics_context_.total_recycled_num +=
4372
54.1k
                                              rs_meta->second.num_segments();
4373
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
4374
54.1k
                                              rs_meta->second.total_disk_size();
4375
54.1k
                                      metrics_context.total_recycled_num++;
4376
54.1k
                                  }
4377
852k
                              });
4378
47
            }
4379
47
            return ret;
4380
47
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4330
5
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4331
5
            DCHECK(accessor_map_.count(*rid))
4332
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4333
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4334
5
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4335
5
                                     &accessor_map_);
4336
5
            if (!accessor_map_.contains(*rid)) {
4337
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4338
0
                        .tag("resource_id", resource_id)
4339
0
                        .tag("instance_id", instance_id_);
4340
0
                return -1;
4341
0
            }
4342
5
            auto& accessor = accessor_map_[*rid];
4343
5
            int ret = accessor->delete_files(*paths);
4344
5
            if (!ret) {
4345
                // deduplication of different files with the same rowset id
4346
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4347
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4348
5
                std::set<std::string> deleted_rowset_id;
4349
4350
5
                std::for_each(paths->begin(), paths->end(),
4351
5
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4352
5
                               this](const std::string& path) {
4353
5
                                  std::vector<std::string> str;
4354
5
                                  butil::SplitString(path, '/', &str);
4355
5
                                  std::string rowset_id;
4356
5
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4357
5
                                      rowset_id = str.back().substr(0, pos);
4358
5
                                  } else {
4359
5
                                      if (path.find("packed_file/") != std::string::npos) {
4360
5
                                          return; // packed files do not have rowset_id encoded
4361
5
                                      }
4362
5
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4363
5
                                      return;
4364
5
                                  }
4365
5
                                  auto rs_meta = rowsets.find(rowset_id);
4366
5
                                  if (rs_meta != rowsets.end() &&
4367
5
                                      !deleted_rowset_id.contains(rowset_id)) {
4368
5
                                      deleted_rowset_id.emplace(rowset_id);
4369
5
                                      metrics_context.total_recycled_data_size +=
4370
5
                                              rs_meta->second.total_disk_size();
4371
5
                                      segment_metrics_context_.total_recycled_num +=
4372
5
                                              rs_meta->second.num_segments();
4373
5
                                      segment_metrics_context_.total_recycled_data_size +=
4374
5
                                              rs_meta->second.total_disk_size();
4375
5
                                      metrics_context.total_recycled_num++;
4376
5
                                  }
4377
5
                              });
4378
5
            }
4379
5
            return ret;
4380
5
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4330
42
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4331
42
            DCHECK(accessor_map_.count(*rid))
4332
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4333
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4334
42
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4335
42
                                     &accessor_map_);
4336
42
            if (!accessor_map_.contains(*rid)) {
4337
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4338
0
                        .tag("resource_id", resource_id)
4339
0
                        .tag("instance_id", instance_id_);
4340
0
                return -1;
4341
0
            }
4342
42
            auto& accessor = accessor_map_[*rid];
4343
42
            int ret = accessor->delete_files(*paths);
4344
42
            if (!ret) {
4345
                // deduplication of different files with the same rowset id
4346
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4347
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4348
42
                std::set<std::string> deleted_rowset_id;
4349
4350
42
                std::for_each(paths->begin(), paths->end(),
4351
42
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4352
42
                               this](const std::string& path) {
4353
42
                                  std::vector<std::string> str;
4354
42
                                  butil::SplitString(path, '/', &str);
4355
42
                                  std::string rowset_id;
4356
42
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4357
42
                                      rowset_id = str.back().substr(0, pos);
4358
42
                                  } else {
4359
42
                                      if (path.find("packed_file/") != std::string::npos) {
4360
42
                                          return; // packed files do not have rowset_id encoded
4361
42
                                      }
4362
42
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4363
42
                                      return;
4364
42
                                  }
4365
42
                                  auto rs_meta = rowsets.find(rowset_id);
4366
42
                                  if (rs_meta != rowsets.end() &&
4367
42
                                      !deleted_rowset_id.contains(rowset_id)) {
4368
42
                                      deleted_rowset_id.emplace(rowset_id);
4369
42
                                      metrics_context.total_recycled_data_size +=
4370
42
                                              rs_meta->second.total_disk_size();
4371
42
                                      segment_metrics_context_.total_recycled_num +=
4372
42
                                              rs_meta->second.num_segments();
4373
42
                                      segment_metrics_context_.total_recycled_data_size +=
4374
42
                                              rs_meta->second.total_disk_size();
4375
42
                                      metrics_context.total_recycled_num++;
4376
42
                                  }
4377
42
                              });
4378
42
            }
4379
42
            return ret;
4380
42
        });
4381
47
    }
4382
56
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
4383
10
        LOG_INFO(
4384
10
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
4385
10
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
4386
10
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
4387
10
        concurrent_delete_executor.add([&]() -> int {
4388
10
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4389
10
            if (!ret) {
4390
10
                auto rs = rowsets.at(rowset_id);
4391
10
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4392
10
                metrics_context.total_recycled_num++;
4393
10
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4394
10
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4395
10
            }
4396
10
            return ret;
4397
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
4387
10
        concurrent_delete_executor.add([&]() -> int {
4388
10
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4389
10
            if (!ret) {
4390
10
                auto rs = rowsets.at(rowset_id);
4391
10
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4392
10
                metrics_context.total_recycled_num++;
4393
10
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4394
10
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4395
10
            }
4396
10
            return ret;
4397
10
        });
4398
10
    }
4399
4400
56
    bool finished = true;
4401
56
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4402
57
    for (int r : rets) {
4403
57
        if (r != 0) {
4404
0
            ret = -1;
4405
0
            break;
4406
0
        }
4407
57
    }
4408
56
    ret = finished ? ret : -1;
4409
56
    return ret;
4410
56
}
4411
4412
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
4413
3.31k
                                         const std::string& rowset_id) {
4414
3.31k
    auto it = accessor_map_.find(resource_id);
4415
3.31k
    if (it == accessor_map_.end()) {
4416
400
        LOG_WARNING("instance has no such resource id")
4417
400
                .tag("instance_id", instance_id_)
4418
400
                .tag("resource_id", resource_id)
4419
400
                .tag("tablet_id", tablet_id)
4420
400
                .tag("rowset_id", rowset_id);
4421
400
        return -1;
4422
400
    }
4423
2.91k
    auto& accessor = it->second;
4424
2.91k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
4425
3.31k
}
4426
4427
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
4428
4
    if (key.empty()) {
4429
0
        return false;
4430
0
    }
4431
4
    std::string_view key_view = key;
4432
4
    key_view.remove_prefix(1); // remove keyspace prefix
4433
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
4434
4
    if (decode_key(&key_view, &decoded) != 0) {
4435
0
        return false;
4436
0
    }
4437
4
    if (decoded.size() < 4) {
4438
0
        return false;
4439
0
    }
4440
4
    try {
4441
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
4442
4
    } catch (const std::bad_variant_access&) {
4443
0
        return false;
4444
0
    }
4445
4
    return true;
4446
4
}
4447
4448
14
int InstanceRecycler::recycle_packed_files() {
4449
14
    const std::string task_name = "recycle_packed_files";
4450
14
    auto start_tp = steady_clock::now();
4451
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
4452
14
    int ret = 0;
4453
14
    PackedFileRecycleStats stats;
4454
4455
14
    register_recycle_task(task_name, start_time);
4456
14
    DORIS_CLOUD_DEFER {
4457
14
        unregister_recycle_task(task_name);
4458
14
        int64_t cost =
4459
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4460
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4461
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4462
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4463
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4464
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4465
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4466
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4467
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4468
14
                                                             stats.bytes_object_deleted);
4469
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4470
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4471
14
                .tag("instance_id", instance_id_)
4472
14
                .tag("num_scanned", stats.num_scanned)
4473
14
                .tag("num_corrected", stats.num_corrected)
4474
14
                .tag("num_deleted", stats.num_deleted)
4475
14
                .tag("num_failed", stats.num_failed)
4476
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4477
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4478
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4479
14
                .tag("bytes_deleted", stats.bytes_deleted)
4480
14
                .tag("ret", ret);
4481
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
4456
14
    DORIS_CLOUD_DEFER {
4457
14
        unregister_recycle_task(task_name);
4458
14
        int64_t cost =
4459
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4460
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4461
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4462
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4463
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4464
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4465
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4466
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4467
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4468
14
                                                             stats.bytes_object_deleted);
4469
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4470
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4471
14
                .tag("instance_id", instance_id_)
4472
14
                .tag("num_scanned", stats.num_scanned)
4473
14
                .tag("num_corrected", stats.num_corrected)
4474
14
                .tag("num_deleted", stats.num_deleted)
4475
14
                .tag("num_failed", stats.num_failed)
4476
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4477
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4478
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4479
14
                .tag("bytes_deleted", stats.bytes_deleted)
4480
14
                .tag("ret", ret);
4481
14
    };
4482
4483
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4484
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4485
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4486
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
4483
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4484
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4485
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4486
4
    };
4487
4488
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
4489
4490
14
    std::string begin = packed_file_key({instance_id_, ""});
4491
14
    std::string end = packed_file_key({instance_id_, "\xff"});
4492
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
4493
0
        ret = -1;
4494
0
    }
4495
4496
14
    return ret;
4497
14
}
4498
4499
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
4500
                                                  RecyclerMetricsContext& metrics_context,
4501
0
                                                  int64_t partition_id, bool is_empty_tablet) {
4502
0
    std::string tablet_key_begin, tablet_key_end;
4503
4504
0
    if (partition_id > 0) {
4505
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
4506
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
4507
0
    } else {
4508
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
4509
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
4510
0
    }
4511
    // for calculate the total num or bytes of recyled objects
4512
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
4513
0
                                                          std::string_view v) -> int {
4514
0
        doris::TabletMetaCloudPB tablet_meta_pb;
4515
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
4516
0
            return 0;
4517
0
        }
4518
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
4519
4520
0
        if (config::enable_recycler_check_lazy_txn_finished &&
4521
0
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
4522
0
            return 0;
4523
0
        }
4524
4525
0
        if (!is_empty_tablet) {
4526
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
4527
0
                return 0;
4528
0
            }
4529
0
            tablet_metrics_context_.total_need_recycle_num++;
4530
0
        }
4531
0
        return 0;
4532
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_
4533
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
4534
0
    metrics_context.report(true);
4535
0
    tablet_metrics_context_.report(true);
4536
0
    segment_metrics_context_.report(true);
4537
0
    return ret;
4538
0
}
4539
4540
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
4541
0
                                                 RecyclerMetricsContext& metrics_context) {
4542
0
    int ret = 0;
4543
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
4544
0
    std::unique_ptr<Transaction> txn;
4545
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4546
0
        LOG_WARNING("failed to recycle tablet ")
4547
0
                .tag("tablet id", tablet_id)
4548
0
                .tag("instance_id", instance_id_)
4549
0
                .tag("reason", "failed to create txn");
4550
0
        ret = -1;
4551
0
    }
4552
0
    GetRowsetResponse resp;
4553
0
    std::string msg;
4554
0
    MetaServiceCode code = MetaServiceCode::OK;
4555
    // get rowsets in tablet
4556
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4557
0
                        tablet_id, code, msg, &resp);
4558
0
    if (code != MetaServiceCode::OK) {
4559
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4560
0
                .tag("tablet id", tablet_id)
4561
0
                .tag("msg", msg)
4562
0
                .tag("code", code)
4563
0
                .tag("instance id", instance_id_);
4564
0
        ret = -1;
4565
0
    }
4566
0
    for (const auto& rs_meta : resp.rowset_meta()) {
4567
        /*
4568
        * For compatibility, we skip the loop for [0-1] here.
4569
        * The purpose of this loop is to delete object files,
4570
        * and since [0-1] only has meta and doesn't have object files,
4571
        * skipping it doesn't affect system correctness.
4572
        *
4573
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
4574
        * would return error -1 directly, causing the recycle operation to fail.
4575
        *
4576
        * [0-1] doesn't have resource id is a bug.
4577
        * In the future, we will fix this problem, after that,
4578
        * we can remove this if statement.
4579
        *
4580
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
4581
        */
4582
4583
0
        if (rs_meta.end_version() == 1) {
4584
            // Assert that [0-1] has no resource_id to make sure
4585
            // this if statement will not be forgetted to remove
4586
            // when the resource id bug is fixed
4587
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4588
0
            continue;
4589
0
        }
4590
0
        if (!rs_meta.has_resource_id()) {
4591
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4592
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4593
0
                    .tag("instance_id", instance_id_)
4594
0
                    .tag("tablet_id", tablet_id);
4595
0
            continue;
4596
0
        }
4597
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4598
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4599
        // possible if the accessor is not initilized correctly
4600
0
        if (it == accessor_map_.end()) [[unlikely]] {
4601
0
            LOG_WARNING(
4602
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4603
0
                    "recycle process")
4604
0
                    .tag("tablet id", tablet_id)
4605
0
                    .tag("instance_id", instance_id_)
4606
0
                    .tag("resource_id", rs_meta.resource_id())
4607
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4608
0
            continue;
4609
0
        }
4610
4611
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
4612
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4613
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4614
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
4615
0
    }
4616
0
    return ret;
4617
0
}
4618
4619
4.26k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
4620
4.26k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
4621
4.26k
            .tag("instance_id", instance_id_)
4622
4.26k
            .tag("tablet_id", tablet_id);
4623
4624
4.26k
    if (should_recycle_versioned_keys()) {
4625
14
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
4626
14
        if (ret != 0) {
4627
0
            return ret;
4628
0
        }
4629
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
4630
        // during the recycle_versioned_tablet process.
4631
        //
4632
        // .. And remove restore job rowsets of this tablet too
4633
14
    }
4634
4635
4.26k
    int ret = 0;
4636
4.26k
    auto start_time = steady_clock::now();
4637
4638
4.26k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4639
4640
    // collect resource ids
4641
260
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4642
260
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4643
260
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4644
260
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4645
260
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
4646
260
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
4647
4648
260
    std::set<std::string> resource_ids;
4649
260
    int64_t recycle_rowsets_number = 0;
4650
260
    int64_t recycle_segments_number = 0;
4651
260
    int64_t recycle_rowsets_data_size = 0;
4652
260
    int64_t recycle_rowsets_index_size = 0;
4653
260
    int64_t recycle_restore_job_rowsets_number = 0;
4654
260
    int64_t recycle_restore_job_segments_number = 0;
4655
260
    int64_t recycle_restore_job_rowsets_data_size = 0;
4656
260
    int64_t recycle_restore_job_rowsets_index_size = 0;
4657
260
    int64_t max_rowset_version = 0;
4658
260
    int64_t min_rowset_creation_time = INT64_MAX;
4659
260
    int64_t max_rowset_creation_time = 0;
4660
260
    int64_t min_rowset_expiration_time = INT64_MAX;
4661
260
    int64_t max_rowset_expiration_time = 0;
4662
4663
260
    DORIS_CLOUD_DEFER {
4664
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4665
260
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4666
260
                .tag("instance_id", instance_id_)
4667
260
                .tag("tablet_id", tablet_id)
4668
260
                .tag("recycle rowsets number", recycle_rowsets_number)
4669
260
                .tag("recycle segments number", recycle_segments_number)
4670
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4671
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4672
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4673
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4674
260
                .tag("all restore job rowsets recycle data size",
4675
260
                     recycle_restore_job_rowsets_data_size)
4676
260
                .tag("all restore job rowsets recycle index size",
4677
260
                     recycle_restore_job_rowsets_index_size)
4678
260
                .tag("max rowset version", max_rowset_version)
4679
260
                .tag("min rowset creation time", min_rowset_creation_time)
4680
260
                .tag("max rowset creation time", max_rowset_creation_time)
4681
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
4682
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
4683
260
                .tag("task type", metrics_context.operation_type)
4684
260
                .tag("ret", ret);
4685
260
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4663
260
    DORIS_CLOUD_DEFER {
4664
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4665
260
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4666
260
                .tag("instance_id", instance_id_)
4667
260
                .tag("tablet_id", tablet_id)
4668
260
                .tag("recycle rowsets number", recycle_rowsets_number)
4669
260
                .tag("recycle segments number", recycle_segments_number)
4670
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4671
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4672
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4673
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4674
260
                .tag("all restore job rowsets recycle data size",
4675
260
                     recycle_restore_job_rowsets_data_size)
4676
260
                .tag("all restore job rowsets recycle index size",
4677
260
                     recycle_restore_job_rowsets_index_size)
4678
260
                .tag("max rowset version", max_rowset_version)
4679
260
                .tag("min rowset creation time", min_rowset_creation_time)
4680
260
                .tag("max rowset creation time", max_rowset_creation_time)
4681
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
4682
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
4683
260
                .tag("task type", metrics_context.operation_type)
4684
260
                .tag("ret", ret);
4685
260
    };
4686
4687
260
    std::unique_ptr<Transaction> txn;
4688
260
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4689
0
        LOG_WARNING("failed to recycle tablet ")
4690
0
                .tag("tablet id", tablet_id)
4691
0
                .tag("instance_id", instance_id_)
4692
0
                .tag("reason", "failed to create txn");
4693
0
        ret = -1;
4694
0
    }
4695
260
    GetRowsetResponse resp;
4696
260
    std::string msg;
4697
260
    MetaServiceCode code = MetaServiceCode::OK;
4698
    // get rowsets in tablet
4699
260
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4700
260
                        tablet_id, code, msg, &resp);
4701
260
    if (code != MetaServiceCode::OK) {
4702
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4703
0
                .tag("tablet id", tablet_id)
4704
0
                .tag("msg", msg)
4705
0
                .tag("code", code)
4706
0
                .tag("instance id", instance_id_);
4707
0
        ret = -1;
4708
0
    }
4709
260
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
4710
4711
2.55k
    for (const auto& rs_meta : resp.rowset_meta()) {
4712
2.55k
        if (!rs_meta.has_resource_id() || rs_meta.resource_id().empty()) {
4713
3
            if (rs_meta.num_segments() <= 0) {
4714
2
                LOG_INFO("rowset meta has no segments and no resource id, skip this rowset")
4715
2
                        .tag("rs_meta", rs_meta.ShortDebugString())
4716
2
                        .tag("instance_id", instance_id_)
4717
2
                        .tag("tablet_id", tablet_id);
4718
2
                recycle_rowsets_number += 1;
4719
2
                continue;
4720
2
            }
4721
1
            LOG_WARNING("rowset meta has a missing or empty resource id, impossible!")
4722
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
4723
1
                    .tag("instance_id", instance_id_)
4724
1
                    .tag("tablet_id", tablet_id);
4725
1
            return -1;
4726
3
        }
4727
2.54k
        DCHECK(rs_meta.has_resource_id() && !rs_meta.resource_id().empty())
4728
2
                << "rs_meta" << rs_meta.ShortDebugString();
4729
2.54k
        auto it = accessor_map_.find(rs_meta.resource_id());
4730
        // possible if the accessor is not initilized correctly
4731
2.54k
        if (it == accessor_map_.end()) [[unlikely]] {
4732
1
            LOG_WARNING(
4733
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4734
1
                    "recycle process")
4735
1
                    .tag("tablet id", tablet_id)
4736
1
                    .tag("instance_id", instance_id_)
4737
1
                    .tag("resource_id", rs_meta.resource_id())
4738
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4739
1
            return -1;
4740
1
        }
4741
2.54k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4742
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
4743
0
                    .tag("instance_id", instance_id_)
4744
0
                    .tag("tablet_id", tablet_id)
4745
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4746
0
            return -1;
4747
0
        }
4748
2.54k
        recycle_rowsets_number += 1;
4749
2.54k
        recycle_segments_number += rs_meta.num_segments();
4750
2.54k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4751
2.54k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4752
2.54k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4753
2.54k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4754
2.54k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4755
2.54k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4756
2.54k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4757
2.54k
        resource_ids.emplace(rs_meta.resource_id());
4758
2.54k
    }
4759
4760
    // get restore job rowset in tablet
4761
258
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
4762
258
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
4763
258
    if (code != MetaServiceCode::OK) {
4764
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
4765
0
                .tag("tablet id", tablet_id)
4766
0
                .tag("msg", msg)
4767
0
                .tag("code", code)
4768
0
                .tag("instance id", instance_id_);
4769
0
        return -1;
4770
0
    }
4771
4772
258
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
4773
0
        if (!rs_meta.has_resource_id()) {
4774
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4775
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4776
0
                    .tag("instance_id", instance_id_)
4777
0
                    .tag("tablet_id", tablet_id);
4778
0
            return -1;
4779
0
        }
4780
4781
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4782
        // possible if the accessor is not initilized correctly
4783
0
        if (it == accessor_map_.end()) [[unlikely]] {
4784
0
            LOG_WARNING(
4785
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4786
0
                    "recycle process")
4787
0
                    .tag("tablet id", tablet_id)
4788
0
                    .tag("instance_id", instance_id_)
4789
0
                    .tag("resource_id", rs_meta.resource_id())
4790
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4791
0
            return -1;
4792
0
        }
4793
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4794
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
4795
0
                    .tag("instance_id", instance_id_)
4796
0
                    .tag("tablet_id", tablet_id)
4797
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4798
0
            return -1;
4799
0
        }
4800
0
        recycle_restore_job_rowsets_number += 1;
4801
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
4802
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
4803
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
4804
0
        resource_ids.emplace(rs_meta.resource_id());
4805
0
    }
4806
4807
258
    LOG_INFO("recycle tablet start to delete object")
4808
258
            .tag("instance id", instance_id_)
4809
258
            .tag("tablet id", tablet_id)
4810
258
            .tag("recycle tablet resource ids are",
4811
258
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
4812
258
                                 [](std::string rs_id, const auto& it) {
4813
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4814
217
                                 }));
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
4812
217
                                 [](std::string rs_id, const auto& it) {
4813
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4814
217
                                 }));
4815
4816
258
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
4817
258
            _thread_pool_group.s3_producer_pool,
4818
258
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4819
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
4819
208
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
4820
4821
    // delete all rowset data in this tablet
4822
    // ATTN: there may be data leak if not all accessor initilized successfully
4823
    //       partial data deleted if the tablet is stored cross-storage vault
4824
    //       vault id is not attached to TabletMeta...
4825
258
    for (const auto& resource_id : resource_ids) {
4826
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
4827
217
        concurrent_delete_executor.add(
4828
217
                [&, rs_id = resource_id,
4829
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4830
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4831
217
                    if (res != 0) {
4832
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4833
3
                                     << " path=" << accessor_ptr->uri()
4834
3
                                     << " task type=" << metrics_context.operation_type;
4835
3
                        return std::make_pair(-1, rs_id);
4836
3
                    }
4837
214
                    return std::make_pair(0, rs_id);
4838
217
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
4829
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4830
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4831
217
                    if (res != 0) {
4832
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4833
3
                                     << " path=" << accessor_ptr->uri()
4834
3
                                     << " task type=" << metrics_context.operation_type;
4835
3
                        return std::make_pair(-1, rs_id);
4836
3
                    }
4837
214
                    return std::make_pair(0, rs_id);
4838
217
                });
4839
217
    }
4840
4841
258
    bool finished = true;
4842
258
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
4843
258
    for (auto& r : rets) {
4844
217
        if (r.first != 0) {
4845
3
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
4846
3
            ret = -1;
4847
3
        }
4848
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
4849
217
    }
4850
258
    ret = finished ? ret : -1;
4851
4852
258
    if (ret != 0) { // failed recycle tablet data
4853
3
        LOG_WARNING("ret!=0")
4854
3
                .tag("finished", finished)
4855
3
                .tag("ret", ret)
4856
3
                .tag("instance_id", instance_id_)
4857
3
                .tag("tablet_id", tablet_id);
4858
3
        return ret;
4859
3
    }
4860
4861
255
    tablet_metrics_context_.total_recycled_data_size +=
4862
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4863
255
    tablet_metrics_context_.total_recycled_num += 1;
4864
255
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
4865
255
    segment_metrics_context_.total_recycled_data_size +=
4866
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4867
255
    metrics_context.total_recycled_data_size +=
4868
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4869
255
    tablet_metrics_context_.report();
4870
255
    segment_metrics_context_.report();
4871
255
    metrics_context.report();
4872
4873
255
    txn.reset();
4874
255
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4875
0
        LOG_WARNING("failed to recycle tablet ")
4876
0
                .tag("tablet id", tablet_id)
4877
0
                .tag("instance_id", instance_id_)
4878
0
                .tag("reason", "failed to create txn");
4879
0
        ret = -1;
4880
0
    }
4881
    // delete all rowset kv in this tablet
4882
255
    txn->remove(rs_key0, rs_key1);
4883
255
    txn->remove(recyc_rs_key0, recyc_rs_key1);
4884
255
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
4885
4886
    // remove delete bitmap for MoW table
4887
255
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
4888
255
    txn->remove(pending_key);
4889
255
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
4890
255
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
4891
255
    txn->remove(delete_bitmap_start, delete_bitmap_end);
4892
4893
255
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
4894
255
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
4895
255
    txn->remove(dbm_start_key, dbm_end_key);
4896
255
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
4897
255
              << " end=" << hex(dbm_end_key);
4898
4899
255
    TxnErrorCode err = txn->commit();
4900
255
    if (err != TxnErrorCode::TXN_OK) {
4901
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
4902
0
        ret = -1;
4903
0
    }
4904
4905
255
    if (ret == 0) {
4906
        // All object files under tablet have been deleted
4907
255
        std::lock_guard lock(recycled_tablets_mtx_);
4908
255
        recycled_tablets_.insert(tablet_id);
4909
255
    }
4910
4911
255
    return ret;
4912
258
}
4913
4914
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
4915
14
                                               RecyclerMetricsContext& metrics_context) {
4916
14
    int ret = 0;
4917
14
    auto start_time = steady_clock::now();
4918
4919
14
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4920
4921
    // collect resource ids
4922
11
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4923
11
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4924
11
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4925
11
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4926
4927
11
    int64_t recycle_rowsets_number = 0;
4928
11
    int64_t recycle_segments_number = 0;
4929
11
    int64_t recycle_rowsets_data_size = 0;
4930
11
    int64_t recycle_rowsets_index_size = 0;
4931
11
    int64_t max_rowset_version = 0;
4932
11
    int64_t min_rowset_creation_time = INT64_MAX;
4933
11
    int64_t max_rowset_creation_time = 0;
4934
11
    int64_t min_rowset_expiration_time = INT64_MAX;
4935
11
    int64_t max_rowset_expiration_time = 0;
4936
4937
11
    DORIS_CLOUD_DEFER {
4938
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4939
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4940
11
                .tag("instance_id", instance_id_)
4941
11
                .tag("tablet_id", tablet_id)
4942
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4943
11
                .tag("recycle segments number", recycle_segments_number)
4944
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4945
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4946
11
                .tag("max rowset version", max_rowset_version)
4947
11
                .tag("min rowset creation time", min_rowset_creation_time)
4948
11
                .tag("max rowset creation time", max_rowset_creation_time)
4949
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4950
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4951
11
                .tag("ret", ret);
4952
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4937
11
    DORIS_CLOUD_DEFER {
4938
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4939
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4940
11
                .tag("instance_id", instance_id_)
4941
11
                .tag("tablet_id", tablet_id)
4942
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4943
11
                .tag("recycle segments number", recycle_segments_number)
4944
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4945
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4946
11
                .tag("max rowset version", max_rowset_version)
4947
11
                .tag("min rowset creation time", min_rowset_creation_time)
4948
11
                .tag("max rowset creation time", max_rowset_creation_time)
4949
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4950
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4951
11
                .tag("ret", ret);
4952
11
    };
4953
4954
11
    std::unique_ptr<Transaction> txn;
4955
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4956
0
        LOG_WARNING("failed to recycle tablet ")
4957
0
                .tag("tablet id", tablet_id)
4958
0
                .tag("instance_id", instance_id_)
4959
0
                .tag("reason", "failed to create txn");
4960
0
        ret = -1;
4961
0
    }
4962
4963
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
4964
    // by the related operation logs.
4965
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
4966
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
4967
11
    MetaReader meta_reader(instance_id_);
4968
11
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
4969
11
    if (err == TxnErrorCode::TXN_OK) {
4970
11
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
4971
11
    }
4972
11
    if (err != TxnErrorCode::TXN_OK) {
4973
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4974
0
                .tag("tablet id", tablet_id)
4975
0
                .tag("err", err)
4976
0
                .tag("instance id", instance_id_);
4977
0
        ret = -1;
4978
0
    }
4979
4980
11
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
4981
11
             load_rowset_metas.size(), compact_rowset_metas.size())
4982
11
            .tag("instance_id", instance_id_)
4983
11
            .tag("tablet_id", tablet_id);
4984
4985
11
    SyncExecutor<int> concurrent_delete_executor(
4986
11
            _thread_pool_group.s3_producer_pool,
4987
11
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4988
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
4989
4990
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
4991
60
        recycle_rowsets_number += 1;
4992
60
        recycle_segments_number += rs_meta.num_segments();
4993
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4994
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4995
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4996
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4997
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4998
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4999
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5000
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
4990
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
4991
60
        recycle_rowsets_number += 1;
4992
60
        recycle_segments_number += rs_meta.num_segments();
4993
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4994
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4995
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4996
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4997
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4998
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4999
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5000
60
    };
5001
5002
11
    std::vector<RowsetDeleteTask> all_tasks;
5003
60
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
5004
60
        update_rowset_stats(rs_meta);
5005
        // Version 0-1 rowset has no resource_id and no actual data files,
5006
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5007
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5008
60
        RowsetDeleteTask task;
5009
60
        task.rowset_meta = rs_meta;
5010
60
        task.versioned_rowset_key =
5011
60
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
5012
60
        task.non_versioned_rowset_key =
5013
60
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5014
60
        task.versionstamp = versionstamp;
5015
60
        all_tasks.push_back(std::move(task));
5016
60
    }
5017
5018
11
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
5019
0
        update_rowset_stats(rs_meta);
5020
        // Version 0-1 rowset has no resource_id and no actual data files,
5021
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5022
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5023
0
        RowsetDeleteTask task;
5024
0
        task.rowset_meta = rs_meta;
5025
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
5026
0
                {instance_id_, tablet_id, rs_meta.end_version()});
5027
0
        task.non_versioned_rowset_key =
5028
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5029
0
        task.versionstamp = versionstamp;
5030
0
        all_tasks.push_back(std::move(task));
5031
0
    }
5032
5033
11
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
5034
0
        RecycleRowsetPB recycle_rowset;
5035
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
5036
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5037
0
            return -1;
5038
0
        }
5039
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
5040
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
5041
                // in old version, keep this key-value pair and it needs to be checked manually
5042
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5043
0
                return -1;
5044
0
            }
5045
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
5046
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5047
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5048
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
5049
0
                return -1;
5050
0
            }
5051
            // decode rowset_id
5052
0
            auto k1 = k;
5053
0
            k1.remove_prefix(1);
5054
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5055
0
            decode_key(&k1, &out);
5056
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5057
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5058
0
            LOG_INFO("delete old-version rowset data")
5059
0
                    .tag("instance_id", instance_id_)
5060
0
                    .tag("tablet_id", tablet_id)
5061
0
                    .tag("rowset_id", rowset_id);
5062
5063
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
5064
            // so we must use prefix deletion directly instead of batch delete.
5065
0
            concurrent_delete_executor.add(
5066
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
5067
                        // delete by prefix, the recycle rowset key will be deleted by range later.
5068
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
5069
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
5070
0
        } else {
5071
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
5072
            // Version 0-1 rowset has no resource_id and no actual data files,
5073
            // but still needs ref_count key cleanup, so we add it to all_tasks.
5074
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
5075
0
            RowsetDeleteTask task;
5076
0
            task.rowset_meta = rowset_meta;
5077
0
            task.recycle_rowset_key = k;
5078
0
            all_tasks.push_back(std::move(task));
5079
0
        }
5080
0
        return 0;
5081
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_
5082
5083
11
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
5084
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
5085
0
                .tag("tablet id", tablet_id)
5086
0
                .tag("instance_id", instance_id_)
5087
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
5088
0
        ret = -1;
5089
0
    }
5090
5091
    // Phase 1: Classify tasks by ref_count
5092
11
    std::vector<RowsetDeleteTask> batch_delete_tasks;
5093
60
    for (auto& task : all_tasks) {
5094
60
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
5095
60
        if (classify_ret < 0) {
5096
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
5097
0
                    .tag("instance_id", instance_id_)
5098
0
                    .tag("tablet_id", tablet_id)
5099
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5100
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
5101
0
                return recycle_rowset_meta_and_data(t);
5102
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_4clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_4clEv
5103
0
        }
5104
60
    }
5105
5106
11
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
5107
5108
11
    LOG_INFO("batch delete plan created")
5109
11
            .tag("instance_id", instance_id_)
5110
11
            .tag("tablet_id", tablet_id)
5111
11
            .tag("plan_count", batch_delete_tasks.size());
5112
5113
    // Phase 2: Execute batch delete using existing delete_rowset_data
5114
11
    if (!batch_delete_tasks.empty()) {
5115
10
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
5116
49
        for (const auto& task : batch_delete_tasks) {
5117
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
5118
49
            if (task.rowset_meta.resource_id().empty()) {
5119
10
                LOG_INFO("skip rowset with empty resource_id in batch delete")
5120
10
                        .tag("instance_id", instance_id_)
5121
10
                        .tag("tablet_id", tablet_id)
5122
10
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5123
10
                continue;
5124
10
            }
5125
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
5126
39
        }
5127
5128
        // Only call delete_rowset_data if there are rowsets with actual data to delete
5129
10
        bool delete_success = true;
5130
10
        if (!rowsets_to_delete.empty()) {
5131
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
5132
9
                                                         "batch_delete_versioned_tablet");
5133
9
            int delete_ret = delete_rowset_data(
5134
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
5135
9
            if (delete_ret != 0) {
5136
0
                LOG_WARNING("batch delete execution failed")
5137
0
                        .tag("instance_id", instance_id_)
5138
0
                        .tag("tablet_id", tablet_id);
5139
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
5140
0
                ret = -1;
5141
0
                delete_success = false;
5142
0
            }
5143
9
        }
5144
5145
        // Phase 3: Only cleanup metadata if data deletion succeeded.
5146
        // If deletion failed, keep recycle_rowset_key so next round will retry.
5147
10
        if (delete_success) {
5148
10
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
5149
10
            if (cleanup_ret != 0) {
5150
0
                LOG_WARNING("batch delete cleanup failed")
5151
0
                        .tag("instance_id", instance_id_)
5152
0
                        .tag("tablet_id", tablet_id);
5153
0
                ret = -1;
5154
0
            }
5155
10
        }
5156
10
    }
5157
5158
    // Always wait for fallback tasks to complete before returning
5159
11
    bool finished = true;
5160
11
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
5161
11
    for (int r : rets) {
5162
0
        if (r != 0) {
5163
0
            ret = -1;
5164
0
        }
5165
0
    }
5166
5167
11
    ret = finished ? ret : -1;
5168
5169
11
    if (ret != 0) { // failed recycle tablet data
5170
0
        LOG_WARNING("recycle versioned tablet failed")
5171
0
                .tag("finished", finished)
5172
0
                .tag("ret", ret)
5173
0
                .tag("instance_id", instance_id_)
5174
0
                .tag("tablet_id", tablet_id);
5175
0
        return ret;
5176
0
    }
5177
5178
11
    tablet_metrics_context_.total_recycled_data_size +=
5179
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5180
11
    tablet_metrics_context_.total_recycled_num += 1;
5181
11
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5182
11
    segment_metrics_context_.total_recycled_data_size +=
5183
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5184
11
    metrics_context.total_recycled_data_size +=
5185
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5186
11
    tablet_metrics_context_.report();
5187
11
    segment_metrics_context_.report();
5188
11
    metrics_context.report();
5189
5190
11
    txn.reset();
5191
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5192
0
        LOG_WARNING("failed to recycle tablet ")
5193
0
                .tag("tablet id", tablet_id)
5194
0
                .tag("instance_id", instance_id_)
5195
0
                .tag("reason", "failed to create txn");
5196
0
        ret = -1;
5197
0
    }
5198
    // delete all rowset kv in this tablet
5199
11
    txn->remove(rs_key0, rs_key1);
5200
11
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5201
5202
    // remove delete bitmap for MoW table
5203
11
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5204
11
    txn->remove(pending_key);
5205
11
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5206
11
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5207
11
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5208
5209
11
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5210
11
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5211
11
    txn->remove(dbm_start_key, dbm_end_key);
5212
11
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5213
11
              << " end=" << hex(dbm_end_key);
5214
5215
11
    std::string versioned_idx_key = versioned::tablet_index_key({instance_id_, tablet_id});
5216
11
    std::string tablet_index_val;
5217
11
    err = txn->get(versioned_idx_key, &tablet_index_val);
5218
11
    if (err != TxnErrorCode::TXN_KEY_NOT_FOUND && err != TxnErrorCode::TXN_OK) {
5219
0
        LOG_WARNING("failed to get tablet index kv")
5220
0
                .tag("instance_id", instance_id_)
5221
0
                .tag("tablet_id", tablet_id)
5222
0
                .tag("err", err);
5223
0
        ret = -1;
5224
11
    } else if (err == TxnErrorCode::TXN_OK) {
5225
        // If the tablet index kv exists, we need to delete it
5226
10
        TabletIndexPB tablet_index_pb;
5227
10
        if (!tablet_index_pb.ParseFromString(tablet_index_val)) {
5228
0
            LOG_WARNING("failed to parse tablet index pb")
5229
0
                    .tag("instance_id", instance_id_)
5230
0
                    .tag("tablet_id", tablet_id);
5231
0
            ret = -1;
5232
10
        } else {
5233
10
            std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
5234
10
                    {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
5235
10
                     tablet_index_pb.index_id(), tablet_index_pb.partition_id(), tablet_id});
5236
10
            txn->remove(versioned_inverted_idx_key);
5237
10
            txn->remove(versioned_idx_key);
5238
10
        }
5239
10
    }
5240
5241
11
    err = txn->commit();
5242
11
    if (err != TxnErrorCode::TXN_OK) {
5243
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5244
0
        ret = -1;
5245
0
    }
5246
5247
11
    if (ret == 0) {
5248
        // All object files under tablet have been deleted
5249
11
        std::lock_guard lock(recycled_tablets_mtx_);
5250
11
        recycled_tablets_.insert(tablet_id);
5251
11
    }
5252
5253
11
    return ret;
5254
11
}
5255
5256
68
int InstanceRecycler::recycle_rowsets() {
5257
68
    if (should_recycle_versioned_keys()) {
5258
5
        return recycle_versioned_rowsets();
5259
5
    }
5260
5261
63
    const std::string task_name = "recycle_rowsets";
5262
63
    int64_t num_scanned = 0;
5263
63
    int64_t num_expired = 0;
5264
63
    int64_t num_prepare = 0;
5265
63
    int64_t num_compacted = 0;
5266
63
    int64_t num_empty_rowset = 0;
5267
63
    size_t total_rowset_key_size = 0;
5268
63
    size_t total_rowset_value_size = 0;
5269
63
    size_t expired_rowset_size = 0;
5270
63
    std::atomic_long num_recycled = 0;
5271
63
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5272
5273
63
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5274
63
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5275
63
    std::string recyc_rs_key0;
5276
63
    std::string recyc_rs_key1;
5277
63
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5278
63
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5279
5280
63
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5281
5282
63
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5283
63
    register_recycle_task(task_name, start_time);
5284
5285
63
    DORIS_CLOUD_DEFER {
5286
63
        unregister_recycle_task(task_name);
5287
63
        int64_t cost =
5288
63
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5289
63
        metrics_context.finish_report();
5290
63
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5291
63
                .tag("instance_id", instance_id_)
5292
63
                .tag("num_scanned", num_scanned)
5293
63
                .tag("num_expired", num_expired)
5294
63
                .tag("num_recycled", num_recycled)
5295
63
                .tag("num_recycled.prepare", num_prepare)
5296
63
                .tag("num_recycled.compacted", num_compacted)
5297
63
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5298
63
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5299
63
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5300
63
                .tag("expired_rowset_meta_size", expired_rowset_size);
5301
63
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5285
7
    DORIS_CLOUD_DEFER {
5286
7
        unregister_recycle_task(task_name);
5287
7
        int64_t cost =
5288
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5289
7
        metrics_context.finish_report();
5290
7
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5291
7
                .tag("instance_id", instance_id_)
5292
7
                .tag("num_scanned", num_scanned)
5293
7
                .tag("num_expired", num_expired)
5294
7
                .tag("num_recycled", num_recycled)
5295
7
                .tag("num_recycled.prepare", num_prepare)
5296
7
                .tag("num_recycled.compacted", num_compacted)
5297
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5298
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5299
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5300
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
5301
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5285
56
    DORIS_CLOUD_DEFER {
5286
56
        unregister_recycle_task(task_name);
5287
56
        int64_t cost =
5288
56
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5289
56
        metrics_context.finish_report();
5290
56
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5291
56
                .tag("instance_id", instance_id_)
5292
56
                .tag("num_scanned", num_scanned)
5293
56
                .tag("num_expired", num_expired)
5294
56
                .tag("num_recycled", num_recycled)
5295
56
                .tag("num_recycled.prepare", num_prepare)
5296
56
                .tag("num_recycled.compacted", num_compacted)
5297
56
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5298
56
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5299
56
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5300
56
                .tag("expired_rowset_meta_size", expired_rowset_size);
5301
56
    };
5302
5303
63
    struct RecycleRowsetEntry {
5304
63
        std::string key;
5305
63
        doris::RowsetMetaCloudPB meta;
5306
63
    };
5307
63
    struct RecycleRowsetDeleteJob {
5308
63
        std::vector<std::string> keys;
5309
63
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
5310
63
    };
5311
    // Store the scanned recycle key with rowset meta. The scanned key is the actual KV key to delete.
5312
63
    std::vector<RecycleRowsetEntry> rowsets;
5313
63
    int64_t current_tablet_id = -1;
5314
63
    int64_t recycled_rowset_count_for_current_tablet = 0;
5315
63
    bool current_tablet_skip_logged = false;
5316
63
    std::string next_scan_begin;
5317
63
    const int64_t rowset_batch_size_per_tablet =
5318
63
            std::max(1, config::recycle_rowsets_per_tablet_batch_size);
5319
63
    const int64_t delete_rowset_batch_size =
5320
63
            std::min(500000, config::recycle_rowsets_delete_batch_size);
5321
4.05k
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5322
4.05k
        if (current_tablet_id != tablet_id) {
5323
27
            current_tablet_id = tablet_id;
5324
27
            recycled_rowset_count_for_current_tablet = 0;
5325
27
            current_tablet_skip_logged = false;
5326
27
        }
5327
4.05k
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5328
7
            if (!current_tablet_skip_logged) {
5329
7
                LOG_INFO(
5330
7
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5331
7
                        .tag("instance_id", instance_id_)
5332
7
                        .tag("tablet_id", tablet_id)
5333
7
                        .tag("limit", rowset_batch_size_per_tablet);
5334
7
                current_tablet_skip_logged = true;
5335
7
            }
5336
7
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5337
7
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5338
7
            return false;
5339
7
        }
5340
4.04k
        ++recycled_rowset_count_for_current_tablet;
5341
4.04k
        return true;
5342
4.05k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_8clEl
Line
Count
Source
5321
7
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5322
7
        if (current_tablet_id != tablet_id) {
5323
7
            current_tablet_id = tablet_id;
5324
7
            recycled_rowset_count_for_current_tablet = 0;
5325
7
            current_tablet_skip_logged = false;
5326
7
        }
5327
7
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5328
0
            if (!current_tablet_skip_logged) {
5329
0
                LOG_INFO(
5330
0
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5331
0
                        .tag("instance_id", instance_id_)
5332
0
                        .tag("tablet_id", tablet_id)
5333
0
                        .tag("limit", rowset_batch_size_per_tablet);
5334
0
                current_tablet_skip_logged = true;
5335
0
            }
5336
0
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5337
0
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5338
0
            return false;
5339
0
        }
5340
7
        ++recycled_rowset_count_for_current_tablet;
5341
7
        return true;
5342
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_8clEl
Line
Count
Source
5321
4.04k
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5322
4.04k
        if (current_tablet_id != tablet_id) {
5323
20
            current_tablet_id = tablet_id;
5324
20
            recycled_rowset_count_for_current_tablet = 0;
5325
20
            current_tablet_skip_logged = false;
5326
20
        }
5327
4.04k
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5328
7
            if (!current_tablet_skip_logged) {
5329
7
                LOG_INFO(
5330
7
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5331
7
                        .tag("instance_id", instance_id_)
5332
7
                        .tag("tablet_id", tablet_id)
5333
7
                        .tag("limit", rowset_batch_size_per_tablet);
5334
7
                current_tablet_skip_logged = true;
5335
7
            }
5336
7
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5337
7
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5338
7
            return false;
5339
7
        }
5340
4.04k
        ++recycled_rowset_count_for_current_tablet;
5341
4.04k
        return true;
5342
4.04k
    };
5343
4.05k
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5344
4.05k
        if (next_scan_begin.empty()) {
5345
4.04k
            return false;
5346
4.04k
        }
5347
7
        *begin = std::move(next_scan_begin);
5348
7
        next_scan_begin.clear();
5349
7
        return true;
5350
4.05k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clEPNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5343
7
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5344
7
        if (next_scan_begin.empty()) {
5345
7
            return false;
5346
7
        }
5347
0
        *begin = std::move(next_scan_begin);
5348
0
        next_scan_begin.clear();
5349
0
        return true;
5350
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clEPNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5343
4.04k
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5344
4.04k
        if (next_scan_begin.empty()) {
5345
4.04k
            return false;
5346
4.04k
        }
5347
7
        *begin = std::move(next_scan_begin);
5348
7
        next_scan_begin.clear();
5349
7
        return true;
5350
4.04k
    };
5351
5352
63
    std::vector<std::string> rowset_keys_to_mark_recycled;
5353
63
    std::vector<std::string> rowset_keys_to_abort;
5354
63
    std::vector<std::string> prepare_rowset_keys_to_delete;
5355
5356
    // Store keys of rowset recycled by background workers
5357
63
    std::mutex async_recycled_rowset_keys_mutex;
5358
63
    std::vector<std::string> async_recycled_rowset_keys;
5359
63
    std::vector<std::string> rowset_keys_without_data;
5360
63
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5361
63
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5362
63
    worker_pool->start();
5363
63
    auto mark_abort_worker_pool = std::make_unique<SimpleThreadPool>(
5364
63
            config::instance_recycler_worker_pool_size, "recycle_rs_mark_abort");
5365
63
    mark_abort_worker_pool->start();
5366
    // TODO bacth delete
5367
4.03k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5368
4.03k
        std::string dbm_start_key =
5369
4.03k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5370
4.03k
        std::string dbm_end_key = dbm_start_key;
5371
4.03k
        encode_int64(INT64_MAX, &dbm_end_key);
5372
4.03k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5373
4.03k
        if (ret != 0) {
5374
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5375
0
                         << instance_id_;
5376
0
        }
5377
4.03k
        return ret;
5378
4.03k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_7clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5367
3
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5368
3
        std::string dbm_start_key =
5369
3
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5370
3
        std::string dbm_end_key = dbm_start_key;
5371
3
        encode_int64(INT64_MAX, &dbm_end_key);
5372
3
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5373
3
        if (ret != 0) {
5374
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5375
0
                         << instance_id_;
5376
0
        }
5377
3
        return ret;
5378
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_7clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5367
4.03k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5368
4.03k
        std::string dbm_start_key =
5369
4.03k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5370
4.03k
        std::string dbm_end_key = dbm_start_key;
5371
4.03k
        encode_int64(INT64_MAX, &dbm_end_key);
5372
4.03k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5373
4.03k
        if (ret != 0) {
5374
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5375
0
                         << instance_id_;
5376
0
        }
5377
4.03k
        return ret;
5378
4.03k
    };
5379
63
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5380
903
                                            int64_t tablet_id, const std::string& rowset_id) {
5381
        // Try to delete rowset data in background thread
5382
903
        int ret = worker_pool->submit_with_timeout(
5383
903
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5384
833
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5385
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5386
0
                        return;
5387
0
                    }
5388
833
                    std::vector<std::string> keys;
5389
833
                    {
5390
833
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5391
833
                        async_recycled_rowset_keys.push_back(std::move(key));
5392
833
                        if (async_recycled_rowset_keys.size() > 100) {
5393
5
                            keys.swap(async_recycled_rowset_keys);
5394
5
                        }
5395
833
                    }
5396
833
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5397
833
                    if (keys.empty()) return;
5398
5
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5399
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5400
0
                                     << instance_id_;
5401
5
                    } else {
5402
5
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5403
5
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5404
5
                                           num_recycled, start_time);
5405
5
                    }
5406
5
                },
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
5383
3
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5384
3
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5385
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5386
0
                        return;
5387
0
                    }
5388
3
                    std::vector<std::string> keys;
5389
3
                    {
5390
3
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5391
3
                        async_recycled_rowset_keys.push_back(std::move(key));
5392
3
                        if (async_recycled_rowset_keys.size() > 100) {
5393
0
                            keys.swap(async_recycled_rowset_keys);
5394
0
                        }
5395
3
                    }
5396
3
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5397
3
                    if (keys.empty()) return;
5398
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5399
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5400
0
                                     << instance_id_;
5401
0
                    } else {
5402
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5403
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5404
0
                                           num_recycled, start_time);
5405
0
                    }
5406
0
                },
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
5383
830
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5384
830
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5385
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5386
0
                        return;
5387
0
                    }
5388
830
                    std::vector<std::string> keys;
5389
830
                    {
5390
830
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5391
830
                        async_recycled_rowset_keys.push_back(std::move(key));
5392
830
                        if (async_recycled_rowset_keys.size() > 100) {
5393
5
                            keys.swap(async_recycled_rowset_keys);
5394
5
                        }
5395
830
                    }
5396
830
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5397
830
                    if (keys.empty()) return;
5398
5
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5399
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5400
0
                                     << instance_id_;
5401
5
                    } else {
5402
5
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5403
5
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5404
5
                                           num_recycled, start_time);
5405
5
                    }
5406
5
                },
5407
903
                0);
5408
903
        if (ret == 0) return 0;
5409
        // Submit task failed, delete rowset data in current thread
5410
70
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5411
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5412
0
            return -1;
5413
0
        }
5414
70
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5415
0
            return -1;
5416
0
        }
5417
70
        rowset_keys_without_data.push_back(std::move(key));
5418
70
        return 0;
5419
70
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
5380
3
                                            int64_t tablet_id, const std::string& rowset_id) {
5381
        // Try to delete rowset data in background thread
5382
3
        int ret = worker_pool->submit_with_timeout(
5383
3
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5384
3
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5385
3
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5386
3
                        return;
5387
3
                    }
5388
3
                    std::vector<std::string> keys;
5389
3
                    {
5390
3
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5391
3
                        async_recycled_rowset_keys.push_back(std::move(key));
5392
3
                        if (async_recycled_rowset_keys.size() > 100) {
5393
3
                            keys.swap(async_recycled_rowset_keys);
5394
3
                        }
5395
3
                    }
5396
3
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5397
3
                    if (keys.empty()) return;
5398
3
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5399
3
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5400
3
                                     << instance_id_;
5401
3
                    } else {
5402
3
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5403
3
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5404
3
                                           num_recycled, start_time);
5405
3
                    }
5406
3
                },
5407
3
                0);
5408
3
        if (ret == 0) return 0;
5409
        // Submit task failed, delete rowset data in current thread
5410
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5411
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5412
0
            return -1;
5413
0
        }
5414
0
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5415
0
            return -1;
5416
0
        }
5417
0
        rowset_keys_without_data.push_back(std::move(key));
5418
0
        return 0;
5419
0
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
5380
900
                                            int64_t tablet_id, const std::string& rowset_id) {
5381
        // Try to delete rowset data in background thread
5382
900
        int ret = worker_pool->submit_with_timeout(
5383
900
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5384
900
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5385
900
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5386
900
                        return;
5387
900
                    }
5388
900
                    std::vector<std::string> keys;
5389
900
                    {
5390
900
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5391
900
                        async_recycled_rowset_keys.push_back(std::move(key));
5392
900
                        if (async_recycled_rowset_keys.size() > 100) {
5393
900
                            keys.swap(async_recycled_rowset_keys);
5394
900
                        }
5395
900
                    }
5396
900
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5397
900
                    if (keys.empty()) return;
5398
900
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5399
900
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5400
900
                                     << instance_id_;
5401
900
                    } else {
5402
900
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5403
900
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5404
900
                                           num_recycled, start_time);
5405
900
                    }
5406
900
                },
5407
900
                0);
5408
900
        if (ret == 0) return 0;
5409
        // Submit task failed, delete rowset data in current thread
5410
70
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5411
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5412
0
            return -1;
5413
0
        }
5414
70
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5415
0
            return -1;
5416
0
        }
5417
70
        rowset_keys_without_data.push_back(std::move(key));
5418
70
        return 0;
5419
70
    };
5420
5421
63
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5422
5423
4.05k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5424
4.05k
        ++num_scanned;
5425
4.05k
        total_rowset_key_size += k.size();
5426
4.05k
        total_rowset_value_size += v.size();
5427
4.05k
        RecycleRowsetPB rowset;
5428
4.05k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5429
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5430
0
            return -1;
5431
0
        }
5432
5433
4.05k
        int64_t current_time = ::time(nullptr);
5434
4.05k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5435
5436
4.05k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5437
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5438
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5439
4.05k
        if (current_time < expiration) { // not expired
5440
0
            return 0;
5441
0
        }
5442
4.05k
        ++num_expired;
5443
4.05k
        expired_rowset_size += v.size();
5444
5445
4.05k
        int64_t tablet_id =
5446
4.05k
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5447
4.05k
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5448
7
            return 0;
5449
7
        }
5450
5451
4.04k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5452
252
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5453
                // in old version, keep this key-value pair and it needs to be checked manually
5454
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5455
0
                return -1;
5456
0
            }
5457
252
            if (rowset.resource_id().empty()) [[unlikely]] {
5458
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5459
2
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5460
2
                          << hex(k) << " value=" << proto_to_json(rowset);
5461
2
                rowset_keys_without_data.emplace_back(k);
5462
2
                return 0;
5463
2
            }
5464
            // decode rowset_id
5465
250
            auto k1 = k;
5466
250
            k1.remove_prefix(1);
5467
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5468
250
            decode_key(&k1, &out);
5469
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5470
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5471
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5472
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5473
250
                      << " task_type=" << metrics_context.operation_type;
5474
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5475
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5476
0
                return -1;
5477
0
            }
5478
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5479
250
            metrics_context.total_recycled_num++;
5480
250
            segment_metrics_context_.total_recycled_data_size +=
5481
250
                    rowset.rowset_meta().total_disk_size();
5482
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5483
250
            return 0;
5484
250
        }
5485
5486
3.79k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5487
3.79k
        if (config::enable_mark_delete_rowset_before_recycle) {
5488
6
            if (need_mark_rowset_as_recycled(rowset)) {
5489
4
                rowset_keys_to_mark_recycled.emplace_back(k);
5490
4
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5491
4
                             "at next turn, instance_id="
5492
4
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5493
4
                          << " version=[" << rowset_meta->start_version() << '-'
5494
4
                          << rowset_meta->end_version() << "]";
5495
4
                return 0;
5496
4
            }
5497
6
        }
5498
5499
3.79k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5500
3.79k
            rowset_meta->end_version() != 1) {
5501
2
            if (make_deferred_abort_task(rowset).has_value()) {
5502
2
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5503
2
                             "instance_id="
5504
2
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5505
2
                          << " version=[" << rowset_meta->start_version() << '-'
5506
2
                          << rowset_meta->end_version() << "]";
5507
2
                rowset_keys_to_abort.emplace_back(k);
5508
2
            }
5509
2
        }
5510
5511
        // TODO(plat1ko): check rowset not referenced
5512
3.79k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5513
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5514
0
                LOG_INFO("recycle rowset that has empty resource id");
5515
0
            } else {
5516
                // other situations, keep this key-value pair and it needs to be checked manually
5517
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5518
0
                return -1;
5519
0
            }
5520
0
        }
5521
3.79k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5522
3.79k
                  << " tablet_id=" << rowset_meta->tablet_id()
5523
3.79k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5524
3.79k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5525
3.79k
                  << "] txn_id=" << rowset_meta->txn_id()
5526
3.79k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5527
3.79k
                  << " rowset_meta_size=" << v.size()
5528
3.79k
                  << " creation_time=" << rowset_meta->creation_time()
5529
3.79k
                  << " task_type=" << metrics_context.operation_type;
5530
3.79k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5531
            // unable to calculate file path, can only be deleted by rowset id prefix
5532
653
            num_prepare += 1;
5533
653
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5534
653
                                             rowset_meta->tablet_id(),
5535
653
                                             rowset_meta->rowset_id_v2()) != 0) {
5536
0
                return -1;
5537
0
            }
5538
3.13k
        } else {
5539
3.13k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5540
3.13k
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
5541
3.13k
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
5542
3.13k
            } else {
5543
3
                ++num_empty_rowset;
5544
3
                rowset_keys_without_data.emplace_back(k);
5545
3
            }
5546
3.13k
        }
5547
3.79k
        return 0;
5548
3.79k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5423
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5424
7
        ++num_scanned;
5425
7
        total_rowset_key_size += k.size();
5426
7
        total_rowset_value_size += v.size();
5427
7
        RecycleRowsetPB rowset;
5428
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5429
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5430
0
            return -1;
5431
0
        }
5432
5433
7
        int64_t current_time = ::time(nullptr);
5434
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5435
5436
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5437
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5438
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5439
7
        if (current_time < expiration) { // not expired
5440
0
            return 0;
5441
0
        }
5442
7
        ++num_expired;
5443
7
        expired_rowset_size += v.size();
5444
5445
7
        int64_t tablet_id =
5446
7
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5447
7
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5448
0
            return 0;
5449
0
        }
5450
5451
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5452
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5453
                // in old version, keep this key-value pair and it needs to be checked manually
5454
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5455
0
                return -1;
5456
0
            }
5457
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5458
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5459
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5460
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5461
0
                rowset_keys_without_data.emplace_back(k);
5462
0
                return 0;
5463
0
            }
5464
            // decode rowset_id
5465
0
            auto k1 = k;
5466
0
            k1.remove_prefix(1);
5467
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5468
0
            decode_key(&k1, &out);
5469
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5470
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5471
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5472
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5473
0
                      << " task_type=" << metrics_context.operation_type;
5474
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5475
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5476
0
                return -1;
5477
0
            }
5478
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5479
0
            metrics_context.total_recycled_num++;
5480
0
            segment_metrics_context_.total_recycled_data_size +=
5481
0
                    rowset.rowset_meta().total_disk_size();
5482
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5483
0
            return 0;
5484
0
        }
5485
5486
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
5487
7
        if (config::enable_mark_delete_rowset_before_recycle) {
5488
6
            if (need_mark_rowset_as_recycled(rowset)) {
5489
4
                rowset_keys_to_mark_recycled.emplace_back(k);
5490
4
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5491
4
                             "at next turn, instance_id="
5492
4
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5493
4
                          << " version=[" << rowset_meta->start_version() << '-'
5494
4
                          << rowset_meta->end_version() << "]";
5495
4
                return 0;
5496
4
            }
5497
6
        }
5498
5499
3
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5500
3
            rowset_meta->end_version() != 1) {
5501
2
            if (make_deferred_abort_task(rowset).has_value()) {
5502
2
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5503
2
                             "instance_id="
5504
2
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5505
2
                          << " version=[" << rowset_meta->start_version() << '-'
5506
2
                          << rowset_meta->end_version() << "]";
5507
2
                rowset_keys_to_abort.emplace_back(k);
5508
2
            }
5509
2
        }
5510
5511
        // TODO(plat1ko): check rowset not referenced
5512
3
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5513
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5514
0
                LOG_INFO("recycle rowset that has empty resource id");
5515
0
            } else {
5516
                // other situations, keep this key-value pair and it needs to be checked manually
5517
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5518
0
                return -1;
5519
0
            }
5520
0
        }
5521
3
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5522
3
                  << " tablet_id=" << rowset_meta->tablet_id()
5523
3
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5524
3
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5525
3
                  << "] txn_id=" << rowset_meta->txn_id()
5526
3
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5527
3
                  << " rowset_meta_size=" << v.size()
5528
3
                  << " creation_time=" << rowset_meta->creation_time()
5529
3
                  << " task_type=" << metrics_context.operation_type;
5530
3
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5531
            // unable to calculate file path, can only be deleted by rowset id prefix
5532
3
            num_prepare += 1;
5533
3
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5534
3
                                             rowset_meta->tablet_id(),
5535
3
                                             rowset_meta->rowset_id_v2()) != 0) {
5536
0
                return -1;
5537
0
            }
5538
3
        } else {
5539
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5540
0
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
5541
0
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
5542
0
            } else {
5543
0
                ++num_empty_rowset;
5544
0
                rowset_keys_without_data.emplace_back(k);
5545
0
            }
5546
0
        }
5547
3
        return 0;
5548
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5423
4.04k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5424
4.04k
        ++num_scanned;
5425
4.04k
        total_rowset_key_size += k.size();
5426
4.04k
        total_rowset_value_size += v.size();
5427
4.04k
        RecycleRowsetPB rowset;
5428
4.04k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5429
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5430
0
            return -1;
5431
0
        }
5432
5433
4.04k
        int64_t current_time = ::time(nullptr);
5434
4.04k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5435
5436
4.04k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5437
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5438
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5439
4.04k
        if (current_time < expiration) { // not expired
5440
0
            return 0;
5441
0
        }
5442
4.04k
        ++num_expired;
5443
4.04k
        expired_rowset_size += v.size();
5444
5445
4.04k
        int64_t tablet_id =
5446
4.04k
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5447
4.04k
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5448
7
            return 0;
5449
7
        }
5450
5451
4.04k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5452
252
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5453
                // in old version, keep this key-value pair and it needs to be checked manually
5454
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5455
0
                return -1;
5456
0
            }
5457
252
            if (rowset.resource_id().empty()) [[unlikely]] {
5458
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5459
2
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5460
2
                          << hex(k) << " value=" << proto_to_json(rowset);
5461
2
                rowset_keys_without_data.emplace_back(k);
5462
2
                return 0;
5463
2
            }
5464
            // decode rowset_id
5465
250
            auto k1 = k;
5466
250
            k1.remove_prefix(1);
5467
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5468
250
            decode_key(&k1, &out);
5469
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5470
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5471
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5472
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5473
250
                      << " task_type=" << metrics_context.operation_type;
5474
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5475
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5476
0
                return -1;
5477
0
            }
5478
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5479
250
            metrics_context.total_recycled_num++;
5480
250
            segment_metrics_context_.total_recycled_data_size +=
5481
250
                    rowset.rowset_meta().total_disk_size();
5482
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5483
250
            return 0;
5484
250
        }
5485
5486
3.78k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5487
3.78k
        if (config::enable_mark_delete_rowset_before_recycle) {
5488
0
            if (need_mark_rowset_as_recycled(rowset)) {
5489
0
                rowset_keys_to_mark_recycled.emplace_back(k);
5490
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5491
0
                             "at next turn, instance_id="
5492
0
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5493
0
                          << " version=[" << rowset_meta->start_version() << '-'
5494
0
                          << rowset_meta->end_version() << "]";
5495
0
                return 0;
5496
0
            }
5497
0
        }
5498
5499
3.78k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5500
3.78k
            rowset_meta->end_version() != 1) {
5501
0
            if (make_deferred_abort_task(rowset).has_value()) {
5502
0
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5503
0
                             "instance_id="
5504
0
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5505
0
                          << " version=[" << rowset_meta->start_version() << '-'
5506
0
                          << rowset_meta->end_version() << "]";
5507
0
                rowset_keys_to_abort.emplace_back(k);
5508
0
            }
5509
0
        }
5510
5511
        // TODO(plat1ko): check rowset not referenced
5512
3.78k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5513
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5514
0
                LOG_INFO("recycle rowset that has empty resource id");
5515
0
            } else {
5516
                // other situations, keep this key-value pair and it needs to be checked manually
5517
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5518
0
                return -1;
5519
0
            }
5520
0
        }
5521
3.78k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5522
3.78k
                  << " tablet_id=" << rowset_meta->tablet_id()
5523
3.78k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5524
3.78k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5525
3.78k
                  << "] txn_id=" << rowset_meta->txn_id()
5526
3.78k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5527
3.78k
                  << " rowset_meta_size=" << v.size()
5528
3.78k
                  << " creation_time=" << rowset_meta->creation_time()
5529
3.78k
                  << " task_type=" << metrics_context.operation_type;
5530
3.78k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5531
            // unable to calculate file path, can only be deleted by rowset id prefix
5532
650
            num_prepare += 1;
5533
650
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5534
650
                                             rowset_meta->tablet_id(),
5535
650
                                             rowset_meta->rowset_id_v2()) != 0) {
5536
0
                return -1;
5537
0
            }
5538
3.13k
        } else {
5539
3.13k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5540
3.13k
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
5541
3.13k
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
5542
3.13k
            } else {
5543
3
                ++num_empty_rowset;
5544
3
                rowset_keys_without_data.emplace_back(k);
5545
3
            }
5546
3.13k
        }
5547
3.78k
        return 0;
5548
3.78k
    };
5549
5550
63
    auto submit_delete_rowset_data_job = [&](std::vector<std::string> rowset_keys,
5551
63
                                             std::map<std::string, RowsetMetaCloudPB> rowsets) {
5552
22
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys),
5553
22
                             rowsets_to_delete = std::move(rowsets)]() {
5554
22
            if (!rowsets_to_delete.empty() &&
5555
22
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5556
17
                                   metrics_context) != 0) {
5557
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5558
0
                return;
5559
0
            }
5560
3.13k
            for (const auto& [_, rs] : rowsets_to_delete) {
5561
3.13k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5562
0
                    return;
5563
0
                }
5564
3.13k
            }
5565
22
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5566
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5567
0
                return;
5568
0
            }
5569
5570
22
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5571
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
5553
22
                             rowsets_to_delete = std::move(rowsets)]() {
5554
22
            if (!rowsets_to_delete.empty() &&
5555
22
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5556
17
                                   metrics_context) != 0) {
5557
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5558
0
                return;
5559
0
            }
5560
3.13k
            for (const auto& [_, rs] : rowsets_to_delete) {
5561
3.13k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5562
0
                    return;
5563
0
                }
5564
3.13k
            }
5565
22
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5566
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5567
0
                return;
5568
0
            }
5569
5570
22
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5571
22
        });
5572
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
5551
22
                                             std::map<std::string, RowsetMetaCloudPB> rowsets) {
5552
22
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys),
5553
22
                             rowsets_to_delete = std::move(rowsets)]() {
5554
22
            if (!rowsets_to_delete.empty() &&
5555
22
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5556
22
                                   metrics_context) != 0) {
5557
22
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5558
22
                return;
5559
22
            }
5560
22
            for (const auto& [_, rs] : rowsets_to_delete) {
5561
22
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5562
22
                    return;
5563
22
                }
5564
22
            }
5565
22
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5566
22
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5567
22
                return;
5568
22
            }
5569
5570
22
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5571
22
        });
5572
22
    };
5573
5574
63
    auto submit_mark_abort_rowset_job = [&](std::vector<std::string> rowset_keys_to_mark,
5575
105
                                            std::vector<std::string> rowset_keys_to_abort) {
5576
105
        if (rowset_keys_to_mark.empty() && rowset_keys_to_abort.empty()) {
5577
99
            return;
5578
99
        }
5579
6
        mark_abort_worker_pool->submit([&, rowset_keys_to_mark = std::move(rowset_keys_to_mark),
5580
6
                                        rowset_keys_to_abort =
5581
6
                                                std::move(rowset_keys_to_abort)]() mutable {
5582
6
            auto start = steady_clock::now();
5583
6
            DORIS_CLOUD_DEFER {
5584
6
                auto cost = duration_cast<milliseconds>(steady_clock::now() - start).count();
5585
6
                LOG(INFO) << "finish mark and abort rowset job, instance_id=" << instance_id_ << ' '
5586
6
                          << "cost_ms=" << cost << ' '
5587
6
                          << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size() << ' '
5588
6
                          << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5589
6
            };
recycler.cpp:_ZZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_ENUlvE_clEvENKUlvE_clEv
Line
Count
Source
5583
6
            DORIS_CLOUD_DEFER {
5584
6
                auto cost = duration_cast<milliseconds>(steady_clock::now() - start).count();
5585
6
                LOG(INFO) << "finish mark and abort rowset job, instance_id=" << instance_id_ << ' '
5586
6
                          << "cost_ms=" << cost << ' '
5587
6
                          << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size() << ' '
5588
6
                          << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5589
6
            };
Unexecuted instantiation: recycler_test.cpp:_ZZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_ENUlvE_clEvENKUlvE_clEv
5590
6
            if (!rowset_keys_to_mark.empty() &&
5591
6
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5592
4
                                                                rowset_keys_to_mark) != 0) {
5593
0
                LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id="
5594
0
                             << instance_id_ << ' '
5595
0
                             << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size();
5596
0
                return;
5597
0
            }
5598
6
            if (!rowset_keys_to_abort.empty() &&
5599
6
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort, true) !=
5600
2
                        0) {
5601
0
                LOG(WARNING) << "failed to batch abort txn or job for related rowset, "
5602
0
                                "instance_id="
5603
0
                             << instance_id_ << ' '
5604
0
                             << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5605
0
                return;
5606
0
            }
5607
6
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_ENUlvE_clEv
Line
Count
Source
5581
6
                                                std::move(rowset_keys_to_abort)]() mutable {
5582
6
            auto start = steady_clock::now();
5583
6
            DORIS_CLOUD_DEFER {
5584
6
                auto cost = duration_cast<milliseconds>(steady_clock::now() - start).count();
5585
6
                LOG(INFO) << "finish mark and abort rowset job, instance_id=" << instance_id_ << ' '
5586
6
                          << "cost_ms=" << cost << ' '
5587
6
                          << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size() << ' '
5588
6
                          << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5589
6
            };
5590
6
            if (!rowset_keys_to_mark.empty() &&
5591
6
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5592
4
                                                                rowset_keys_to_mark) != 0) {
5593
0
                LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id="
5594
0
                             << instance_id_ << ' '
5595
0
                             << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size();
5596
0
                return;
5597
0
            }
5598
6
            if (!rowset_keys_to_abort.empty() &&
5599
6
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort, true) !=
5600
2
                        0) {
5601
0
                LOG(WARNING) << "failed to batch abort txn or job for related rowset, "
5602
0
                                "instance_id="
5603
0
                             << instance_id_ << ' '
5604
0
                             << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5605
0
                return;
5606
0
            }
5607
6
        });
Unexecuted instantiation: recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_ENUlvE_clEv
5608
6
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_
Line
Count
Source
5575
14
                                            std::vector<std::string> rowset_keys_to_abort) {
5576
14
        if (rowset_keys_to_mark.empty() && rowset_keys_to_abort.empty()) {
5577
8
            return;
5578
8
        }
5579
6
        mark_abort_worker_pool->submit([&, rowset_keys_to_mark = std::move(rowset_keys_to_mark),
5580
6
                                        rowset_keys_to_abort =
5581
6
                                                std::move(rowset_keys_to_abort)]() mutable {
5582
6
            auto start = steady_clock::now();
5583
6
            DORIS_CLOUD_DEFER {
5584
6
                auto cost = duration_cast<milliseconds>(steady_clock::now() - start).count();
5585
6
                LOG(INFO) << "finish mark and abort rowset job, instance_id=" << instance_id_ << ' '
5586
6
                          << "cost_ms=" << cost << ' '
5587
6
                          << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size() << ' '
5588
6
                          << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5589
6
            };
5590
6
            if (!rowset_keys_to_mark.empty() &&
5591
6
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5592
6
                                                                rowset_keys_to_mark) != 0) {
5593
6
                LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id="
5594
6
                             << instance_id_ << ' '
5595
6
                             << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size();
5596
6
                return;
5597
6
            }
5598
6
            if (!rowset_keys_to_abort.empty() &&
5599
6
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort, true) !=
5600
6
                        0) {
5601
6
                LOG(WARNING) << "failed to batch abort txn or job for related rowset, "
5602
6
                                "instance_id="
5603
6
                             << instance_id_ << ' '
5604
6
                             << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5605
6
                return;
5606
6
            }
5607
6
        });
5608
6
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESB_
Line
Count
Source
5575
91
                                            std::vector<std::string> rowset_keys_to_abort) {
5576
91
        if (rowset_keys_to_mark.empty() && rowset_keys_to_abort.empty()) {
5577
91
            return;
5578
91
        }
5579
0
        mark_abort_worker_pool->submit([&, rowset_keys_to_mark = std::move(rowset_keys_to_mark),
5580
0
                                        rowset_keys_to_abort =
5581
0
                                                std::move(rowset_keys_to_abort)]() mutable {
5582
0
            auto start = steady_clock::now();
5583
0
            DORIS_CLOUD_DEFER {
5584
0
                auto cost = duration_cast<milliseconds>(steady_clock::now() - start).count();
5585
0
                LOG(INFO) << "finish mark and abort rowset job, instance_id=" << instance_id_ << ' '
5586
0
                          << "cost_ms=" << cost << ' '
5587
0
                          << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size() << ' '
5588
0
                          << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5589
0
            };
5590
0
            if (!rowset_keys_to_mark.empty() &&
5591
0
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5592
0
                                                                rowset_keys_to_mark) != 0) {
5593
0
                LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id="
5594
0
                             << instance_id_ << ' '
5595
0
                             << "rowset_keys_to_mark.size()=" << rowset_keys_to_mark.size();
5596
0
                return;
5597
0
            }
5598
0
            if (!rowset_keys_to_abort.empty() &&
5599
0
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort, true) !=
5600
0
                        0) {
5601
0
                LOG(WARNING) << "failed to batch abort txn or job for related rowset, "
5602
0
                                "instance_id="
5603
0
                             << instance_id_ << ' '
5604
0
                             << "rowset_keys_to_abort.size()=" << rowset_keys_to_abort.size();
5605
0
                return;
5606
0
            }
5607
0
        });
5608
0
    };
5609
5610
63
    bool scan_finished = false;
5611
105
    auto loop_done = [&]() -> int {
5612
105
        std::vector<std::string> mark_keys_to_process;
5613
105
        std::vector<std::string> abort_keys_to_process;
5614
105
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5615
105
        abort_keys_to_process.swap(rowset_keys_to_abort);
5616
105
        submit_mark_abort_rowset_job(std::move(mark_keys_to_process),
5617
105
                                     std::move(abort_keys_to_process));
5618
105
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
5619
42
            return 0;
5620
42
        }
5621
5622
63
        DORIS_CLOUD_DEFER {
5623
            // if return -1 in loop done, rowset info in memory is not cleared,
5624
            // it can lead to memory accumulation
5625
63
            rowset_keys_without_data.clear();
5626
63
            rowsets.clear();
5627
63
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
5622
7
        DORIS_CLOUD_DEFER {
5623
            // if return -1 in loop done, rowset info in memory is not cleared,
5624
            // it can lead to memory accumulation
5625
7
            rowset_keys_without_data.clear();
5626
7
            rowsets.clear();
5627
7
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
5622
56
        DORIS_CLOUD_DEFER {
5623
            // if return -1 in loop done, rowset info in memory is not cleared,
5624
            // it can lead to memory accumulation
5625
56
            rowset_keys_without_data.clear();
5626
56
            rowsets.clear();
5627
56
        };
5628
63
        std::random_device rd;
5629
63
        std::mt19937 g(rd());
5630
63
        std::ranges::shuffle(rowsets, g);
5631
5632
63
        std::vector<std::string> rowset_keys_to_delete;
5633
63
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
5634
        // rowset_id -> rowset_meta
5635
        // store rowset id and meta for statistics rs size when delete
5636
63
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5637
5638
63
        size_t rowsets_per_batch_size = 0;
5639
3.13k
        for (auto& rowset : rowsets) {
5640
3.13k
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
5641
3.13k
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
5642
3.13k
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
5643
3.12k
                continue;
5644
3.12k
            }
5645
5646
8
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5647
8
                                          std::move(rowsets_to_delete));
5648
8
            rowsets_per_batch_size = 0;
5649
8
            rowset_keys_to_delete.clear();
5650
8
            rowsets_to_delete.clear();
5651
8
        }
5652
5653
63
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
5654
9
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5655
9
                                          std::move(rowsets_to_delete));
5656
9
        }
5657
5658
68
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
5659
5
            auto begin = rowset_keys_without_data.begin() + i;
5660
5
            auto end = rowset_keys_without_data.begin() +
5661
5
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
5662
5
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
5663
5
                                                           std::make_move_iterator(end));
5664
5
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
5665
5
        }
5666
5667
63
        return 0;
5668
105
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5611
14
    auto loop_done = [&]() -> int {
5612
14
        std::vector<std::string> mark_keys_to_process;
5613
14
        std::vector<std::string> abort_keys_to_process;
5614
14
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5615
14
        abort_keys_to_process.swap(rowset_keys_to_abort);
5616
14
        submit_mark_abort_rowset_job(std::move(mark_keys_to_process),
5617
14
                                     std::move(abort_keys_to_process));
5618
14
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
5619
7
            return 0;
5620
7
        }
5621
5622
7
        DORIS_CLOUD_DEFER {
5623
            // if return -1 in loop done, rowset info in memory is not cleared,
5624
            // it can lead to memory accumulation
5625
7
            rowset_keys_without_data.clear();
5626
7
            rowsets.clear();
5627
7
        };
5628
7
        std::random_device rd;
5629
7
        std::mt19937 g(rd());
5630
7
        std::ranges::shuffle(rowsets, g);
5631
5632
7
        std::vector<std::string> rowset_keys_to_delete;
5633
7
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
5634
        // rowset_id -> rowset_meta
5635
        // store rowset id and meta for statistics rs size when delete
5636
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5637
5638
7
        size_t rowsets_per_batch_size = 0;
5639
7
        for (auto& rowset : rowsets) {
5640
0
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
5641
0
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
5642
0
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
5643
0
                continue;
5644
0
            }
5645
5646
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5647
0
                                          std::move(rowsets_to_delete));
5648
0
            rowsets_per_batch_size = 0;
5649
0
            rowset_keys_to_delete.clear();
5650
0
            rowsets_to_delete.clear();
5651
0
        }
5652
5653
7
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
5654
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5655
0
                                          std::move(rowsets_to_delete));
5656
0
        }
5657
5658
7
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
5659
0
            auto begin = rowset_keys_without_data.begin() + i;
5660
0
            auto end = rowset_keys_without_data.begin() +
5661
0
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
5662
0
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
5663
0
                                                           std::make_move_iterator(end));
5664
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
5665
0
        }
5666
5667
7
        return 0;
5668
14
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5611
91
    auto loop_done = [&]() -> int {
5612
91
        std::vector<std::string> mark_keys_to_process;
5613
91
        std::vector<std::string> abort_keys_to_process;
5614
91
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5615
91
        abort_keys_to_process.swap(rowset_keys_to_abort);
5616
91
        submit_mark_abort_rowset_job(std::move(mark_keys_to_process),
5617
91
                                     std::move(abort_keys_to_process));
5618
91
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
5619
35
            return 0;
5620
35
        }
5621
5622
56
        DORIS_CLOUD_DEFER {
5623
            // if return -1 in loop done, rowset info in memory is not cleared,
5624
            // it can lead to memory accumulation
5625
56
            rowset_keys_without_data.clear();
5626
56
            rowsets.clear();
5627
56
        };
5628
56
        std::random_device rd;
5629
56
        std::mt19937 g(rd());
5630
56
        std::ranges::shuffle(rowsets, g);
5631
5632
56
        std::vector<std::string> rowset_keys_to_delete;
5633
56
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
5634
        // rowset_id -> rowset_meta
5635
        // store rowset id and meta for statistics rs size when delete
5636
56
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5637
5638
56
        size_t rowsets_per_batch_size = 0;
5639
3.13k
        for (auto& rowset : rowsets) {
5640
3.13k
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
5641
3.13k
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
5642
3.13k
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
5643
3.12k
                continue;
5644
3.12k
            }
5645
5646
8
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5647
8
                                          std::move(rowsets_to_delete));
5648
8
            rowsets_per_batch_size = 0;
5649
8
            rowset_keys_to_delete.clear();
5650
8
            rowsets_to_delete.clear();
5651
8
        }
5652
5653
56
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
5654
9
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
5655
9
                                          std::move(rowsets_to_delete));
5656
9
        }
5657
5658
61
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
5659
5
            auto begin = rowset_keys_without_data.begin() + i;
5660
5
            auto end = rowset_keys_without_data.begin() +
5661
5
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
5662
5
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
5663
5
                                                           std::make_move_iterator(end));
5664
5
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
5665
5
        }
5666
5667
56
        return 0;
5668
91
    };
5669
5670
63
    if (config::enable_recycler_stats_metrics) {
5671
0
        scan_and_statistics_rowsets();
5672
0
    }
5673
    // recycle_func and loop_done for scan and recycle
5674
63
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv), loop_done,
5675
63
                               std::move(next_scan_begin_getter));
5676
63
    scan_finished = true;
5677
    // if the size of rowsets is always less than delete_rowset_batch_size
5678
    // it need to submit the task directly
5679
    // else if the size of rowsets is greater than delete_rowset_batch_size,
5680
    // but there are residual, whether due to failed or unsuccessful cleanup, this behavior is idempotent
5681
63
    if (loop_done() != 0) {
5682
0
        ret = -1;
5683
0
    }
5684
5685
63
    mark_abort_worker_pool->stop();
5686
63
    worker_pool->stop();
5687
5688
63
    if (!async_recycled_rowset_keys.empty()) {
5689
7
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5690
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5691
0
            return -1;
5692
7
        } else {
5693
7
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5694
7
        }
5695
7
    }
5696
5697
    // Report final metrics after all concurrent tasks completed
5698
63
    segment_metrics_context_.report();
5699
63
    metrics_context.report();
5700
5701
63
    return ret;
5702
63
}
5703
5704
int InstanceRecycler::next_recycle_rowset_tablet_key(const std::string& instance_id,
5705
1
                                                     int64_t tablet_id, std::string* next_key) {
5706
1
    DCHECK(next_key != nullptr);
5707
1
    if (tablet_id == std::numeric_limits<int64_t>::max()) {
5708
0
        return -1;
5709
0
    }
5710
1
    *next_key = recycle_rowset_key({instance_id, tablet_id + 1, ""});
5711
1
    return 0;
5712
1
}
5713
5714
13
int InstanceRecycler::recycle_restore_jobs() {
5715
13
    const std::string task_name = "recycle_restore_jobs";
5716
13
    int64_t num_scanned = 0;
5717
13
    int64_t num_expired = 0;
5718
13
    int64_t num_recycled = 0;
5719
13
    int64_t num_aborted = 0;
5720
5721
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5722
5723
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
5724
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
5725
13
    std::string restore_job_key0;
5726
13
    std::string restore_job_key1;
5727
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
5728
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
5729
5730
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
5731
5732
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5733
13
    register_recycle_task(task_name, start_time);
5734
5735
13
    DORIS_CLOUD_DEFER {
5736
13
        unregister_recycle_task(task_name);
5737
13
        int64_t cost =
5738
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5739
13
        metrics_context.finish_report();
5740
5741
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5742
13
                .tag("instance_id", instance_id_)
5743
13
                .tag("num_scanned", num_scanned)
5744
13
                .tag("num_expired", num_expired)
5745
13
                .tag("num_recycled", num_recycled)
5746
13
                .tag("num_aborted", num_aborted);
5747
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
5735
13
    DORIS_CLOUD_DEFER {
5736
13
        unregister_recycle_task(task_name);
5737
13
        int64_t cost =
5738
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5739
13
        metrics_context.finish_report();
5740
5741
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5742
13
                .tag("instance_id", instance_id_)
5743
13
                .tag("num_scanned", num_scanned)
5744
13
                .tag("num_expired", num_expired)
5745
13
                .tag("num_recycled", num_recycled)
5746
13
                .tag("num_aborted", num_aborted);
5747
13
    };
5748
5749
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5750
5751
13
    std::vector<std::string_view> restore_job_keys;
5752
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5753
41
        ++num_scanned;
5754
41
        RestoreJobCloudPB restore_job_pb;
5755
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5756
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5757
0
            return -1;
5758
0
        }
5759
41
        int64_t expiration =
5760
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5761
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5762
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5763
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5764
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5765
0
                   << " state=" << restore_job_pb.state();
5766
41
        int64_t current_time = ::time(nullptr);
5767
41
        if (current_time < expiration) { // not expired
5768
0
            return 0;
5769
0
        }
5770
41
        ++num_expired;
5771
5772
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5773
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5774
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5775
5776
41
        std::unique_ptr<Transaction> txn;
5777
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5778
41
        if (err != TxnErrorCode::TXN_OK) {
5779
0
            LOG_WARNING("failed to recycle restore job")
5780
0
                    .tag("err", err)
5781
0
                    .tag("tablet id", tablet_id)
5782
0
                    .tag("instance_id", instance_id_)
5783
0
                    .tag("reason", "failed to create txn");
5784
0
            return -1;
5785
0
        }
5786
5787
41
        std::string val;
5788
41
        err = txn->get(k, &val);
5789
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5790
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5791
0
            return 0;
5792
0
        }
5793
41
        if (err != TxnErrorCode::TXN_OK) {
5794
0
            LOG_WARNING("failed to get kv");
5795
0
            return -1;
5796
0
        }
5797
41
        restore_job_pb.Clear();
5798
41
        if (!restore_job_pb.ParseFromString(val)) {
5799
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5800
0
            return -1;
5801
0
        }
5802
5803
        // PREPARED or COMMITTED, change state to DROPPED and return
5804
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5805
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5806
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5807
0
            restore_job_pb.set_need_recycle_data(true);
5808
0
            txn->put(k, restore_job_pb.SerializeAsString());
5809
0
            err = txn->commit();
5810
0
            if (err != TxnErrorCode::TXN_OK) {
5811
0
                LOG_WARNING("failed to commit txn: {}", err);
5812
0
                return -1;
5813
0
            }
5814
0
            num_aborted++;
5815
0
            return 0;
5816
0
        }
5817
5818
        // Change state to RECYCLING
5819
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5820
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5821
21
            txn->put(k, restore_job_pb.SerializeAsString());
5822
21
            err = txn->commit();
5823
21
            if (err != TxnErrorCode::TXN_OK) {
5824
0
                LOG_WARNING("failed to commit txn: {}", err);
5825
0
                return -1;
5826
0
            }
5827
21
            return 0;
5828
21
        }
5829
5830
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5831
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5832
5833
        // Recycle all data associated with the restore job.
5834
        // This includes rowsets, segments, and related resources.
5835
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5836
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5837
0
            LOG_WARNING("failed to recycle tablet")
5838
0
                    .tag("tablet_id", tablet_id)
5839
0
                    .tag("instance_id", instance_id_);
5840
0
            return -1;
5841
0
        }
5842
5843
        // delete all restore job rowset kv
5844
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5845
5846
20
        err = txn->commit();
5847
20
        if (err != TxnErrorCode::TXN_OK) {
5848
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5849
0
                    .tag("err", err)
5850
0
                    .tag("tablet id", tablet_id)
5851
0
                    .tag("instance_id", instance_id_)
5852
0
                    .tag("reason", "failed to commit txn");
5853
0
            return -1;
5854
0
        }
5855
5856
20
        metrics_context.total_recycled_num = ++num_recycled;
5857
20
        metrics_context.report();
5858
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5859
20
        restore_job_keys.push_back(k);
5860
5861
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5862
20
                  << " tablet_id=" << tablet_id;
5863
20
        return 0;
5864
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
5752
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5753
41
        ++num_scanned;
5754
41
        RestoreJobCloudPB restore_job_pb;
5755
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5756
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5757
0
            return -1;
5758
0
        }
5759
41
        int64_t expiration =
5760
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5761
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5762
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5763
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5764
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5765
0
                   << " state=" << restore_job_pb.state();
5766
41
        int64_t current_time = ::time(nullptr);
5767
41
        if (current_time < expiration) { // not expired
5768
0
            return 0;
5769
0
        }
5770
41
        ++num_expired;
5771
5772
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5773
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5774
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5775
5776
41
        std::unique_ptr<Transaction> txn;
5777
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5778
41
        if (err != TxnErrorCode::TXN_OK) {
5779
0
            LOG_WARNING("failed to recycle restore job")
5780
0
                    .tag("err", err)
5781
0
                    .tag("tablet id", tablet_id)
5782
0
                    .tag("instance_id", instance_id_)
5783
0
                    .tag("reason", "failed to create txn");
5784
0
            return -1;
5785
0
        }
5786
5787
41
        std::string val;
5788
41
        err = txn->get(k, &val);
5789
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5790
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5791
0
            return 0;
5792
0
        }
5793
41
        if (err != TxnErrorCode::TXN_OK) {
5794
0
            LOG_WARNING("failed to get kv");
5795
0
            return -1;
5796
0
        }
5797
41
        restore_job_pb.Clear();
5798
41
        if (!restore_job_pb.ParseFromString(val)) {
5799
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5800
0
            return -1;
5801
0
        }
5802
5803
        // PREPARED or COMMITTED, change state to DROPPED and return
5804
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5805
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5806
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5807
0
            restore_job_pb.set_need_recycle_data(true);
5808
0
            txn->put(k, restore_job_pb.SerializeAsString());
5809
0
            err = txn->commit();
5810
0
            if (err != TxnErrorCode::TXN_OK) {
5811
0
                LOG_WARNING("failed to commit txn: {}", err);
5812
0
                return -1;
5813
0
            }
5814
0
            num_aborted++;
5815
0
            return 0;
5816
0
        }
5817
5818
        // Change state to RECYCLING
5819
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5820
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5821
21
            txn->put(k, restore_job_pb.SerializeAsString());
5822
21
            err = txn->commit();
5823
21
            if (err != TxnErrorCode::TXN_OK) {
5824
0
                LOG_WARNING("failed to commit txn: {}", err);
5825
0
                return -1;
5826
0
            }
5827
21
            return 0;
5828
21
        }
5829
5830
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5831
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5832
5833
        // Recycle all data associated with the restore job.
5834
        // This includes rowsets, segments, and related resources.
5835
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5836
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5837
0
            LOG_WARNING("failed to recycle tablet")
5838
0
                    .tag("tablet_id", tablet_id)
5839
0
                    .tag("instance_id", instance_id_);
5840
0
            return -1;
5841
0
        }
5842
5843
        // delete all restore job rowset kv
5844
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5845
5846
20
        err = txn->commit();
5847
20
        if (err != TxnErrorCode::TXN_OK) {
5848
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5849
0
                    .tag("err", err)
5850
0
                    .tag("tablet id", tablet_id)
5851
0
                    .tag("instance_id", instance_id_)
5852
0
                    .tag("reason", "failed to commit txn");
5853
0
            return -1;
5854
0
        }
5855
5856
20
        metrics_context.total_recycled_num = ++num_recycled;
5857
20
        metrics_context.report();
5858
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5859
20
        restore_job_keys.push_back(k);
5860
5861
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5862
20
                  << " tablet_id=" << tablet_id;
5863
20
        return 0;
5864
20
    };
5865
5866
13
    auto loop_done = [&restore_job_keys, this]() -> int {
5867
3
        if (restore_job_keys.empty()) return 0;
5868
1
        DORIS_CLOUD_DEFER {
5869
1
            restore_job_keys.clear();
5870
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5868
1
        DORIS_CLOUD_DEFER {
5869
1
            restore_job_keys.clear();
5870
1
        };
5871
5872
1
        std::unique_ptr<Transaction> txn;
5873
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5874
1
        if (err != TxnErrorCode::TXN_OK) {
5875
0
            LOG_WARNING("failed to recycle restore job")
5876
0
                    .tag("err", err)
5877
0
                    .tag("instance_id", instance_id_)
5878
0
                    .tag("reason", "failed to create txn");
5879
0
            return -1;
5880
0
        }
5881
20
        for (auto& k : restore_job_keys) {
5882
20
            txn->remove(k);
5883
20
        }
5884
1
        err = txn->commit();
5885
1
        if (err != TxnErrorCode::TXN_OK) {
5886
0
            LOG_WARNING("failed to recycle restore job")
5887
0
                    .tag("err", err)
5888
0
                    .tag("instance_id", instance_id_)
5889
0
                    .tag("reason", "failed to commit txn");
5890
0
            return -1;
5891
0
        }
5892
1
        return 0;
5893
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
5866
3
    auto loop_done = [&restore_job_keys, this]() -> int {
5867
3
        if (restore_job_keys.empty()) return 0;
5868
1
        DORIS_CLOUD_DEFER {
5869
1
            restore_job_keys.clear();
5870
1
        };
5871
5872
1
        std::unique_ptr<Transaction> txn;
5873
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5874
1
        if (err != TxnErrorCode::TXN_OK) {
5875
0
            LOG_WARNING("failed to recycle restore job")
5876
0
                    .tag("err", err)
5877
0
                    .tag("instance_id", instance_id_)
5878
0
                    .tag("reason", "failed to create txn");
5879
0
            return -1;
5880
0
        }
5881
20
        for (auto& k : restore_job_keys) {
5882
20
            txn->remove(k);
5883
20
        }
5884
1
        err = txn->commit();
5885
1
        if (err != TxnErrorCode::TXN_OK) {
5886
0
            LOG_WARNING("failed to recycle restore job")
5887
0
                    .tag("err", err)
5888
0
                    .tag("instance_id", instance_id_)
5889
0
                    .tag("reason", "failed to commit txn");
5890
0
            return -1;
5891
0
        }
5892
1
        return 0;
5893
1
    };
5894
5895
13
    if (config::enable_recycler_stats_metrics) {
5896
0
        scan_and_statistics_restore_jobs();
5897
0
    }
5898
5899
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
5900
13
                            std::move(loop_done));
5901
13
}
5902
5903
11
int InstanceRecycler::recycle_versioned_rowsets() {
5904
11
    const std::string task_name = "recycle_rowsets";
5905
11
    int64_t num_scanned = 0;
5906
11
    int64_t num_expired = 0;
5907
11
    int64_t num_prepare = 0;
5908
11
    int64_t num_compacted = 0;
5909
11
    int64_t num_empty_rowset = 0;
5910
11
    size_t total_rowset_key_size = 0;
5911
11
    size_t total_rowset_value_size = 0;
5912
11
    size_t expired_rowset_size = 0;
5913
11
    std::atomic_long num_recycled = 0;
5914
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5915
5916
11
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5917
11
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5918
11
    std::string recyc_rs_key0;
5919
11
    std::string recyc_rs_key1;
5920
11
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5921
11
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5922
5923
11
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5924
5925
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5926
11
    register_recycle_task(task_name, start_time);
5927
5928
11
    DORIS_CLOUD_DEFER {
5929
11
        unregister_recycle_task(task_name);
5930
11
        int64_t cost =
5931
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5932
11
        metrics_context.finish_report();
5933
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5934
11
                .tag("instance_id", instance_id_)
5935
11
                .tag("num_scanned", num_scanned)
5936
11
                .tag("num_expired", num_expired)
5937
11
                .tag("num_recycled", num_recycled)
5938
11
                .tag("num_recycled.prepare", num_prepare)
5939
11
                .tag("num_recycled.compacted", num_compacted)
5940
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5941
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5942
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5943
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
5944
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
5928
11
    DORIS_CLOUD_DEFER {
5929
11
        unregister_recycle_task(task_name);
5930
11
        int64_t cost =
5931
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5932
11
        metrics_context.finish_report();
5933
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5934
11
                .tag("instance_id", instance_id_)
5935
11
                .tag("num_scanned", num_scanned)
5936
11
                .tag("num_expired", num_expired)
5937
11
                .tag("num_recycled", num_recycled)
5938
11
                .tag("num_recycled.prepare", num_prepare)
5939
11
                .tag("num_recycled.compacted", num_compacted)
5940
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5941
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5942
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5943
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
5944
11
    };
5945
5946
11
    std::vector<std::string> orphan_rowset_keys;
5947
5948
    // Store keys of rowset recycled by background workers
5949
11
    std::mutex async_recycled_rowset_keys_mutex;
5950
11
    std::vector<std::string> async_recycled_rowset_keys;
5951
11
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5952
11
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5953
11
    worker_pool->start();
5954
11
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5955
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5956
        // Try to delete rowset data in background thread
5957
400
        int ret = worker_pool->submit_with_timeout(
5958
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5959
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5960
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5961
400
                        return;
5962
400
                    }
5963
                    // The async recycled rowsets are staled format or has not been used,
5964
                    // so we don't need to check the rowset ref count key.
5965
0
                    std::vector<std::string> keys;
5966
0
                    {
5967
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5968
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5969
0
                        if (async_recycled_rowset_keys.size() > 100) {
5970
0
                            keys.swap(async_recycled_rowset_keys);
5971
0
                        }
5972
0
                    }
5973
0
                    if (keys.empty()) return;
5974
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5975
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5976
0
                                     << instance_id_;
5977
0
                    } else {
5978
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5979
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5980
0
                                           num_recycled, start_time);
5981
0
                    }
5982
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
5958
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5959
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5960
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5961
400
                        return;
5962
400
                    }
5963
                    // The async recycled rowsets are staled format or has not been used,
5964
                    // so we don't need to check the rowset ref count key.
5965
0
                    std::vector<std::string> keys;
5966
0
                    {
5967
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5968
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5969
0
                        if (async_recycled_rowset_keys.size() > 100) {
5970
0
                            keys.swap(async_recycled_rowset_keys);
5971
0
                        }
5972
0
                    }
5973
0
                    if (keys.empty()) return;
5974
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5975
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5976
0
                                     << instance_id_;
5977
0
                    } else {
5978
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5979
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5980
0
                                           num_recycled, start_time);
5981
0
                    }
5982
0
                },
5983
400
                0);
5984
400
        if (ret == 0) return 0;
5985
        // Submit task failed, delete rowset data in current thread
5986
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5987
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5988
0
            return -1;
5989
0
        }
5990
0
        orphan_rowset_keys.push_back(std::move(key));
5991
0
        return 0;
5992
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
5955
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5956
        // Try to delete rowset data in background thread
5957
400
        int ret = worker_pool->submit_with_timeout(
5958
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5959
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5960
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5961
400
                        return;
5962
400
                    }
5963
                    // The async recycled rowsets are staled format or has not been used,
5964
                    // so we don't need to check the rowset ref count key.
5965
400
                    std::vector<std::string> keys;
5966
400
                    {
5967
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5968
400
                        async_recycled_rowset_keys.push_back(std::move(key));
5969
400
                        if (async_recycled_rowset_keys.size() > 100) {
5970
400
                            keys.swap(async_recycled_rowset_keys);
5971
400
                        }
5972
400
                    }
5973
400
                    if (keys.empty()) return;
5974
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5975
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5976
400
                                     << instance_id_;
5977
400
                    } else {
5978
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5979
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5980
400
                                           num_recycled, start_time);
5981
400
                    }
5982
400
                },
5983
400
                0);
5984
400
        if (ret == 0) return 0;
5985
        // Submit task failed, delete rowset data in current thread
5986
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5987
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5988
0
            return -1;
5989
0
        }
5990
0
        orphan_rowset_keys.push_back(std::move(key));
5991
0
        return 0;
5992
0
    };
5993
5994
11
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5995
5996
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
5997
2.01k
        ++num_scanned;
5998
2.01k
        total_rowset_key_size += k.size();
5999
2.01k
        total_rowset_value_size += v.size();
6000
2.01k
        RecycleRowsetPB rowset;
6001
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6002
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6003
0
            return -1;
6004
0
        }
6005
6006
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6007
6008
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6009
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6010
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6011
2.01k
        int64_t current_time = ::time(nullptr);
6012
2.01k
        if (current_time < final_expiration) { // not expired
6013
0
            return 0;
6014
0
        }
6015
2.01k
        ++num_expired;
6016
2.01k
        expired_rowset_size += v.size();
6017
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6018
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6019
                // in old version, keep this key-value pair and it needs to be checked manually
6020
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6021
0
                return -1;
6022
0
            }
6023
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6024
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6025
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6026
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6027
0
                orphan_rowset_keys.emplace_back(k);
6028
0
                return -1;
6029
0
            }
6030
            // decode rowset_id
6031
0
            auto k1 = k;
6032
0
            k1.remove_prefix(1);
6033
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6034
0
            decode_key(&k1, &out);
6035
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6036
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6037
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6038
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6039
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6040
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6041
0
                return -1;
6042
0
            }
6043
0
            return 0;
6044
0
        }
6045
        // TODO(plat1ko): check rowset not referenced
6046
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6047
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6048
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6049
0
                LOG_INFO("recycle rowset that has empty resource id");
6050
0
            } else {
6051
                // other situations, keep this key-value pair and it needs to be checked manually
6052
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6053
0
                return -1;
6054
0
            }
6055
0
        }
6056
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6057
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6058
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6059
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6060
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6061
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6062
2.01k
                  << " rowset_meta_size=" << v.size()
6063
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6064
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6065
            // unable to calculate file path, can only be deleted by rowset id prefix
6066
400
            num_prepare += 1;
6067
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6068
400
                                             rowset_meta->tablet_id(),
6069
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6070
0
                return -1;
6071
0
            }
6072
1.61k
        } else {
6073
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6074
1.61k
            worker_pool->submit(
6075
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6076
                        // The load & compact rowset keys are recycled during recycling operation logs.
6077
1.61k
                        RowsetDeleteTask task;
6078
1.61k
                        task.rowset_meta = rowset_meta;
6079
1.61k
                        task.recycle_rowset_key = k;
6080
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6081
1.60k
                            return;
6082
1.60k
                        }
6083
13
                        num_compacted += is_compacted;
6084
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6085
13
                        if (rowset_meta.num_segments() == 0) {
6086
0
                            ++num_empty_rowset;
6087
0
                        }
6088
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
6075
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6076
                        // The load & compact rowset keys are recycled during recycling operation logs.
6077
1.61k
                        RowsetDeleteTask task;
6078
1.61k
                        task.rowset_meta = rowset_meta;
6079
1.61k
                        task.recycle_rowset_key = k;
6080
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6081
1.60k
                            return;
6082
1.60k
                        }
6083
13
                        num_compacted += is_compacted;
6084
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6085
13
                        if (rowset_meta.num_segments() == 0) {
6086
0
                            ++num_empty_rowset;
6087
0
                        }
6088
13
                    });
6089
1.61k
        }
6090
2.01k
        return 0;
6091
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
5996
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
5997
2.01k
        ++num_scanned;
5998
2.01k
        total_rowset_key_size += k.size();
5999
2.01k
        total_rowset_value_size += v.size();
6000
2.01k
        RecycleRowsetPB rowset;
6001
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6002
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6003
0
            return -1;
6004
0
        }
6005
6006
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6007
6008
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6009
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6010
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6011
2.01k
        int64_t current_time = ::time(nullptr);
6012
2.01k
        if (current_time < final_expiration) { // not expired
6013
0
            return 0;
6014
0
        }
6015
2.01k
        ++num_expired;
6016
2.01k
        expired_rowset_size += v.size();
6017
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6018
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6019
                // in old version, keep this key-value pair and it needs to be checked manually
6020
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6021
0
                return -1;
6022
0
            }
6023
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6024
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6025
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6026
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6027
0
                orphan_rowset_keys.emplace_back(k);
6028
0
                return -1;
6029
0
            }
6030
            // decode rowset_id
6031
0
            auto k1 = k;
6032
0
            k1.remove_prefix(1);
6033
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6034
0
            decode_key(&k1, &out);
6035
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6036
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6037
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6038
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6039
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6040
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6041
0
                return -1;
6042
0
            }
6043
0
            return 0;
6044
0
        }
6045
        // TODO(plat1ko): check rowset not referenced
6046
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6047
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6048
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6049
0
                LOG_INFO("recycle rowset that has empty resource id");
6050
0
            } else {
6051
                // other situations, keep this key-value pair and it needs to be checked manually
6052
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6053
0
                return -1;
6054
0
            }
6055
0
        }
6056
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6057
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6058
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6059
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6060
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6061
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6062
2.01k
                  << " rowset_meta_size=" << v.size()
6063
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6064
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6065
            // unable to calculate file path, can only be deleted by rowset id prefix
6066
400
            num_prepare += 1;
6067
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6068
400
                                             rowset_meta->tablet_id(),
6069
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6070
0
                return -1;
6071
0
            }
6072
1.61k
        } else {
6073
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6074
1.61k
            worker_pool->submit(
6075
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6076
                        // The load & compact rowset keys are recycled during recycling operation logs.
6077
1.61k
                        RowsetDeleteTask task;
6078
1.61k
                        task.rowset_meta = rowset_meta;
6079
1.61k
                        task.recycle_rowset_key = k;
6080
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6081
1.61k
                            return;
6082
1.61k
                        }
6083
1.61k
                        num_compacted += is_compacted;
6084
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6085
1.61k
                        if (rowset_meta.num_segments() == 0) {
6086
1.61k
                            ++num_empty_rowset;
6087
1.61k
                        }
6088
1.61k
                    });
6089
1.61k
        }
6090
2.01k
        return 0;
6091
2.01k
    };
6092
6093
11
    if (config::enable_recycler_stats_metrics) {
6094
0
        scan_and_statistics_rowsets();
6095
0
    }
6096
6097
11
    auto loop_done = [&]() -> int {
6098
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6099
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6100
0
        }
6101
6
        orphan_rowset_keys.clear();
6102
6
        return 0;
6103
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
Line
Count
Source
6097
6
    auto loop_done = [&]() -> int {
6098
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6099
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6100
0
        }
6101
6
        orphan_rowset_keys.clear();
6102
6
        return 0;
6103
6
    };
6104
6105
    // recycle_func and loop_done for scan and recycle
6106
11
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
6107
11
                               std::move(loop_done));
6108
6109
11
    worker_pool->stop();
6110
6111
11
    if (!async_recycled_rowset_keys.empty()) {
6112
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
6113
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6114
0
            return -1;
6115
0
        } else {
6116
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
6117
0
        }
6118
0
    }
6119
6120
    // Report final metrics after all concurrent tasks completed
6121
11
    segment_metrics_context_.report();
6122
11
    metrics_context.report();
6123
6124
11
    return ret;
6125
11
}
6126
6127
1.61k
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task) {
6128
1.61k
    constexpr int MAX_RETRY = 10;
6129
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
6130
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
6131
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
6132
1.61k
    std::string_view reference_instance_id = instance_id_;
6133
1.61k
    if (rowset_meta.has_reference_instance_id()) {
6134
8
        reference_instance_id = rowset_meta.reference_instance_id();
6135
8
    }
6136
6137
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
6138
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
6139
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
6140
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
6141
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
6142
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
6143
1.61k
        std::unique_ptr<Transaction> txn;
6144
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6145
1.61k
        if (err != TxnErrorCode::TXN_OK) {
6146
0
            LOG_WARNING("failed to create txn").tag("err", err);
6147
0
            return -1;
6148
0
        }
6149
6150
1.61k
        std::string rowset_ref_count_key =
6151
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
6152
1.61k
        int64_t ref_count = 0;
6153
1.61k
        {
6154
1.61k
            std::string value;
6155
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
6156
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6157
                // This is the old version rowset, we could recycle it directly.
6158
1.60k
                ref_count = 1;
6159
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
6160
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
6161
0
                return -1;
6162
10
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
6163
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
6164
0
                return -1;
6165
0
            }
6166
1.61k
        }
6167
6168
1.61k
        if (ref_count == 1) {
6169
            // It would not be added since it is recycling.
6170
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
6171
1.60k
                LOG_WARNING("failed to delete rowset data");
6172
1.60k
                return -1;
6173
1.60k
            }
6174
6175
            // Reset the transaction to avoid timeout.
6176
10
            err = txn_kv_->create_txn(&txn);
6177
10
            if (err != TxnErrorCode::TXN_OK) {
6178
0
                LOG_WARNING("failed to create txn").tag("err", err);
6179
0
                return -1;
6180
0
            }
6181
10
            txn->remove(rowset_ref_count_key);
6182
10
            LOG_INFO("delete rowset data ref count key")
6183
10
                    .tag("txn_id", rowset_meta.txn_id())
6184
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6185
6186
10
            std::string dbm_start_key =
6187
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
6188
10
            std::string dbm_end_key = meta_delete_bitmap_key(
6189
10
                    {reference_instance_id, tablet_id, rowset_id,
6190
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
6191
10
            txn->remove(dbm_start_key, dbm_end_key);
6192
10
            LOG_INFO("remove delete bitmap kv")
6193
10
                    .tag("begin", hex(dbm_start_key))
6194
10
                    .tag("end", hex(dbm_end_key));
6195
6196
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
6197
10
                    {reference_instance_id, tablet_id, rowset_id});
6198
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
6199
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
6200
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
6201
10
            LOG_INFO("remove versioned delete bitmap kv")
6202
10
                    .tag("begin", hex(versioned_dbm_start_key))
6203
10
                    .tag("end", hex(versioned_dbm_end_key));
6204
10
        } else {
6205
            // Decrease the rowset ref count.
6206
            //
6207
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
6208
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
6209
2
            txn->atomic_add(rowset_ref_count_key, -1);
6210
2
            LOG_INFO("decrease rowset data ref count")
6211
2
                    .tag("txn_id", rowset_meta.txn_id())
6212
2
                    .tag("ref_count", ref_count - 1)
6213
2
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6214
2
        }
6215
6216
12
        if (!task.versioned_rowset_key.empty()) {
6217
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
6218
0
                                                          task.versionstamp);
6219
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
6220
0
        }
6221
6222
12
        if (!task.non_versioned_rowset_key.empty()) {
6223
0
            txn->remove(task.non_versioned_rowset_key);
6224
0
            LOG_INFO("remove non versioned rowset key")
6225
0
                    .tag("key", hex(task.non_versioned_rowset_key));
6226
0
        }
6227
6228
        // empty when recycle ref rowsets for deleted instance
6229
13
        if (!task.recycle_rowset_key.empty()) {
6230
13
            txn->remove(task.recycle_rowset_key);
6231
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
6232
13
        }
6233
6234
12
        err = txn->commit();
6235
12
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
6236
            // The rowset ref count key has been changed, we need to retry.
6237
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
6238
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
6239
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
6240
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6241
0
            continue;
6242
12
        } else if (err != TxnErrorCode::TXN_OK) {
6243
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
6244
0
            return -1;
6245
0
        }
6246
12
        LOG_INFO("recycle rowset meta and data success");
6247
12
        return 0;
6248
12
    }
6249
1
    LOG_WARNING("failed to recycle rowset meta and data after retry")
6250
1
            .tag("tablet_id", tablet_id)
6251
1
            .tag("rowset_id", rowset_id)
6252
1
            .tag("retry", MAX_RETRY);
6253
1
    return -1;
6254
1.61k
}
6255
6256
35
int InstanceRecycler::recycle_tmp_rowsets() {
6257
35
    const std::string task_name = "recycle_tmp_rowsets";
6258
35
    int64_t num_scanned = 0;
6259
35
    int64_t num_expired = 0;
6260
35
    std::atomic_long num_recycled = 0;
6261
35
    size_t expired_rowset_size = 0;
6262
35
    size_t total_rowset_key_size = 0;
6263
35
    size_t total_rowset_value_size = 0;
6264
35
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6265
6266
35
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
6267
35
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
6268
35
    std::string tmp_rs_key0;
6269
35
    std::string tmp_rs_key1;
6270
35
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
6271
35
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
6272
6273
35
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
6274
6275
35
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6276
35
    register_recycle_task(task_name, start_time);
6277
6278
35
    DORIS_CLOUD_DEFER {
6279
35
        unregister_recycle_task(task_name);
6280
35
        int64_t cost =
6281
35
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6282
35
        metrics_context.finish_report();
6283
35
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6284
35
                .tag("instance_id", instance_id_)
6285
35
                .tag("num_scanned", num_scanned)
6286
35
                .tag("num_expired", num_expired)
6287
35
                .tag("num_recycled", num_recycled)
6288
35
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6289
35
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6290
35
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6291
35
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6278
12
    DORIS_CLOUD_DEFER {
6279
12
        unregister_recycle_task(task_name);
6280
12
        int64_t cost =
6281
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6282
12
        metrics_context.finish_report();
6283
12
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6284
12
                .tag("instance_id", instance_id_)
6285
12
                .tag("num_scanned", num_scanned)
6286
12
                .tag("num_expired", num_expired)
6287
12
                .tag("num_recycled", num_recycled)
6288
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6289
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6290
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6291
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6278
23
    DORIS_CLOUD_DEFER {
6279
23
        unregister_recycle_task(task_name);
6280
23
        int64_t cost =
6281
23
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6282
23
        metrics_context.finish_report();
6283
23
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6284
23
                .tag("instance_id", instance_id_)
6285
23
                .tag("num_scanned", num_scanned)
6286
23
                .tag("num_expired", num_expired)
6287
23
                .tag("num_recycled", num_recycled)
6288
23
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6289
23
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6290
23
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6291
23
    };
6292
6293
    // Elements in `tmp_rowset_keys` has the same lifetime as `it`
6294
6295
35
    std::vector<std::string> tmp_rowset_keys;
6296
35
    std::vector<std::string> tmp_rowset_ref_count_keys;
6297
35
    std::vector<std::string> tmp_rowset_keys_to_mark_recycled;
6298
35
    std::vector<std::string> tmp_rowset_keys_to_abort;
6299
6300
    // rowset_id -> rowset_meta
6301
    // store tmp_rowset id and meta for statistics rs size when delete
6302
35
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
6303
35
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6304
35
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
6305
35
    worker_pool->start();
6306
6307
35
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6308
6309
35
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &tmp_rowsets,
6310
35
                             &expired_rowset_size, &total_rowset_key_size, &total_rowset_value_size,
6311
35
                             &earlest_ts, &tmp_rowset_ref_count_keys,
6312
35
                             &tmp_rowset_keys_to_mark_recycled, &tmp_rowset_keys_to_abort, this,
6313
53.0k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
6314
53.0k
        ++num_scanned;
6315
53.0k
        total_rowset_key_size += k.size();
6316
53.0k
        total_rowset_value_size += v.size();
6317
53.0k
        doris::RowsetMetaCloudPB rowset;
6318
53.0k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6319
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6320
0
            return -1;
6321
0
        }
6322
53.0k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6323
53.0k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6324
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6325
0
                   << " txn_expiration=" << rowset.txn_expiration()
6326
0
                   << " rowset_creation_time=" << rowset.creation_time();
6327
53.0k
        int64_t current_time = ::time(nullptr);
6328
53.0k
        if (current_time < expiration) { // not expired
6329
0
            return 0;
6330
0
        }
6331
6332
53.0k
        if (config::enable_mark_delete_rowset_before_recycle) {
6333
16
            if (need_mark_rowset_as_recycled(rowset)) {
6334
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6335
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6336
9
                             "at next turn, instance_id="
6337
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6338
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6339
9
                return 0;
6340
9
            }
6341
16
        }
6342
6343
53.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6344
7
            if (make_deferred_abort_task(rowset).has_value()) {
6345
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6346
3
                             "instance_id="
6347
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6348
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6349
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6350
3
            }
6351
7
        }
6352
6353
53.0k
        ++num_expired;
6354
53.0k
        expired_rowset_size += v.size();
6355
53.0k
        if (!rowset.has_resource_id()) {
6356
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6357
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6358
0
                return -1;
6359
0
            }
6360
            // might be a delete pred rowset
6361
0
            tmp_rowset_keys.emplace_back(k);
6362
0
            return 0;
6363
0
        }
6364
        // TODO(plat1ko): check rowset not referenced
6365
53.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6366
53.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6367
53.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6368
53.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6369
53.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6370
53.0k
                  << " num_expired=" << num_expired
6371
53.0k
                  << " task_type=" << metrics_context.operation_type;
6372
6373
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6374
        // Remove the rowset ref count key directly since it has not been used.
6375
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6376
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6377
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6378
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6379
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6380
6381
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6382
53.0k
        return 0;
6383
53.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6313
16
                             &metrics_context](std::string_view k, std::string_view v) -> int {
6314
16
        ++num_scanned;
6315
16
        total_rowset_key_size += k.size();
6316
16
        total_rowset_value_size += v.size();
6317
16
        doris::RowsetMetaCloudPB rowset;
6318
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6319
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6320
0
            return -1;
6321
0
        }
6322
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6323
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6324
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6325
0
                   << " txn_expiration=" << rowset.txn_expiration()
6326
0
                   << " rowset_creation_time=" << rowset.creation_time();
6327
16
        int64_t current_time = ::time(nullptr);
6328
16
        if (current_time < expiration) { // not expired
6329
0
            return 0;
6330
0
        }
6331
6332
16
        if (config::enable_mark_delete_rowset_before_recycle) {
6333
16
            if (need_mark_rowset_as_recycled(rowset)) {
6334
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6335
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6336
9
                             "at next turn, instance_id="
6337
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6338
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6339
9
                return 0;
6340
9
            }
6341
16
        }
6342
6343
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6344
7
            if (make_deferred_abort_task(rowset).has_value()) {
6345
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6346
3
                             "instance_id="
6347
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6348
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6349
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6350
3
            }
6351
7
        }
6352
6353
7
        ++num_expired;
6354
7
        expired_rowset_size += v.size();
6355
7
        if (!rowset.has_resource_id()) {
6356
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6357
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6358
0
                return -1;
6359
0
            }
6360
            // might be a delete pred rowset
6361
0
            tmp_rowset_keys.emplace_back(k);
6362
0
            return 0;
6363
0
        }
6364
        // TODO(plat1ko): check rowset not referenced
6365
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6366
7
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6367
7
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6368
7
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6369
7
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6370
7
                  << " num_expired=" << num_expired
6371
7
                  << " task_type=" << metrics_context.operation_type;
6372
6373
7
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6374
        // Remove the rowset ref count key directly since it has not been used.
6375
7
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6376
7
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6377
7
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6378
7
                  << "key=" << hex(rowset_ref_count_key);
6379
7
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6380
6381
7
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6382
7
        return 0;
6383
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6313
53.0k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
6314
53.0k
        ++num_scanned;
6315
53.0k
        total_rowset_key_size += k.size();
6316
53.0k
        total_rowset_value_size += v.size();
6317
53.0k
        doris::RowsetMetaCloudPB rowset;
6318
53.0k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6319
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6320
0
            return -1;
6321
0
        }
6322
53.0k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6323
53.0k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6324
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6325
0
                   << " txn_expiration=" << rowset.txn_expiration()
6326
0
                   << " rowset_creation_time=" << rowset.creation_time();
6327
53.0k
        int64_t current_time = ::time(nullptr);
6328
53.0k
        if (current_time < expiration) { // not expired
6329
0
            return 0;
6330
0
        }
6331
6332
53.0k
        if (config::enable_mark_delete_rowset_before_recycle) {
6333
0
            if (need_mark_rowset_as_recycled(rowset)) {
6334
0
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6335
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6336
0
                             "at next turn, instance_id="
6337
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6338
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6339
0
                return 0;
6340
0
            }
6341
0
        }
6342
6343
53.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6344
0
            if (make_deferred_abort_task(rowset).has_value()) {
6345
0
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6346
0
                             "instance_id="
6347
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6348
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6349
0
                tmp_rowset_keys_to_abort.emplace_back(k);
6350
0
            }
6351
0
        }
6352
6353
53.0k
        ++num_expired;
6354
53.0k
        expired_rowset_size += v.size();
6355
53.0k
        if (!rowset.has_resource_id()) {
6356
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6357
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6358
0
                return -1;
6359
0
            }
6360
            // might be a delete pred rowset
6361
0
            tmp_rowset_keys.emplace_back(k);
6362
0
            return 0;
6363
0
        }
6364
        // TODO(plat1ko): check rowset not referenced
6365
53.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6366
53.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6367
53.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6368
53.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6369
53.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6370
53.0k
                  << " num_expired=" << num_expired
6371
53.0k
                  << " task_type=" << metrics_context.operation_type;
6372
6373
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6374
        // Remove the rowset ref count key directly since it has not been used.
6375
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6376
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6377
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6378
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6379
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6380
6381
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6382
53.0k
        return 0;
6383
53.0k
    };
6384
6385
    // TODO bacth delete
6386
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6387
51.0k
        std::string dbm_start_key =
6388
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
6389
51.0k
        std::string dbm_end_key = dbm_start_key;
6390
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
6391
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
6392
51.0k
        if (ret != 0) {
6393
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6394
0
                         << instance_id_ << ", tablet_id=" << tablet_id
6395
0
                         << ", rowset_id=" << rowset_id;
6396
0
        }
6397
51.0k
        return ret;
6398
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6386
7
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6387
7
        std::string dbm_start_key =
6388
7
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
6389
7
        std::string dbm_end_key = dbm_start_key;
6390
7
        encode_int64(INT64_MAX, &dbm_end_key);
6391
7
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
6392
7
        if (ret != 0) {
6393
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6394
0
                         << instance_id_ << ", tablet_id=" << tablet_id
6395
0
                         << ", rowset_id=" << rowset_id;
6396
0
        }
6397
7
        return ret;
6398
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6386
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6387
51.0k
        std::string dbm_start_key =
6388
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
6389
51.0k
        std::string dbm_end_key = dbm_start_key;
6390
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
6391
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
6392
51.0k
        if (ret != 0) {
6393
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6394
0
                         << instance_id_ << ", tablet_id=" << tablet_id
6395
0
                         << ", rowset_id=" << rowset_id;
6396
0
        }
6397
51.0k
        return ret;
6398
51.0k
    };
6399
6400
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6401
51.0k
        auto delete_bitmap_start =
6402
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
6403
51.0k
        auto delete_bitmap_end =
6404
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
6405
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
6406
51.0k
        if (ret != 0) {
6407
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
6408
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
6409
0
        }
6410
51.0k
        return ret;
6411
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6400
7
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6401
7
        auto delete_bitmap_start =
6402
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
6403
7
        auto delete_bitmap_end =
6404
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
6405
7
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
6406
7
        if (ret != 0) {
6407
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
6408
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
6409
0
        }
6410
7
        return ret;
6411
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6400
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6401
51.0k
        auto delete_bitmap_start =
6402
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
6403
51.0k
        auto delete_bitmap_end =
6404
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
6405
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
6406
51.0k
        if (ret != 0) {
6407
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
6408
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
6409
0
        }
6410
51.0k
        return ret;
6411
51.0k
    };
6412
6413
35
    auto loop_done = [&]() -> int {
6414
22
        std::vector<std::string> tmp_rowset_keys_to_delete;
6415
22
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6416
22
        std::vector<std::string> mark_keys_to_process;
6417
22
        std::vector<std::string> abort_keys_to_process;
6418
22
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6419
22
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6420
22
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6421
22
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6422
22
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6423
22
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6424
22
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6425
22
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6426
22
                             tmp_rowset_ref_count_keys_to_delete =
6427
22
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6428
22
                             mark_keys_to_process = std::move(mark_keys_to_process),
6429
22
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6430
22
            if (!mark_keys_to_process.empty() &&
6431
22
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6432
7
                                                                  mark_keys_to_process) != 0) {
6433
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6434
0
                             << instance_id_;
6435
0
                return;
6436
0
            }
6437
22
            if (!abort_keys_to_process.empty() &&
6438
22
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6439
3
                                                                      false) != 0) {
6440
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6441
0
                             << instance_id_;
6442
0
                return;
6443
0
            }
6444
22
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6445
22
                                   metrics_context) != 0) {
6446
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6447
2
                return;
6448
2
            }
6449
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6450
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6451
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6452
0
                                 << rs.ShortDebugString();
6453
0
                    return;
6454
0
                }
6455
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6456
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6457
0
                                 << rs.ShortDebugString();
6458
0
                    return;
6459
0
                }
6460
51.0k
            }
6461
20
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6462
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6463
0
                return;
6464
0
            }
6465
20
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6466
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6467
0
                return;
6468
0
            }
6469
20
            num_recycled += tmp_rowset_keys_to_delete.size();
6470
20
            return;
6471
20
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
6429
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6430
12
            if (!mark_keys_to_process.empty() &&
6431
12
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6432
7
                                                                  mark_keys_to_process) != 0) {
6433
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6434
0
                             << instance_id_;
6435
0
                return;
6436
0
            }
6437
12
            if (!abort_keys_to_process.empty() &&
6438
12
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6439
3
                                                                      false) != 0) {
6440
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6441
0
                             << instance_id_;
6442
0
                return;
6443
0
            }
6444
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6445
12
                                   metrics_context) != 0) {
6446
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6447
0
                return;
6448
0
            }
6449
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6450
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6451
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6452
0
                                 << rs.ShortDebugString();
6453
0
                    return;
6454
0
                }
6455
7
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6456
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6457
0
                                 << rs.ShortDebugString();
6458
0
                    return;
6459
0
                }
6460
7
            }
6461
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6462
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6463
0
                return;
6464
0
            }
6465
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6466
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6467
0
                return;
6468
0
            }
6469
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6470
12
            return;
6471
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
6429
10
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6430
10
            if (!mark_keys_to_process.empty() &&
6431
10
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6432
0
                                                                  mark_keys_to_process) != 0) {
6433
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6434
0
                             << instance_id_;
6435
0
                return;
6436
0
            }
6437
10
            if (!abort_keys_to_process.empty() &&
6438
10
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6439
0
                                                                      false) != 0) {
6440
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6441
0
                             << instance_id_;
6442
0
                return;
6443
0
            }
6444
10
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6445
10
                                   metrics_context) != 0) {
6446
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6447
2
                return;
6448
2
            }
6449
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6450
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6451
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6452
0
                                 << rs.ShortDebugString();
6453
0
                    return;
6454
0
                }
6455
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6456
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6457
0
                                 << rs.ShortDebugString();
6458
0
                    return;
6459
0
                }
6460
51.0k
            }
6461
8
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6462
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6463
0
                return;
6464
0
            }
6465
8
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6466
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6467
0
                return;
6468
0
            }
6469
8
            num_recycled += tmp_rowset_keys_to_delete.size();
6470
8
            return;
6471
8
        });
6472
22
        return 0;
6473
22
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEv
Line
Count
Source
6413
12
    auto loop_done = [&]() -> int {
6414
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6415
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6416
12
        std::vector<std::string> mark_keys_to_process;
6417
12
        std::vector<std::string> abort_keys_to_process;
6418
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6419
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6420
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6421
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6422
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6423
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6424
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6425
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6426
12
                             tmp_rowset_ref_count_keys_to_delete =
6427
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6428
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6429
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6430
12
            if (!mark_keys_to_process.empty() &&
6431
12
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6432
12
                                                                  mark_keys_to_process) != 0) {
6433
12
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6434
12
                             << instance_id_;
6435
12
                return;
6436
12
            }
6437
12
            if (!abort_keys_to_process.empty() &&
6438
12
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6439
12
                                                                      false) != 0) {
6440
12
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6441
12
                             << instance_id_;
6442
12
                return;
6443
12
            }
6444
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6445
12
                                   metrics_context) != 0) {
6446
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6447
12
                return;
6448
12
            }
6449
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6450
12
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6451
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6452
12
                                 << rs.ShortDebugString();
6453
12
                    return;
6454
12
                }
6455
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6456
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6457
12
                                 << rs.ShortDebugString();
6458
12
                    return;
6459
12
                }
6460
12
            }
6461
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6462
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6463
12
                return;
6464
12
            }
6465
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6466
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6467
12
                return;
6468
12
            }
6469
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6470
12
            return;
6471
12
        });
6472
12
        return 0;
6473
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEv
Line
Count
Source
6413
10
    auto loop_done = [&]() -> int {
6414
10
        std::vector<std::string> tmp_rowset_keys_to_delete;
6415
10
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6416
10
        std::vector<std::string> mark_keys_to_process;
6417
10
        std::vector<std::string> abort_keys_to_process;
6418
10
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6419
10
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6420
10
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6421
10
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6422
10
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6423
10
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6424
10
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6425
10
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6426
10
                             tmp_rowset_ref_count_keys_to_delete =
6427
10
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6428
10
                             mark_keys_to_process = std::move(mark_keys_to_process),
6429
10
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6430
10
            if (!mark_keys_to_process.empty() &&
6431
10
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6432
10
                                                                  mark_keys_to_process) != 0) {
6433
10
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6434
10
                             << instance_id_;
6435
10
                return;
6436
10
            }
6437
10
            if (!abort_keys_to_process.empty() &&
6438
10
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6439
10
                                                                      false) != 0) {
6440
10
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6441
10
                             << instance_id_;
6442
10
                return;
6443
10
            }
6444
10
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6445
10
                                   metrics_context) != 0) {
6446
10
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6447
10
                return;
6448
10
            }
6449
10
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6450
10
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6451
10
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6452
10
                                 << rs.ShortDebugString();
6453
10
                    return;
6454
10
                }
6455
10
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6456
10
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6457
10
                                 << rs.ShortDebugString();
6458
10
                    return;
6459
10
                }
6460
10
            }
6461
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6462
10
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6463
10
                return;
6464
10
            }
6465
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6466
10
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6467
10
                return;
6468
10
            }
6469
10
            num_recycled += tmp_rowset_keys_to_delete.size();
6470
10
            return;
6471
10
        });
6472
10
        return 0;
6473
10
    };
6474
6475
35
    if (config::enable_recycler_stats_metrics) {
6476
0
        scan_and_statistics_tmp_rowsets();
6477
0
    }
6478
    // recycle_func and loop_done for scan and recycle
6479
35
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
6480
35
                               std::move(loop_done));
6481
6482
35
    worker_pool->stop();
6483
6484
    // Report final metrics after all concurrent tasks completed
6485
35
    segment_metrics_context_.report();
6486
35
    metrics_context.report();
6487
6488
35
    return ret;
6489
35
}
6490
6491
int InstanceRecycler::scan_and_recycle(
6492
        std::string begin, std::string_view end,
6493
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
6494
324
        std::function<int()> loop_done, std::function<bool(std::string*)> next_begin_getter) {
6495
324
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
6496
324
    int ret = 0;
6497
324
    int64_t cnt = 0;
6498
324
    int get_range_retried = 0;
6499
324
    std::string err;
6500
324
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6501
324
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6502
324
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6503
324
                  << " ret=" << ret << " err=" << err;
6504
324
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6500
36
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6501
36
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6502
36
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6503
36
                  << " ret=" << ret << " err=" << err;
6504
36
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6500
288
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6501
288
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6502
288
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6503
288
                  << " ret=" << ret << " err=" << err;
6504
288
    };
6505
6506
324
    std::unique_ptr<RangeGetIterator> it;
6507
503
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
6508
359
        if (get_range_retried > 1000) {
6509
0
            err = "txn_get exceeds max retry(1000), may not scan all keys";
6510
0
            ret = -3;
6511
0
            return ret;
6512
0
        }
6513
359
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
6514
359
        if (get_ret != 0) { // txn kv may complain "Request for future version"
6515
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
6516
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
6517
0
                         << " get_range_retried=" << get_range_retried;
6518
0
            ++get_range_retried;
6519
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6520
0
            continue; // try again
6521
0
        }
6522
359
        if (!it->has_next()) {
6523
180
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
6524
180
            break; // scan finished
6525
180
        }
6526
179
        bool begin_updated = false;
6527
179
        LOG(INFO) << "scan_and_recycle iterator key_range=[" << hex(begin) << "," << hex(end)
6528
179
                  << ") iterator->size()=" << it->size();
6529
97.6k
        while (it->has_next()) {
6530
97.4k
            ++cnt;
6531
            // recycle corresponding resources
6532
97.4k
            auto [k, v] = it->next();
6533
97.4k
            if (!it->has_next()) {
6534
172
                begin = k;
6535
172
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
6536
172
            }
6537
            // FIXME(gavin): if we want to continue scanning, the recycle_func should not return non-zero
6538
97.4k
            if (recycle_func(k, v) != 0) {
6539
4.00k
                err = "recycle_func error";
6540
4.00k
                ret = -1;
6541
4.00k
            }
6542
97.4k
            if (next_begin_getter) {
6543
4.05k
                std::string next_begin;
6544
4.05k
                if (next_begin_getter(&next_begin)) {
6545
7
                    if (next_begin > k) {
6546
7
                        begin = std::move(next_begin);
6547
7
                        begin_updated = true;
6548
7
                        VLOG_DEBUG << "scan_and_recycle updates begin to " << hex(begin)
6549
0
                                   << " after key=" << hex(k);
6550
7
                        break;
6551
7
                    }
6552
0
                    LOG_WARNING("ignore invalid next begin in scan_and_recycle")
6553
0
                            .tag("next_begin", hex(next_begin))
6554
0
                            .tag("current_key", hex(k));
6555
0
                }
6556
4.05k
            }
6557
97.4k
        }
6558
179
        if (!begin_updated) {
6559
171
            begin.push_back('\x00'); // Update to next smallest key for iteration
6560
171
        } else {
6561
8
            it.reset();
6562
8
        }
6563
6564
        // FIXME(gavin): if we want to continue scanning, the loop_done should not return non-zero
6565
        // if we want to continue scanning, the recycle_func should not return non-zero
6566
179
        if (loop_done && loop_done() != 0) {
6567
5
            err = "loop_done error";
6568
5
            ret = -1;
6569
5
        }
6570
179
    }
6571
324
    return ret;
6572
324
}
6573
6574
19
int InstanceRecycler::abort_timeout_txn() {
6575
19
    const std::string task_name = "abort_timeout_txn";
6576
19
    int64_t num_scanned = 0;
6577
19
    int64_t num_timeout = 0;
6578
19
    int64_t num_abort = 0;
6579
19
    int64_t num_advance = 0;
6580
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6581
6582
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6583
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6584
19
    std::string begin_txn_running_key;
6585
19
    std::string end_txn_running_key;
6586
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6587
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6588
6589
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
6590
6591
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6592
19
    register_recycle_task(task_name, start_time);
6593
6594
19
    DORIS_CLOUD_DEFER {
6595
19
        unregister_recycle_task(task_name);
6596
19
        int64_t cost =
6597
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6598
19
        metrics_context.finish_report();
6599
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6600
19
                .tag("instance_id", instance_id_)
6601
19
                .tag("num_scanned", num_scanned)
6602
19
                .tag("num_timeout", num_timeout)
6603
19
                .tag("num_abort", num_abort)
6604
19
                .tag("num_advance", num_advance);
6605
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6594
3
    DORIS_CLOUD_DEFER {
6595
3
        unregister_recycle_task(task_name);
6596
3
        int64_t cost =
6597
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6598
3
        metrics_context.finish_report();
6599
3
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6600
3
                .tag("instance_id", instance_id_)
6601
3
                .tag("num_scanned", num_scanned)
6602
3
                .tag("num_timeout", num_timeout)
6603
3
                .tag("num_abort", num_abort)
6604
3
                .tag("num_advance", num_advance);
6605
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6594
16
    DORIS_CLOUD_DEFER {
6595
16
        unregister_recycle_task(task_name);
6596
16
        int64_t cost =
6597
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6598
16
        metrics_context.finish_report();
6599
16
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6600
16
                .tag("instance_id", instance_id_)
6601
16
                .tag("num_scanned", num_scanned)
6602
16
                .tag("num_timeout", num_timeout)
6603
16
                .tag("num_abort", num_abort)
6604
16
                .tag("num_advance", num_advance);
6605
16
    };
6606
6607
19
    int64_t current_time =
6608
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6609
6610
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
6611
19
                                  &current_time, &metrics_context,
6612
19
                                  this](std::string_view k, std::string_view v) -> int {
6613
9
        ++num_scanned;
6614
6615
9
        std::unique_ptr<Transaction> txn;
6616
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6617
9
        if (err != TxnErrorCode::TXN_OK) {
6618
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6619
0
            return -1;
6620
0
        }
6621
9
        std::string_view k1 = k;
6622
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6623
9
        k1.remove_prefix(1); // Remove key space
6624
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6625
9
        if (decode_key(&k1, &out) != 0) {
6626
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6627
0
            return -1;
6628
0
        }
6629
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6630
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6631
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6632
        // Update txn_info
6633
9
        std::string txn_inf_key, txn_inf_val;
6634
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6635
9
        err = txn->get(txn_inf_key, &txn_inf_val);
6636
9
        if (err != TxnErrorCode::TXN_OK) {
6637
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6638
0
            return -1;
6639
0
        }
6640
9
        TxnInfoPB txn_info;
6641
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
6642
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6643
0
            return -1;
6644
0
        }
6645
6646
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6647
3
            txn.reset();
6648
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6649
3
            std::shared_ptr<TxnLazyCommitTask> task =
6650
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6651
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6652
3
            if (ret.first != MetaServiceCode::OK) {
6653
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6654
0
                             << "msg=" << ret.second;
6655
0
                return -1;
6656
0
            }
6657
3
            ++num_advance;
6658
3
            return 0;
6659
6
        } else {
6660
6
            TxnRunningPB txn_running_pb;
6661
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6662
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6663
0
                return -1;
6664
0
            }
6665
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6666
4
                return 0;
6667
4
            }
6668
2
            ++num_timeout;
6669
6670
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6671
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6672
2
            txn_info.set_finish_time(current_time);
6673
2
            txn_info.set_reason("timeout");
6674
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6675
2
            txn_inf_val.clear();
6676
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6677
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6678
0
                return -1;
6679
0
            }
6680
2
            txn->put(txn_inf_key, txn_inf_val);
6681
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6682
            // Put recycle txn key
6683
2
            std::string recyc_txn_key, recyc_txn_val;
6684
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6685
2
            RecycleTxnPB recycle_txn_pb;
6686
2
            recycle_txn_pb.set_creation_time(current_time);
6687
2
            recycle_txn_pb.set_label(txn_info.label());
6688
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6689
0
                LOG_WARNING("failed to serialize txn recycle info")
6690
0
                        .tag("key", hex(k))
6691
0
                        .tag("db_id", db_id)
6692
0
                        .tag("txn_id", txn_id);
6693
0
                return -1;
6694
0
            }
6695
2
            txn->put(recyc_txn_key, recyc_txn_val);
6696
            // Remove txn running key
6697
2
            txn->remove(k);
6698
2
            err = txn->commit();
6699
2
            if (err != TxnErrorCode::TXN_OK) {
6700
0
                LOG_WARNING("failed to commit txn err={}", err)
6701
0
                        .tag("key", hex(k))
6702
0
                        .tag("db_id", db_id)
6703
0
                        .tag("txn_id", txn_id);
6704
0
                return -1;
6705
0
            }
6706
2
            metrics_context.total_recycled_num = ++num_abort;
6707
2
            metrics_context.report();
6708
2
        }
6709
6710
2
        return 0;
6711
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6612
3
                                  this](std::string_view k, std::string_view v) -> int {
6613
3
        ++num_scanned;
6614
6615
3
        std::unique_ptr<Transaction> txn;
6616
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6617
3
        if (err != TxnErrorCode::TXN_OK) {
6618
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6619
0
            return -1;
6620
0
        }
6621
3
        std::string_view k1 = k;
6622
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6623
3
        k1.remove_prefix(1); // Remove key space
6624
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6625
3
        if (decode_key(&k1, &out) != 0) {
6626
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6627
0
            return -1;
6628
0
        }
6629
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6630
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6631
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6632
        // Update txn_info
6633
3
        std::string txn_inf_key, txn_inf_val;
6634
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6635
3
        err = txn->get(txn_inf_key, &txn_inf_val);
6636
3
        if (err != TxnErrorCode::TXN_OK) {
6637
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6638
0
            return -1;
6639
0
        }
6640
3
        TxnInfoPB txn_info;
6641
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
6642
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6643
0
            return -1;
6644
0
        }
6645
6646
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6647
3
            txn.reset();
6648
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6649
3
            std::shared_ptr<TxnLazyCommitTask> task =
6650
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6651
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6652
3
            if (ret.first != MetaServiceCode::OK) {
6653
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6654
0
                             << "msg=" << ret.second;
6655
0
                return -1;
6656
0
            }
6657
3
            ++num_advance;
6658
3
            return 0;
6659
3
        } else {
6660
0
            TxnRunningPB txn_running_pb;
6661
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6662
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6663
0
                return -1;
6664
0
            }
6665
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6666
0
                return 0;
6667
0
            }
6668
0
            ++num_timeout;
6669
6670
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6671
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6672
0
            txn_info.set_finish_time(current_time);
6673
0
            txn_info.set_reason("timeout");
6674
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6675
0
            txn_inf_val.clear();
6676
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6677
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6678
0
                return -1;
6679
0
            }
6680
0
            txn->put(txn_inf_key, txn_inf_val);
6681
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6682
            // Put recycle txn key
6683
0
            std::string recyc_txn_key, recyc_txn_val;
6684
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6685
0
            RecycleTxnPB recycle_txn_pb;
6686
0
            recycle_txn_pb.set_creation_time(current_time);
6687
0
            recycle_txn_pb.set_label(txn_info.label());
6688
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6689
0
                LOG_WARNING("failed to serialize txn recycle info")
6690
0
                        .tag("key", hex(k))
6691
0
                        .tag("db_id", db_id)
6692
0
                        .tag("txn_id", txn_id);
6693
0
                return -1;
6694
0
            }
6695
0
            txn->put(recyc_txn_key, recyc_txn_val);
6696
            // Remove txn running key
6697
0
            txn->remove(k);
6698
0
            err = txn->commit();
6699
0
            if (err != TxnErrorCode::TXN_OK) {
6700
0
                LOG_WARNING("failed to commit txn err={}", err)
6701
0
                        .tag("key", hex(k))
6702
0
                        .tag("db_id", db_id)
6703
0
                        .tag("txn_id", txn_id);
6704
0
                return -1;
6705
0
            }
6706
0
            metrics_context.total_recycled_num = ++num_abort;
6707
0
            metrics_context.report();
6708
0
        }
6709
6710
0
        return 0;
6711
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6612
6
                                  this](std::string_view k, std::string_view v) -> int {
6613
6
        ++num_scanned;
6614
6615
6
        std::unique_ptr<Transaction> txn;
6616
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6617
6
        if (err != TxnErrorCode::TXN_OK) {
6618
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6619
0
            return -1;
6620
0
        }
6621
6
        std::string_view k1 = k;
6622
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6623
6
        k1.remove_prefix(1); // Remove key space
6624
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6625
6
        if (decode_key(&k1, &out) != 0) {
6626
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6627
0
            return -1;
6628
0
        }
6629
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6630
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6631
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6632
        // Update txn_info
6633
6
        std::string txn_inf_key, txn_inf_val;
6634
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6635
6
        err = txn->get(txn_inf_key, &txn_inf_val);
6636
6
        if (err != TxnErrorCode::TXN_OK) {
6637
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6638
0
            return -1;
6639
0
        }
6640
6
        TxnInfoPB txn_info;
6641
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
6642
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6643
0
            return -1;
6644
0
        }
6645
6646
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6647
0
            txn.reset();
6648
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6649
0
            std::shared_ptr<TxnLazyCommitTask> task =
6650
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6651
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6652
0
            if (ret.first != MetaServiceCode::OK) {
6653
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6654
0
                             << "msg=" << ret.second;
6655
0
                return -1;
6656
0
            }
6657
0
            ++num_advance;
6658
0
            return 0;
6659
6
        } else {
6660
6
            TxnRunningPB txn_running_pb;
6661
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6662
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6663
0
                return -1;
6664
0
            }
6665
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6666
4
                return 0;
6667
4
            }
6668
2
            ++num_timeout;
6669
6670
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6671
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6672
2
            txn_info.set_finish_time(current_time);
6673
2
            txn_info.set_reason("timeout");
6674
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6675
2
            txn_inf_val.clear();
6676
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6677
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6678
0
                return -1;
6679
0
            }
6680
2
            txn->put(txn_inf_key, txn_inf_val);
6681
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6682
            // Put recycle txn key
6683
2
            std::string recyc_txn_key, recyc_txn_val;
6684
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6685
2
            RecycleTxnPB recycle_txn_pb;
6686
2
            recycle_txn_pb.set_creation_time(current_time);
6687
2
            recycle_txn_pb.set_label(txn_info.label());
6688
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6689
0
                LOG_WARNING("failed to serialize txn recycle info")
6690
0
                        .tag("key", hex(k))
6691
0
                        .tag("db_id", db_id)
6692
0
                        .tag("txn_id", txn_id);
6693
0
                return -1;
6694
0
            }
6695
2
            txn->put(recyc_txn_key, recyc_txn_val);
6696
            // Remove txn running key
6697
2
            txn->remove(k);
6698
2
            err = txn->commit();
6699
2
            if (err != TxnErrorCode::TXN_OK) {
6700
0
                LOG_WARNING("failed to commit txn err={}", err)
6701
0
                        .tag("key", hex(k))
6702
0
                        .tag("db_id", db_id)
6703
0
                        .tag("txn_id", txn_id);
6704
0
                return -1;
6705
0
            }
6706
2
            metrics_context.total_recycled_num = ++num_abort;
6707
2
            metrics_context.report();
6708
2
        }
6709
6710
2
        return 0;
6711
6
    };
6712
6713
19
    if (config::enable_recycler_stats_metrics) {
6714
0
        scan_and_statistics_abort_timeout_txn();
6715
0
    }
6716
    // recycle_func and loop_done for scan and recycle
6717
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
6718
19
                            std::move(handle_txn_running_kv));
6719
19
}
6720
6721
19
int InstanceRecycler::recycle_expired_txn_label() {
6722
19
    const std::string task_name = "recycle_expired_txn_label";
6723
19
    int64_t num_scanned = 0;
6724
19
    int64_t num_expired = 0;
6725
19
    std::atomic_long num_recycled = 0;
6726
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6727
19
    int ret = 0;
6728
6729
19
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
6730
19
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6731
19
    std::string begin_recycle_txn_key;
6732
19
    std::string end_recycle_txn_key;
6733
19
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
6734
19
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
6735
19
    std::vector<std::string> recycle_txn_info_keys;
6736
6737
19
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
6738
6739
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6740
19
    register_recycle_task(task_name, start_time);
6741
19
    DORIS_CLOUD_DEFER {
6742
19
        unregister_recycle_task(task_name);
6743
19
        int64_t cost =
6744
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6745
19
        metrics_context.finish_report();
6746
19
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6747
19
                .tag("instance_id", instance_id_)
6748
19
                .tag("num_scanned", num_scanned)
6749
19
                .tag("num_expired", num_expired)
6750
19
                .tag("num_recycled", num_recycled);
6751
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6741
1
    DORIS_CLOUD_DEFER {
6742
1
        unregister_recycle_task(task_name);
6743
1
        int64_t cost =
6744
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6745
1
        metrics_context.finish_report();
6746
1
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6747
1
                .tag("instance_id", instance_id_)
6748
1
                .tag("num_scanned", num_scanned)
6749
1
                .tag("num_expired", num_expired)
6750
1
                .tag("num_recycled", num_recycled);
6751
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6741
18
    DORIS_CLOUD_DEFER {
6742
18
        unregister_recycle_task(task_name);
6743
18
        int64_t cost =
6744
18
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6745
18
        metrics_context.finish_report();
6746
18
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6747
18
                .tag("instance_id", instance_id_)
6748
18
                .tag("num_scanned", num_scanned)
6749
18
                .tag("num_expired", num_expired)
6750
18
                .tag("num_recycled", num_recycled);
6751
18
    };
6752
6753
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6754
6755
19
    SyncExecutor<int> concurrent_delete_executor(
6756
19
            _thread_pool_group.s3_producer_pool,
6757
19
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
6758
23.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
6758
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
6758
23.0k
            [](const int& ret) { return ret != 0; });
6759
6760
19
    int64_t current_time_ms =
6761
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6762
6763
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6764
30.0k
        ++num_scanned;
6765
30.0k
        RecycleTxnPB recycle_txn_pb;
6766
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6767
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6768
0
            return -1;
6769
0
        }
6770
30.0k
        if ((config::force_immediate_recycle) ||
6771
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6772
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6773
30.0k
             current_time_ms)) {
6774
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6775
23.0k
            num_expired++;
6776
23.0k
            recycle_txn_info_keys.emplace_back(k);
6777
23.0k
        }
6778
30.0k
        return 0;
6779
30.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6763
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6764
1
        ++num_scanned;
6765
1
        RecycleTxnPB recycle_txn_pb;
6766
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6767
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6768
0
            return -1;
6769
0
        }
6770
1
        if ((config::force_immediate_recycle) ||
6771
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6772
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6773
1
             current_time_ms)) {
6774
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6775
1
            num_expired++;
6776
1
            recycle_txn_info_keys.emplace_back(k);
6777
1
        }
6778
1
        return 0;
6779
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6763
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6764
30.0k
        ++num_scanned;
6765
30.0k
        RecycleTxnPB recycle_txn_pb;
6766
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6767
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6768
0
            return -1;
6769
0
        }
6770
30.0k
        if ((config::force_immediate_recycle) ||
6771
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6772
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6773
30.0k
             current_time_ms)) {
6774
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6775
23.0k
            num_expired++;
6776
23.0k
            recycle_txn_info_keys.emplace_back(k);
6777
23.0k
        }
6778
30.0k
        return 0;
6779
30.0k
    };
6780
6781
    // int 0 for success, 1 for conflict, -1 for error
6782
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6783
23.0k
        std::string_view k1 = k;
6784
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6785
23.0k
        k1.remove_prefix(1); // Remove key space
6786
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6787
23.0k
        int ret = decode_key(&k1, &out);
6788
23.0k
        if (ret != 0) {
6789
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6790
0
            return -1;
6791
0
        }
6792
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6793
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6794
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6795
23.0k
        std::unique_ptr<Transaction> txn;
6796
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6797
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6798
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6799
0
            return -1;
6800
0
        }
6801
        // Remove txn index kv
6802
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6803
23.0k
        txn->remove(index_key);
6804
        // Remove txn info kv
6805
23.0k
        std::string info_key, info_val;
6806
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6807
23.0k
        err = txn->get(info_key, &info_val);
6808
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6809
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6810
0
            return -1;
6811
0
        }
6812
23.0k
        TxnInfoPB txn_info;
6813
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6814
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6815
0
            return -1;
6816
0
        }
6817
23.0k
        txn->remove(info_key);
6818
        // Remove sub txn index kvs
6819
23.0k
        std::vector<std::string> sub_txn_index_keys;
6820
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6821
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6822
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6823
22.9k
        }
6824
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6825
22.9k
            txn->remove(sub_txn_index_key);
6826
22.9k
        }
6827
        // Update txn label
6828
23.0k
        std::string label_key, label_val;
6829
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6830
23.0k
        err = txn->get(label_key, &label_val);
6831
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6832
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6833
0
                         << " err=" << err;
6834
0
            return -1;
6835
0
        }
6836
23.0k
        TxnLabelPB txn_label;
6837
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6838
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6839
0
            return -1;
6840
0
        }
6841
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6842
23.0k
        if (it != txn_label.txn_ids().end()) {
6843
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6844
23.0k
        }
6845
23.0k
        if (txn_label.txn_ids().empty()) {
6846
23.0k
            txn->remove(label_key);
6847
23.0k
            TEST_SYNC_POINT_CALLBACK(
6848
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6849
23.0k
        } else {
6850
73
            if (!txn_label.SerializeToString(&label_val)) {
6851
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6852
0
                return -1;
6853
0
            }
6854
73
            TEST_SYNC_POINT_CALLBACK(
6855
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6856
73
            txn->atomic_set_ver_value(label_key, label_val);
6857
73
            TEST_SYNC_POINT_CALLBACK(
6858
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6859
73
        }
6860
        // Remove recycle txn kv
6861
23.0k
        txn->remove(k);
6862
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6863
23.0k
        err = txn->commit();
6864
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6865
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6866
62
                TEST_SYNC_POINT_CALLBACK(
6867
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6868
                // log the txn_id and label
6869
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6870
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6871
62
                             << " txn_label=" << txn_info.label();
6872
62
                return 1;
6873
62
            }
6874
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6875
0
            return -1;
6876
62
        }
6877
23.0k
        ++num_recycled;
6878
6879
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6880
23.0k
        return 0;
6881
23.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6782
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6783
1
        std::string_view k1 = k;
6784
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6785
1
        k1.remove_prefix(1); // Remove key space
6786
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6787
1
        int ret = decode_key(&k1, &out);
6788
1
        if (ret != 0) {
6789
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6790
0
            return -1;
6791
0
        }
6792
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6793
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6794
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6795
1
        std::unique_ptr<Transaction> txn;
6796
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6797
1
        if (err != TxnErrorCode::TXN_OK) {
6798
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6799
0
            return -1;
6800
0
        }
6801
        // Remove txn index kv
6802
1
        auto index_key = txn_index_key({instance_id_, txn_id});
6803
1
        txn->remove(index_key);
6804
        // Remove txn info kv
6805
1
        std::string info_key, info_val;
6806
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6807
1
        err = txn->get(info_key, &info_val);
6808
1
        if (err != TxnErrorCode::TXN_OK) {
6809
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6810
0
            return -1;
6811
0
        }
6812
1
        TxnInfoPB txn_info;
6813
1
        if (!txn_info.ParseFromString(info_val)) {
6814
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6815
0
            return -1;
6816
0
        }
6817
1
        txn->remove(info_key);
6818
        // Remove sub txn index kvs
6819
1
        std::vector<std::string> sub_txn_index_keys;
6820
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6821
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6822
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
6823
0
        }
6824
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6825
0
            txn->remove(sub_txn_index_key);
6826
0
        }
6827
        // Update txn label
6828
1
        std::string label_key, label_val;
6829
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6830
1
        err = txn->get(label_key, &label_val);
6831
1
        if (err != TxnErrorCode::TXN_OK) {
6832
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6833
0
                         << " err=" << err;
6834
0
            return -1;
6835
0
        }
6836
1
        TxnLabelPB txn_label;
6837
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6838
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6839
0
            return -1;
6840
0
        }
6841
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6842
1
        if (it != txn_label.txn_ids().end()) {
6843
1
            txn_label.mutable_txn_ids()->erase(it);
6844
1
        }
6845
1
        if (txn_label.txn_ids().empty()) {
6846
1
            txn->remove(label_key);
6847
1
            TEST_SYNC_POINT_CALLBACK(
6848
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6849
1
        } else {
6850
0
            if (!txn_label.SerializeToString(&label_val)) {
6851
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6852
0
                return -1;
6853
0
            }
6854
0
            TEST_SYNC_POINT_CALLBACK(
6855
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6856
0
            txn->atomic_set_ver_value(label_key, label_val);
6857
0
            TEST_SYNC_POINT_CALLBACK(
6858
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6859
0
        }
6860
        // Remove recycle txn kv
6861
1
        txn->remove(k);
6862
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6863
1
        err = txn->commit();
6864
1
        if (err != TxnErrorCode::TXN_OK) {
6865
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
6866
0
                TEST_SYNC_POINT_CALLBACK(
6867
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6868
                // log the txn_id and label
6869
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6870
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6871
0
                             << " txn_label=" << txn_info.label();
6872
0
                return 1;
6873
0
            }
6874
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6875
0
            return -1;
6876
0
        }
6877
1
        ++num_recycled;
6878
6879
1
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6880
1
        return 0;
6881
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6782
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6783
23.0k
        std::string_view k1 = k;
6784
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6785
23.0k
        k1.remove_prefix(1); // Remove key space
6786
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6787
23.0k
        int ret = decode_key(&k1, &out);
6788
23.0k
        if (ret != 0) {
6789
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6790
0
            return -1;
6791
0
        }
6792
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6793
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6794
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6795
23.0k
        std::unique_ptr<Transaction> txn;
6796
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6797
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6798
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6799
0
            return -1;
6800
0
        }
6801
        // Remove txn index kv
6802
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6803
23.0k
        txn->remove(index_key);
6804
        // Remove txn info kv
6805
23.0k
        std::string info_key, info_val;
6806
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6807
23.0k
        err = txn->get(info_key, &info_val);
6808
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6809
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6810
0
            return -1;
6811
0
        }
6812
23.0k
        TxnInfoPB txn_info;
6813
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6814
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6815
0
            return -1;
6816
0
        }
6817
23.0k
        txn->remove(info_key);
6818
        // Remove sub txn index kvs
6819
23.0k
        std::vector<std::string> sub_txn_index_keys;
6820
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6821
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6822
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6823
22.9k
        }
6824
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6825
22.9k
            txn->remove(sub_txn_index_key);
6826
22.9k
        }
6827
        // Update txn label
6828
23.0k
        std::string label_key, label_val;
6829
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6830
23.0k
        err = txn->get(label_key, &label_val);
6831
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6832
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6833
0
                         << " err=" << err;
6834
0
            return -1;
6835
0
        }
6836
23.0k
        TxnLabelPB txn_label;
6837
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6838
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6839
0
            return -1;
6840
0
        }
6841
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6842
23.0k
        if (it != txn_label.txn_ids().end()) {
6843
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6844
23.0k
        }
6845
23.0k
        if (txn_label.txn_ids().empty()) {
6846
23.0k
            txn->remove(label_key);
6847
23.0k
            TEST_SYNC_POINT_CALLBACK(
6848
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6849
23.0k
        } else {
6850
73
            if (!txn_label.SerializeToString(&label_val)) {
6851
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6852
0
                return -1;
6853
0
            }
6854
73
            TEST_SYNC_POINT_CALLBACK(
6855
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6856
73
            txn->atomic_set_ver_value(label_key, label_val);
6857
73
            TEST_SYNC_POINT_CALLBACK(
6858
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6859
73
        }
6860
        // Remove recycle txn kv
6861
23.0k
        txn->remove(k);
6862
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6863
23.0k
        err = txn->commit();
6864
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6865
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6866
62
                TEST_SYNC_POINT_CALLBACK(
6867
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6868
                // log the txn_id and label
6869
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6870
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6871
62
                             << " txn_label=" << txn_info.label();
6872
62
                return 1;
6873
62
            }
6874
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6875
0
            return -1;
6876
62
        }
6877
23.0k
        ++num_recycled;
6878
6879
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6880
23.0k
        return 0;
6881
23.0k
    };
6882
6883
19
    auto loop_done = [&]() -> int {
6884
10
        DORIS_CLOUD_DEFER {
6885
10
            recycle_txn_info_keys.clear();
6886
10
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6884
1
        DORIS_CLOUD_DEFER {
6885
1
            recycle_txn_info_keys.clear();
6886
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6884
9
        DORIS_CLOUD_DEFER {
6885
9
            recycle_txn_info_keys.clear();
6886
9
        };
6887
10
        TEST_SYNC_POINT_CALLBACK(
6888
10
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6889
10
                &recycle_txn_info_keys);
6890
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6891
23.0k
            concurrent_delete_executor.add([&]() {
6892
23.0k
                int ret = delete_recycle_txn_kv(k);
6893
23.0k
                if (ret == 1) {
6894
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6895
54
                    for (int i = 1; i <= max_retry; ++i) {
6896
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6897
54
                        ret = delete_recycle_txn_kv(k);
6898
                        // clang-format off
6899
54
                        TEST_SYNC_POINT_CALLBACK(
6900
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6901
                        // clang-format off
6902
54
                        if (ret != 1) {
6903
18
                            break;
6904
18
                        }
6905
                        // random sleep 0-100 ms to retry
6906
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6907
36
                    }
6908
18
                }
6909
23.0k
                if (ret != 0) {
6910
9
                    LOG_WARNING("failed to delete recycle txn kv")
6911
9
                            .tag("instance id", instance_id_)
6912
9
                            .tag("key", hex(k));
6913
9
                    return -1;
6914
9
                }
6915
23.0k
                return 0;
6916
23.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6891
1
            concurrent_delete_executor.add([&]() {
6892
1
                int ret = delete_recycle_txn_kv(k);
6893
1
                if (ret == 1) {
6894
0
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6895
0
                    for (int i = 1; i <= max_retry; ++i) {
6896
0
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6897
0
                        ret = delete_recycle_txn_kv(k);
6898
                        // clang-format off
6899
0
                        TEST_SYNC_POINT_CALLBACK(
6900
0
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6901
                        // clang-format off
6902
0
                        if (ret != 1) {
6903
0
                            break;
6904
0
                        }
6905
                        // random sleep 0-100 ms to retry
6906
0
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6907
0
                    }
6908
0
                }
6909
1
                if (ret != 0) {
6910
0
                    LOG_WARNING("failed to delete recycle txn kv")
6911
0
                            .tag("instance id", instance_id_)
6912
0
                            .tag("key", hex(k));
6913
0
                    return -1;
6914
0
                }
6915
1
                return 0;
6916
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6891
23.0k
            concurrent_delete_executor.add([&]() {
6892
23.0k
                int ret = delete_recycle_txn_kv(k);
6893
23.0k
                if (ret == 1) {
6894
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6895
54
                    for (int i = 1; i <= max_retry; ++i) {
6896
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6897
54
                        ret = delete_recycle_txn_kv(k);
6898
                        // clang-format off
6899
54
                        TEST_SYNC_POINT_CALLBACK(
6900
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6901
                        // clang-format off
6902
54
                        if (ret != 1) {
6903
18
                            break;
6904
18
                        }
6905
                        // random sleep 0-100 ms to retry
6906
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6907
36
                    }
6908
18
                }
6909
23.0k
                if (ret != 0) {
6910
9
                    LOG_WARNING("failed to delete recycle txn kv")
6911
9
                            .tag("instance id", instance_id_)
6912
9
                            .tag("key", hex(k));
6913
9
                    return -1;
6914
9
                }
6915
23.0k
                return 0;
6916
23.0k
            });
6917
23.0k
        }
6918
10
        bool finished = true;
6919
10
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6920
23.0k
        for (int r : rets) {
6921
23.0k
            if (r != 0) {
6922
9
                ret = -1;
6923
9
            }
6924
23.0k
        }
6925
6926
10
        ret = finished ? ret : -1;
6927
6928
        // Update metrics after all concurrent tasks completed
6929
10
        metrics_context.total_recycled_num = num_recycled.load();
6930
10
        metrics_context.report();
6931
6932
10
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6933
6934
10
        if (ret != 0) {
6935
3
            LOG_WARNING("recycle txn kv ret!=0")
6936
3
                    .tag("finished", finished)
6937
3
                    .tag("ret", ret)
6938
3
                    .tag("instance_id", instance_id_);
6939
3
            return ret;
6940
3
        }
6941
7
        return ret;
6942
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6883
1
    auto loop_done = [&]() -> int {
6884
1
        DORIS_CLOUD_DEFER {
6885
1
            recycle_txn_info_keys.clear();
6886
1
        };
6887
1
        TEST_SYNC_POINT_CALLBACK(
6888
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6889
1
                &recycle_txn_info_keys);
6890
1
        for (const auto& k : recycle_txn_info_keys) {
6891
1
            concurrent_delete_executor.add([&]() {
6892
1
                int ret = delete_recycle_txn_kv(k);
6893
1
                if (ret == 1) {
6894
1
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6895
1
                    for (int i = 1; i <= max_retry; ++i) {
6896
1
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6897
1
                        ret = delete_recycle_txn_kv(k);
6898
                        // clang-format off
6899
1
                        TEST_SYNC_POINT_CALLBACK(
6900
1
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6901
                        // clang-format off
6902
1
                        if (ret != 1) {
6903
1
                            break;
6904
1
                        }
6905
                        // random sleep 0-100 ms to retry
6906
1
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6907
1
                    }
6908
1
                }
6909
1
                if (ret != 0) {
6910
1
                    LOG_WARNING("failed to delete recycle txn kv")
6911
1
                            .tag("instance id", instance_id_)
6912
1
                            .tag("key", hex(k));
6913
1
                    return -1;
6914
1
                }
6915
1
                return 0;
6916
1
            });
6917
1
        }
6918
1
        bool finished = true;
6919
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6920
1
        for (int r : rets) {
6921
1
            if (r != 0) {
6922
0
                ret = -1;
6923
0
            }
6924
1
        }
6925
6926
1
        ret = finished ? ret : -1;
6927
6928
        // Update metrics after all concurrent tasks completed
6929
1
        metrics_context.total_recycled_num = num_recycled.load();
6930
1
        metrics_context.report();
6931
6932
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6933
6934
1
        if (ret != 0) {
6935
0
            LOG_WARNING("recycle txn kv ret!=0")
6936
0
                    .tag("finished", finished)
6937
0
                    .tag("ret", ret)
6938
0
                    .tag("instance_id", instance_id_);
6939
0
            return ret;
6940
0
        }
6941
1
        return ret;
6942
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6883
9
    auto loop_done = [&]() -> int {
6884
9
        DORIS_CLOUD_DEFER {
6885
9
            recycle_txn_info_keys.clear();
6886
9
        };
6887
9
        TEST_SYNC_POINT_CALLBACK(
6888
9
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6889
9
                &recycle_txn_info_keys);
6890
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6891
23.0k
            concurrent_delete_executor.add([&]() {
6892
23.0k
                int ret = delete_recycle_txn_kv(k);
6893
23.0k
                if (ret == 1) {
6894
23.0k
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6895
23.0k
                    for (int i = 1; i <= max_retry; ++i) {
6896
23.0k
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6897
23.0k
                        ret = delete_recycle_txn_kv(k);
6898
                        // clang-format off
6899
23.0k
                        TEST_SYNC_POINT_CALLBACK(
6900
23.0k
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6901
                        // clang-format off
6902
23.0k
                        if (ret != 1) {
6903
23.0k
                            break;
6904
23.0k
                        }
6905
                        // random sleep 0-100 ms to retry
6906
23.0k
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6907
23.0k
                    }
6908
23.0k
                }
6909
23.0k
                if (ret != 0) {
6910
23.0k
                    LOG_WARNING("failed to delete recycle txn kv")
6911
23.0k
                            .tag("instance id", instance_id_)
6912
23.0k
                            .tag("key", hex(k));
6913
23.0k
                    return -1;
6914
23.0k
                }
6915
23.0k
                return 0;
6916
23.0k
            });
6917
23.0k
        }
6918
9
        bool finished = true;
6919
9
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6920
23.0k
        for (int r : rets) {
6921
23.0k
            if (r != 0) {
6922
9
                ret = -1;
6923
9
            }
6924
23.0k
        }
6925
6926
9
        ret = finished ? ret : -1;
6927
6928
        // Update metrics after all concurrent tasks completed
6929
9
        metrics_context.total_recycled_num = num_recycled.load();
6930
9
        metrics_context.report();
6931
6932
9
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6933
6934
9
        if (ret != 0) {
6935
3
            LOG_WARNING("recycle txn kv ret!=0")
6936
3
                    .tag("finished", finished)
6937
3
                    .tag("ret", ret)
6938
3
                    .tag("instance_id", instance_id_);
6939
3
            return ret;
6940
3
        }
6941
6
        return ret;
6942
9
    };
6943
6944
19
    if (config::enable_recycler_stats_metrics) {
6945
0
        scan_and_statistics_expired_txn_label();
6946
0
    }
6947
    // recycle_func and loop_done for scan and recycle
6948
19
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
6949
19
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
6950
19
}
6951
6952
struct CopyJobIdTuple {
6953
    std::string instance_id;
6954
    std::string stage_id;
6955
    long table_id;
6956
    std::string copy_id;
6957
    std::string stage_path;
6958
};
6959
struct BatchObjStoreAccessor {
6960
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
6961
                          TxnKv* txn_kv)
6962
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
6963
3
    ~BatchObjStoreAccessor() {
6964
3
        if (!paths_.empty()) {
6965
3
            consume();
6966
3
        }
6967
3
    }
6968
6969
    /**
6970
    * To implicitely do batch work and submit the batch delete task to s3
6971
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
6972
    *
6973
    * @param copy_job The protubuf struct consists of the copy job files.
6974
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
6975
    *            it would last until we finish the delete task, here we need pass one string value
6976
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
6977
    */
6978
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
6979
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
6980
5
        auto& file_keys = copy_file_keys_[key];
6981
5
        file_keys.log_trace =
6982
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
6983
5
                            instance_id, stage_id, table_id, copy_id, path);
6984
5
        std::string_view log_trace = file_keys.log_trace;
6985
2.03k
        for (const auto& file : copy_job.object_files()) {
6986
2.03k
            auto relative_path = file.relative_path();
6987
2.03k
            paths_.push_back(relative_path);
6988
2.03k
            file_keys.keys.push_back(copy_file_key(
6989
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
6990
2.03k
            LOG_INFO(log_trace)
6991
2.03k
                    .tag("relative_path", relative_path)
6992
2.03k
                    .tag("batch_count", batch_count_);
6993
2.03k
        }
6994
5
        LOG_INFO(log_trace)
6995
5
                .tag("objects_num", copy_job.object_files().size())
6996
5
                .tag("batch_count", batch_count_);
6997
        // 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
6998
        // recommend using delete objects when objects num is less than 10)
6999
5
        if (paths_.size() < 1000) {
7000
3
            return;
7001
3
        }
7002
2
        consume();
7003
2
    }
7004
7005
private:
7006
5
    void consume() {
7007
5
        DORIS_CLOUD_DEFER {
7008
5
            paths_.clear();
7009
5
            copy_file_keys_.clear();
7010
5
            batch_count_++;
7011
7012
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
7013
5
                        batch_count_);
7014
5
        };
7015
7016
5
        StopWatch sw;
7017
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
7018
5
        if (0 != accessor_->delete_files(paths_)) {
7019
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
7020
2
                        paths_.size(), batch_count_, sw.elapsed_us());
7021
2
            return;
7022
2
        }
7023
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
7024
3
                    paths_.size(), batch_count_, sw.elapsed_us());
7025
        // delete fdb's keys
7026
3
        for (auto& file_keys : copy_file_keys_) {
7027
3
            auto& [log_trace, keys] = file_keys.second;
7028
3
            std::unique_ptr<Transaction> txn;
7029
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
7030
0
                LOG(WARNING) << "failed to create txn";
7031
0
                continue;
7032
0
            }
7033
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7034
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7035
            // limited, should not cause the txn commit failed.
7036
1.02k
            for (const auto& key : keys) {
7037
1.02k
                txn->remove(key);
7038
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
7039
1.02k
            }
7040
3
            txn->remove(file_keys.first);
7041
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
7042
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
7043
0
                continue;
7044
0
            }
7045
3
        }
7046
3
    }
7047
    std::shared_ptr<StorageVaultAccessor> accessor_;
7048
    // the path of the s3 files to be deleted
7049
    std::vector<std::string> paths_;
7050
    struct CopyFiles {
7051
        std::string log_trace;
7052
        std::vector<std::string> keys;
7053
    };
7054
    // pair<std::string, std::vector<std::string>>
7055
    // first: instance_id_ stage_id table_id query_id
7056
    // second: keys to be deleted
7057
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
7058
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
7059
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
7060
    // which can together uniquely identifies different tasks for tracing log
7061
    uint64_t& batch_count_;
7062
    TxnKv* txn_kv_;
7063
};
7064
7065
13
int InstanceRecycler::recycle_copy_jobs() {
7066
13
    int64_t num_scanned = 0;
7067
13
    int64_t num_finished = 0;
7068
13
    int64_t num_expired = 0;
7069
13
    int64_t num_recycled = 0;
7070
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
7071
13
    uint64_t batch_count = 0;
7072
13
    const std::string task_name = "recycle_copy_jobs";
7073
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7074
7075
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
7076
7077
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7078
13
    register_recycle_task(task_name, start_time);
7079
7080
13
    DORIS_CLOUD_DEFER {
7081
13
        unregister_recycle_task(task_name);
7082
13
        int64_t cost =
7083
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7084
13
        metrics_context.finish_report();
7085
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7086
13
                .tag("instance_id", instance_id_)
7087
13
                .tag("num_scanned", num_scanned)
7088
13
                .tag("num_finished", num_finished)
7089
13
                .tag("num_expired", num_expired)
7090
13
                .tag("num_recycled", num_recycled);
7091
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
7080
13
    DORIS_CLOUD_DEFER {
7081
13
        unregister_recycle_task(task_name);
7082
13
        int64_t cost =
7083
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7084
13
        metrics_context.finish_report();
7085
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7086
13
                .tag("instance_id", instance_id_)
7087
13
                .tag("num_scanned", num_scanned)
7088
13
                .tag("num_finished", num_finished)
7089
13
                .tag("num_expired", num_expired)
7090
13
                .tag("num_recycled", num_recycled);
7091
13
    };
7092
7093
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7094
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7095
13
    std::string key0;
7096
13
    std::string key1;
7097
13
    copy_job_key(key_info0, &key0);
7098
13
    copy_job_key(key_info1, &key1);
7099
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
7100
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
7101
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
7102
16
                         this](std::string_view k, std::string_view v) -> int {
7103
16
        ++num_scanned;
7104
16
        CopyJobPB copy_job;
7105
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7106
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7107
0
            return -1;
7108
0
        }
7109
7110
        // decode copy job key
7111
16
        auto k1 = k;
7112
16
        k1.remove_prefix(1);
7113
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7114
16
        decode_key(&k1, &out);
7115
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7116
        // -> CopyJobPB
7117
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7118
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7119
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7120
7121
16
        bool check_storage = true;
7122
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7123
12
            ++num_finished;
7124
7125
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7126
7
                auto it = stage_accessor_map.find(stage_id);
7127
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7128
7
                std::string_view path;
7129
7
                if (it != stage_accessor_map.end()) {
7130
2
                    accessor = it->second;
7131
5
                } else {
7132
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7133
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7134
5
                                                      &inner_accessor);
7135
5
                    if (ret < 0) { // error
7136
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7137
0
                        return -1;
7138
5
                    } else if (ret == 0) {
7139
3
                        path = inner_accessor->uri();
7140
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7141
3
                                inner_accessor, batch_count, txn_kv_.get());
7142
3
                        stage_accessor_map.emplace(stage_id, accessor);
7143
3
                    } else { // stage not found, skip check storage
7144
2
                        check_storage = false;
7145
2
                    }
7146
5
                }
7147
7
                if (check_storage) {
7148
                    // TODO delete objects with key and etag is not supported
7149
5
                    accessor->add(std::move(copy_job), std::string(k),
7150
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7151
5
                    return 0;
7152
5
                }
7153
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7154
5
                int64_t current_time =
7155
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7156
5
                if (copy_job.finish_time_ms() > 0) {
7157
2
                    if (!config::force_immediate_recycle &&
7158
2
                        current_time < copy_job.finish_time_ms() +
7159
2
                                               config::copy_job_max_retention_second * 1000) {
7160
1
                        return 0;
7161
1
                    }
7162
3
                } else {
7163
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7164
3
                    if (!config::force_immediate_recycle &&
7165
3
                        current_time < copy_job.start_time_ms() +
7166
3
                                               config::copy_job_max_retention_second * 1000) {
7167
1
                        return 0;
7168
1
                    }
7169
3
                }
7170
5
            }
7171
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7172
4
            int64_t current_time =
7173
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7174
            // if copy job is timeout: delete all copy file kvs and copy job kv
7175
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7176
2
                return 0;
7177
2
            }
7178
2
            ++num_expired;
7179
2
        }
7180
7181
        // delete all copy files
7182
7
        std::vector<std::string> copy_file_keys;
7183
70
        for (auto& file : copy_job.object_files()) {
7184
70
            copy_file_keys.push_back(copy_file_key(
7185
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7186
70
        }
7187
7
        std::unique_ptr<Transaction> txn;
7188
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7189
0
            LOG(WARNING) << "failed to create txn";
7190
0
            return -1;
7191
0
        }
7192
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7193
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7194
        // limited, should not cause the txn commit failed.
7195
70
        for (const auto& key : copy_file_keys) {
7196
70
            txn->remove(key);
7197
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7198
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7199
70
                      << ", query_id=" << copy_id;
7200
70
        }
7201
7
        txn->remove(k);
7202
7
        TxnErrorCode err = txn->commit();
7203
7
        if (err != TxnErrorCode::TXN_OK) {
7204
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7205
0
            return -1;
7206
0
        }
7207
7208
7
        metrics_context.total_recycled_num = ++num_recycled;
7209
7
        metrics_context.report();
7210
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7211
7
        return 0;
7212
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
7102
16
                         this](std::string_view k, std::string_view v) -> int {
7103
16
        ++num_scanned;
7104
16
        CopyJobPB copy_job;
7105
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7106
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7107
0
            return -1;
7108
0
        }
7109
7110
        // decode copy job key
7111
16
        auto k1 = k;
7112
16
        k1.remove_prefix(1);
7113
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7114
16
        decode_key(&k1, &out);
7115
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7116
        // -> CopyJobPB
7117
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7118
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7119
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7120
7121
16
        bool check_storage = true;
7122
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7123
12
            ++num_finished;
7124
7125
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7126
7
                auto it = stage_accessor_map.find(stage_id);
7127
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7128
7
                std::string_view path;
7129
7
                if (it != stage_accessor_map.end()) {
7130
2
                    accessor = it->second;
7131
5
                } else {
7132
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7133
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7134
5
                                                      &inner_accessor);
7135
5
                    if (ret < 0) { // error
7136
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7137
0
                        return -1;
7138
5
                    } else if (ret == 0) {
7139
3
                        path = inner_accessor->uri();
7140
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7141
3
                                inner_accessor, batch_count, txn_kv_.get());
7142
3
                        stage_accessor_map.emplace(stage_id, accessor);
7143
3
                    } else { // stage not found, skip check storage
7144
2
                        check_storage = false;
7145
2
                    }
7146
5
                }
7147
7
                if (check_storage) {
7148
                    // TODO delete objects with key and etag is not supported
7149
5
                    accessor->add(std::move(copy_job), std::string(k),
7150
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7151
5
                    return 0;
7152
5
                }
7153
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7154
5
                int64_t current_time =
7155
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7156
5
                if (copy_job.finish_time_ms() > 0) {
7157
2
                    if (!config::force_immediate_recycle &&
7158
2
                        current_time < copy_job.finish_time_ms() +
7159
2
                                               config::copy_job_max_retention_second * 1000) {
7160
1
                        return 0;
7161
1
                    }
7162
3
                } else {
7163
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7164
3
                    if (!config::force_immediate_recycle &&
7165
3
                        current_time < copy_job.start_time_ms() +
7166
3
                                               config::copy_job_max_retention_second * 1000) {
7167
1
                        return 0;
7168
1
                    }
7169
3
                }
7170
5
            }
7171
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7172
4
            int64_t current_time =
7173
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7174
            // if copy job is timeout: delete all copy file kvs and copy job kv
7175
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7176
2
                return 0;
7177
2
            }
7178
2
            ++num_expired;
7179
2
        }
7180
7181
        // delete all copy files
7182
7
        std::vector<std::string> copy_file_keys;
7183
70
        for (auto& file : copy_job.object_files()) {
7184
70
            copy_file_keys.push_back(copy_file_key(
7185
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7186
70
        }
7187
7
        std::unique_ptr<Transaction> txn;
7188
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7189
0
            LOG(WARNING) << "failed to create txn";
7190
0
            return -1;
7191
0
        }
7192
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7193
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7194
        // limited, should not cause the txn commit failed.
7195
70
        for (const auto& key : copy_file_keys) {
7196
70
            txn->remove(key);
7197
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7198
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7199
70
                      << ", query_id=" << copy_id;
7200
70
        }
7201
7
        txn->remove(k);
7202
7
        TxnErrorCode err = txn->commit();
7203
7
        if (err != TxnErrorCode::TXN_OK) {
7204
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7205
0
            return -1;
7206
0
        }
7207
7208
7
        metrics_context.total_recycled_num = ++num_recycled;
7209
7
        metrics_context.report();
7210
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7211
7
        return 0;
7212
7
    };
7213
7214
13
    if (config::enable_recycler_stats_metrics) {
7215
0
        scan_and_statistics_copy_jobs();
7216
0
    }
7217
    // recycle_func and loop_done for scan and recycle
7218
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
7219
13
}
7220
7221
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
7222
                                             const StagePB::StageType& stage_type,
7223
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
7224
5
#ifdef UNIT_TEST
7225
    // In unit test, external use the same accessor as the internal stage
7226
5
    auto it = accessor_map_.find(stage_id);
7227
5
    if (it != accessor_map_.end()) {
7228
3
        *accessor = it->second;
7229
3
    } else {
7230
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
7231
2
        return 1;
7232
2
    }
7233
#else
7234
    // init s3 accessor and add to accessor map
7235
    auto stage_it =
7236
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
7237
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
7238
7239
    if (stage_it == instance_info_.stages().end()) {
7240
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
7241
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
7242
        return 1;
7243
    }
7244
7245
    const auto& object_store_info = stage_it->obj_info();
7246
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
7247
7248
    S3Conf s3_conf;
7249
    if (stage_type == StagePB::EXTERNAL) {
7250
        if (stage_access_type == StagePB::AKSK) {
7251
            auto conf = S3Conf::from_obj_store_info(object_store_info);
7252
            if (!conf) {
7253
                return -1;
7254
            }
7255
7256
            s3_conf = std::move(*conf);
7257
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
7258
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
7259
            if (!conf) {
7260
                return -1;
7261
            }
7262
7263
            s3_conf = std::move(*conf);
7264
            if (instance_info_.ram_user().has_encryption_info()) {
7265
                AkSkPair plain_ak_sk_pair;
7266
                int ret = decrypt_ak_sk_helper(
7267
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
7268
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
7269
                if (ret != 0) {
7270
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
7271
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
7272
                    return -1;
7273
                }
7274
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
7275
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
7276
            } else {
7277
                s3_conf.ak = instance_info_.ram_user().ak();
7278
                s3_conf.sk = instance_info_.ram_user().sk();
7279
            }
7280
        } else {
7281
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
7282
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
7283
            return -1;
7284
        }
7285
    } else if (stage_type == StagePB::INTERNAL) {
7286
        int idx = stoi(object_store_info.id());
7287
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7288
            LOG(WARNING) << "invalid idx: " << idx;
7289
            return -1;
7290
        }
7291
7292
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7293
        auto conf = S3Conf::from_obj_store_info(old_obj);
7294
        if (!conf) {
7295
            return -1;
7296
        }
7297
7298
        s3_conf = std::move(*conf);
7299
        s3_conf.prefix = object_store_info.prefix();
7300
    } else {
7301
        LOG(WARNING) << "unknown stage type " << stage_type;
7302
        return -1;
7303
    }
7304
7305
    std::shared_ptr<S3Accessor> s3_accessor;
7306
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
7307
    if (ret != 0) {
7308
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
7309
        return -1;
7310
    }
7311
7312
    *accessor = std::move(s3_accessor);
7313
#endif
7314
3
    return 0;
7315
5
}
7316
7317
11
int InstanceRecycler::recycle_stage() {
7318
11
    int64_t num_scanned = 0;
7319
11
    int64_t num_recycled = 0;
7320
11
    const std::string task_name = "recycle_stage";
7321
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7322
7323
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
7324
7325
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7326
11
    register_recycle_task(task_name, start_time);
7327
7328
11
    DORIS_CLOUD_DEFER {
7329
11
        unregister_recycle_task(task_name);
7330
11
        int64_t cost =
7331
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7332
11
        metrics_context.finish_report();
7333
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7334
11
                .tag("instance_id", instance_id_)
7335
11
                .tag("num_scanned", num_scanned)
7336
11
                .tag("num_recycled", num_recycled);
7337
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
7328
11
    DORIS_CLOUD_DEFER {
7329
11
        unregister_recycle_task(task_name);
7330
11
        int64_t cost =
7331
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7332
11
        metrics_context.finish_report();
7333
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7334
11
                .tag("instance_id", instance_id_)
7335
11
                .tag("num_scanned", num_scanned)
7336
11
                .tag("num_recycled", num_recycled);
7337
11
    };
7338
7339
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7340
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7341
11
    std::string key0 = recycle_stage_key(key_info0);
7342
11
    std::string key1 = recycle_stage_key(key_info1);
7343
7344
11
    std::vector<std::string_view> stage_keys;
7345
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
7346
11
                         this](std::string_view k, std::string_view v) -> int {
7347
1
        ++num_scanned;
7348
1
        RecycleStagePB recycle_stage;
7349
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7350
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7351
0
            return -1;
7352
0
        }
7353
7354
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7355
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7356
0
            LOG(WARNING) << "invalid idx: " << idx;
7357
0
            return -1;
7358
0
        }
7359
7360
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7361
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7362
1
                [&] {
7363
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7364
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7365
1
                    if (!s3_conf) {
7366
1
                        return -1;
7367
1
                    }
7368
7369
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7370
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7371
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7372
1
                    if (ret != 0) {
7373
1
                        return -1;
7374
1
                    }
7375
7376
1
                    accessor = std::move(s3_accessor);
7377
1
                    return 0;
7378
1
                }(),
7379
1
                "recycle_stage:get_accessor", &accessor);
7380
7381
1
        if (ret != 0) {
7382
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7383
0
            return ret;
7384
0
        }
7385
7386
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7387
1
                .tag("instance_id", instance_id_)
7388
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7389
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7390
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7391
1
                .tag("obj_info_id", idx)
7392
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7393
1
        ret = accessor->delete_all();
7394
1
        if (ret != 0) {
7395
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7396
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7397
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7398
0
                         << ", ret=" << ret;
7399
0
            return -1;
7400
0
        }
7401
1
        metrics_context.total_recycled_num = ++num_recycled;
7402
1
        metrics_context.report();
7403
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7404
1
        stage_keys.push_back(k);
7405
1
        return 0;
7406
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7346
1
                         this](std::string_view k, std::string_view v) -> int {
7347
1
        ++num_scanned;
7348
1
        RecycleStagePB recycle_stage;
7349
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7350
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7351
0
            return -1;
7352
0
        }
7353
7354
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7355
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7356
0
            LOG(WARNING) << "invalid idx: " << idx;
7357
0
            return -1;
7358
0
        }
7359
7360
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7361
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7362
1
                [&] {
7363
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7364
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7365
1
                    if (!s3_conf) {
7366
1
                        return -1;
7367
1
                    }
7368
7369
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7370
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7371
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7372
1
                    if (ret != 0) {
7373
1
                        return -1;
7374
1
                    }
7375
7376
1
                    accessor = std::move(s3_accessor);
7377
1
                    return 0;
7378
1
                }(),
7379
1
                "recycle_stage:get_accessor", &accessor);
7380
7381
1
        if (ret != 0) {
7382
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7383
0
            return ret;
7384
0
        }
7385
7386
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7387
1
                .tag("instance_id", instance_id_)
7388
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7389
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7390
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7391
1
                .tag("obj_info_id", idx)
7392
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7393
1
        ret = accessor->delete_all();
7394
1
        if (ret != 0) {
7395
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7396
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7397
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7398
0
                         << ", ret=" << ret;
7399
0
            return -1;
7400
0
        }
7401
1
        metrics_context.total_recycled_num = ++num_recycled;
7402
1
        metrics_context.report();
7403
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7404
1
        stage_keys.push_back(k);
7405
1
        return 0;
7406
1
    };
7407
7408
11
    auto loop_done = [&stage_keys, this]() -> int {
7409
1
        if (stage_keys.empty()) return 0;
7410
1
        DORIS_CLOUD_DEFER {
7411
1
            stage_keys.clear();
7412
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
7410
1
        DORIS_CLOUD_DEFER {
7411
1
            stage_keys.clear();
7412
1
        };
7413
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7414
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7415
0
            return -1;
7416
0
        }
7417
1
        return 0;
7418
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
7408
1
    auto loop_done = [&stage_keys, this]() -> int {
7409
1
        if (stage_keys.empty()) return 0;
7410
1
        DORIS_CLOUD_DEFER {
7411
1
            stage_keys.clear();
7412
1
        };
7413
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7414
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7415
0
            return -1;
7416
0
        }
7417
1
        return 0;
7418
1
    };
7419
11
    if (config::enable_recycler_stats_metrics) {
7420
0
        scan_and_statistics_stage();
7421
0
    }
7422
    // recycle_func and loop_done for scan and recycle
7423
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
7424
11
}
7425
7426
10
int InstanceRecycler::recycle_expired_stage_objects() {
7427
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
7428
7429
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7430
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7431
7432
10
    DORIS_CLOUD_DEFER {
7433
10
        int64_t cost =
7434
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7435
10
        metrics_context.finish_report();
7436
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7437
10
                .tag("instance_id", instance_id_);
7438
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
7432
10
    DORIS_CLOUD_DEFER {
7433
10
        int64_t cost =
7434
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7435
10
        metrics_context.finish_report();
7436
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7437
10
                .tag("instance_id", instance_id_);
7438
10
    };
7439
7440
10
    int ret = 0;
7441
7442
10
    if (config::enable_recycler_stats_metrics) {
7443
0
        scan_and_statistics_expired_stage_objects();
7444
0
    }
7445
7446
10
    for (const auto& stage : instance_info_.stages()) {
7447
0
        std::stringstream ss;
7448
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
7449
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
7450
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
7451
0
           << ", prefix=" << stage.obj_info().prefix();
7452
7453
0
        if (stopped()) {
7454
0
            break;
7455
0
        }
7456
0
        if (stage.type() == StagePB::EXTERNAL) {
7457
0
            continue;
7458
0
        }
7459
0
        int idx = stoi(stage.obj_info().id());
7460
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7461
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
7462
0
            continue;
7463
0
        }
7464
7465
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7466
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7467
0
        if (!s3_conf) {
7468
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
7469
0
            continue;
7470
0
        }
7471
7472
0
        s3_conf->prefix = stage.obj_info().prefix();
7473
0
        std::shared_ptr<S3Accessor> accessor;
7474
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
7475
0
        if (ret1 != 0) {
7476
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
7477
0
            ret = -1;
7478
0
            continue;
7479
0
        }
7480
7481
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7482
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
7483
0
            ret = -1;
7484
0
            continue;
7485
0
        }
7486
7487
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
7488
0
        int64_t expiration_time =
7489
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
7490
0
                config::internal_stage_objects_expire_time_second;
7491
0
        if (config::force_immediate_recycle) {
7492
0
            expiration_time = INT64_MAX;
7493
0
        }
7494
0
        ret1 = accessor->delete_all(expiration_time);
7495
0
        if (ret1 != 0) {
7496
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
7497
0
                         << ss.str();
7498
0
            ret = -1;
7499
0
            continue;
7500
0
        }
7501
0
        metrics_context.total_recycled_num++;
7502
0
        metrics_context.report();
7503
0
    }
7504
10
    return ret;
7505
10
}
7506
7507
234
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
7508
234
    std::lock_guard lock(recycle_tasks_mutex);
7509
234
    running_recycle_tasks[task_name] = start_time;
7510
234
}
7511
7512
235
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
7513
235
    std::lock_guard lock(recycle_tasks_mutex);
7514
235
    DCHECK(running_recycle_tasks[task_name] > 0);
7515
235
    running_recycle_tasks.erase(task_name);
7516
235
}
7517
7518
3
bool InstanceRecycler::check_recycle_tasks() {
7519
3
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
7520
3
    {
7521
3
        std::lock_guard lock(recycle_tasks_mutex);
7522
3
        tmp_running_recycle_tasks = running_recycle_tasks;
7523
3
    }
7524
7525
3
    bool found = false;
7526
3
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7527
3
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
7528
2
        int64_t cost = now - start_time;
7529
2
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
7530
2
            LOG_INFO("recycle task cost too much time cost={}s", cost)
7531
2
                    .tag("instance_id", instance_id_)
7532
2
                    .tag("task", task_name);
7533
2
            found = true;
7534
2
        }
7535
2
    }
7536
7537
3
    return found;
7538
3
}
7539
7540
// Scan and statistics indexes that need to be recycled
7541
1
int InstanceRecycler::scan_and_statistics_indexes() {
7542
1
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
7543
1
    RecyclerMetricsContext stream_metrics_context(instance_id_, "recycle_stream");
7544
7545
1
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
7546
1
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
7547
1
    std::string index_key0;
7548
1
    std::string index_key1;
7549
1
    recycle_index_key(index_key_info0, &index_key0);
7550
1
    recycle_index_key(index_key_info1, &index_key1);
7551
1
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7552
7553
1
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7554
1
        RecycleIndexPB index_pb;
7555
1
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7556
0
            return 0;
7557
0
        }
7558
1
        int64_t current_time = ::time(nullptr);
7559
1
        if (current_time <
7560
1
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7561
0
            return 0;
7562
0
        }
7563
        // decode index_id
7564
1
        auto k1 = k;
7565
1
        k1.remove_prefix(1);
7566
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7567
1
        decode_key(&k1, &out);
7568
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7569
1
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7570
1
        std::unique_ptr<Transaction> txn;
7571
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7572
1
        if (err != TxnErrorCode::TXN_OK) {
7573
0
            return 0;
7574
0
        }
7575
1
        std::string val;
7576
1
        err = txn->get(k, &val);
7577
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7578
0
            return 0;
7579
0
        }
7580
1
        if (err != TxnErrorCode::TXN_OK) {
7581
0
            return 0;
7582
0
        }
7583
1
        index_pb.Clear();
7584
1
        if (!index_pb.ParseFromString(val)) {
7585
0
            return 0;
7586
0
        }
7587
1
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
7588
1
            if (!index_pb.has_db_id() || !index_pb.has_stream_db_id()) {
7589
0
                LOG_WARNING("table stream recycle index is missing binding")
7590
0
                        .tag("instance_id", instance_id_)
7591
0
                        .tag("stream_id", index_id);
7592
0
                return 0;
7593
0
            }
7594
2
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7595
2
                std::string end = prefix;
7596
2
                end.push_back('\xff');
7597
2
                auto count_offset = [&stream_metrics_context](std::string_view key,
7598
6
                                                              std::string_view value) {
7599
6
                    stream_metrics_context.total_need_recycle_num++;
7600
6
                    stream_metrics_context.total_need_recycle_data_size +=
7601
6
                            key.size() + value.size();
7602
6
                    return 0;
7603
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
7598
6
                                                              std::string_view value) {
7599
6
                    stream_metrics_context.total_need_recycle_num++;
7600
6
                    stream_metrics_context.total_need_recycle_data_size +=
7601
6
                            key.size() + value.size();
7602
6
                    return 0;
7603
6
                };
7604
2
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7605
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
7594
2
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7595
2
                std::string end = prefix;
7596
2
                end.push_back('\xff');
7597
2
                auto count_offset = [&stream_metrics_context](std::string_view key,
7598
2
                                                              std::string_view value) {
7599
2
                    stream_metrics_context.total_need_recycle_num++;
7600
2
                    stream_metrics_context.total_need_recycle_data_size +=
7601
2
                            key.size() + value.size();
7602
2
                    return 0;
7603
2
                };
7604
2
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7605
2
            };
7606
1
            const std::string latest_prefix = table_stream_offset_key_prefix(
7607
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7608
1
                    index_id);
7609
1
            const std::string versioned_prefix = versioned::table_stream_offset_key_prefix(
7610
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7611
1
                    index_id);
7612
1
            if (scan_offset_prefix(latest_prefix) != 0 ||
7613
1
                scan_offset_prefix(versioned_prefix) != 0) {
7614
0
                LOG_WARNING("failed to scan table stream offsets for recycle statistics")
7615
0
                        .tag("instance_id", instance_id_)
7616
0
                        .tag("stream_id", index_id);
7617
0
            }
7618
1
            return 0;
7619
1
        }
7620
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7621
0
            return 0;
7622
0
        }
7623
0
        metrics_context.total_need_recycle_num++;
7624
0
        return 0;
7625
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
7553
1
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7554
1
        RecycleIndexPB index_pb;
7555
1
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7556
0
            return 0;
7557
0
        }
7558
1
        int64_t current_time = ::time(nullptr);
7559
1
        if (current_time <
7560
1
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7561
0
            return 0;
7562
0
        }
7563
        // decode index_id
7564
1
        auto k1 = k;
7565
1
        k1.remove_prefix(1);
7566
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7567
1
        decode_key(&k1, &out);
7568
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7569
1
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7570
1
        std::unique_ptr<Transaction> txn;
7571
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7572
1
        if (err != TxnErrorCode::TXN_OK) {
7573
0
            return 0;
7574
0
        }
7575
1
        std::string val;
7576
1
        err = txn->get(k, &val);
7577
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7578
0
            return 0;
7579
0
        }
7580
1
        if (err != TxnErrorCode::TXN_OK) {
7581
0
            return 0;
7582
0
        }
7583
1
        index_pb.Clear();
7584
1
        if (!index_pb.ParseFromString(val)) {
7585
0
            return 0;
7586
0
        }
7587
1
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
7588
1
            if (!index_pb.has_db_id() || !index_pb.has_stream_db_id()) {
7589
0
                LOG_WARNING("table stream recycle index is missing binding")
7590
0
                        .tag("instance_id", instance_id_)
7591
0
                        .tag("stream_id", index_id);
7592
0
                return 0;
7593
0
            }
7594
1
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7595
1
                std::string end = prefix;
7596
1
                end.push_back('\xff');
7597
1
                auto count_offset = [&stream_metrics_context](std::string_view key,
7598
1
                                                              std::string_view value) {
7599
1
                    stream_metrics_context.total_need_recycle_num++;
7600
1
                    stream_metrics_context.total_need_recycle_data_size +=
7601
1
                            key.size() + value.size();
7602
1
                    return 0;
7603
1
                };
7604
1
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7605
1
            };
7606
1
            const std::string latest_prefix = table_stream_offset_key_prefix(
7607
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7608
1
                    index_id);
7609
1
            const std::string versioned_prefix = versioned::table_stream_offset_key_prefix(
7610
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7611
1
                    index_id);
7612
1
            if (scan_offset_prefix(latest_prefix) != 0 ||
7613
1
                scan_offset_prefix(versioned_prefix) != 0) {
7614
0
                LOG_WARNING("failed to scan table stream offsets for recycle statistics")
7615
0
                        .tag("instance_id", instance_id_)
7616
0
                        .tag("stream_id", index_id);
7617
0
            }
7618
1
            return 0;
7619
1
        }
7620
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7621
0
            return 0;
7622
0
        }
7623
0
        metrics_context.total_need_recycle_num++;
7624
0
        return 0;
7625
0
    };
7626
7627
1
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
7628
1
    metrics_context.report(true);
7629
1
    stream_metrics_context.report(true);
7630
1
    segment_metrics_context_.report(true);
7631
1
    tablet_metrics_context_.report(true);
7632
1
    return ret;
7633
1
}
7634
7635
// Scan and statistics partitions that need to be recycled
7636
0
int InstanceRecycler::scan_and_statistics_partitions() {
7637
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
7638
7639
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
7640
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
7641
0
    std::string part_key0;
7642
0
    std::string part_key1;
7643
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7644
7645
0
    recycle_partition_key(part_key_info0, &part_key0);
7646
0
    recycle_partition_key(part_key_info1, &part_key1);
7647
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
7648
0
        RecyclePartitionPB part_pb;
7649
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
7650
0
            return 0;
7651
0
        }
7652
0
        int64_t current_time = ::time(nullptr);
7653
0
        if (current_time <
7654
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
7655
0
            return 0;
7656
0
        }
7657
        // decode partition_id
7658
0
        auto k1 = k;
7659
0
        k1.remove_prefix(1);
7660
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7661
0
        decode_key(&k1, &out);
7662
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
7663
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
7664
        // Change state to RECYCLING
7665
0
        std::unique_ptr<Transaction> txn;
7666
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7667
0
        if (err != TxnErrorCode::TXN_OK) {
7668
0
            return 0;
7669
0
        }
7670
0
        std::string val;
7671
0
        err = txn->get(k, &val);
7672
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7673
0
            return 0;
7674
0
        }
7675
0
        if (err != TxnErrorCode::TXN_OK) {
7676
0
            return 0;
7677
0
        }
7678
0
        part_pb.Clear();
7679
0
        if (!part_pb.ParseFromString(val)) {
7680
0
            return 0;
7681
0
        }
7682
        // Partitions with PREPARED state MUST have no data
7683
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
7684
0
        int ret = 0;
7685
0
        for (int64_t index_id : part_pb.index_id()) {
7686
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
7687
0
                                            partition_id, is_empty_tablet) != 0) {
7688
0
                ret = 0;
7689
0
            }
7690
0
        }
7691
0
        metrics_context.total_need_recycle_num++;
7692
0
        return ret;
7693
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_
7694
7695
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
7696
0
    metrics_context.report(true);
7697
0
    segment_metrics_context_.report(true);
7698
0
    tablet_metrics_context_.report(true);
7699
0
    return ret;
7700
0
}
7701
7702
// Scan and statistics rowsets that need to be recycled
7703
0
int InstanceRecycler::scan_and_statistics_rowsets() {
7704
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
7705
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
7706
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
7707
0
    std::string recyc_rs_key0;
7708
0
    std::string recyc_rs_key1;
7709
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
7710
0
                recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
7711
0
       int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7712
7713
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
7714
0
        RecycleRowsetPB rowset;
7715
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7716
0
            return 0;
7717
0
        }
7718
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
7719
0
        int64_t current_time = ::time(nullptr);
7720
0
        if (current_time <
7721
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
7722
0
            return 0;
7723
0
        }
7724
7725
0
        if (!rowset.has_type()) {
7726
0
            if (!rowset.has_resource_id()) [[unlikely]] {
7727
0
                return 0;
7728
0
            }
7729
0
            if (rowset.resource_id().empty()) [[unlikely]] {
7730
0
                return 0;
7731
0
            }
7732
0
            metrics_context.total_need_recycle_num++;
7733
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7734
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
7735
0
            segment_metrics_context_.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7736
0
            return 0;
7737
0
        }
7738
7739
0
        if(!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled()) {
7740
0
            return 0;
7741
0
        }
7742
7743
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
7744
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
7745
0
                return 0;
7746
0
            }
7747
0
        }
7748
0
        metrics_context.total_need_recycle_num++;
7749
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
7750
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
7751
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
7752
0
        return 0;
7753
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_
7754
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
7755
0
    metrics_context.report(true);
7756
0
    segment_metrics_context_.report(true);
7757
0
    return ret;
7758
0
}
7759
7760
// Scan and statistics tmp_rowsets that need to be recycled
7761
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
7762
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
7763
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
7764
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
7765
0
    std::string tmp_rs_key0;
7766
0
    std::string tmp_rs_key1;
7767
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
7768
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
7769
7770
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7771
7772
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
7773
0
        doris::RowsetMetaCloudPB rowset;
7774
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7775
0
            return 0;
7776
0
        }
7777
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
7778
0
        int64_t current_time = ::time(nullptr);
7779
0
        if (current_time < expiration) {
7780
0
            return 0;
7781
0
        }
7782
7783
0
        DCHECK_GT(rowset.txn_id(), 0)
7784
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
7785
7786
0
        if(!rowset.has_is_recycled() || !rowset.is_recycled()) {
7787
0
            return 0;
7788
0
        }
7789
7790
0
        if (!rowset.has_resource_id()) {
7791
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
7792
0
                return 0;
7793
0
            }
7794
0
            return 0;
7795
0
        }
7796
7797
0
        metrics_context.total_need_recycle_num++;
7798
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
7799
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
7800
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
7801
0
        return 0;
7802
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_
7803
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
7804
0
    metrics_context.report(true);
7805
0
    segment_metrics_context_.report(true);
7806
0
    return ret;
7807
0
}
7808
7809
// Scan and statistics abort_timeout_txn that need to be recycled
7810
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
7811
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
7812
7813
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
7814
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7815
0
    std::string begin_txn_running_key;
7816
0
    std::string end_txn_running_key;
7817
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
7818
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
7819
7820
0
    int64_t current_time =
7821
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7822
7823
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
7824
0
                                               std::string_view k, std::string_view v) -> int {
7825
0
        std::unique_ptr<Transaction> txn;
7826
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7827
0
        if (err != TxnErrorCode::TXN_OK) {
7828
0
            return 0;
7829
0
        }
7830
0
        std::string_view k1 = k;
7831
0
        k1.remove_prefix(1);
7832
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7833
0
        if (decode_key(&k1, &out) != 0) {
7834
0
            return 0;
7835
0
        }
7836
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7837
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7838
        // Update txn_info
7839
0
        std::string txn_inf_key, txn_inf_val;
7840
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
7841
0
        err = txn->get(txn_inf_key, &txn_inf_val);
7842
0
        if (err != TxnErrorCode::TXN_OK) {
7843
0
            return 0;
7844
0
        }
7845
0
        TxnInfoPB txn_info;
7846
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
7847
0
            return 0;
7848
0
        }
7849
7850
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
7851
0
            TxnRunningPB txn_running_pb;
7852
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7853
0
                return 0;
7854
0
            }
7855
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7856
0
                return 0;
7857
0
            }
7858
0
            metrics_context.total_need_recycle_num++;
7859
0
        }
7860
0
        return 0;
7861
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_
7862
7863
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key, std::move(handle_abort_timeout_txn_kv));
7864
0
    metrics_context.report(true);
7865
0
    return ret;
7866
0
}
7867
7868
// Scan and statistics expired_txn_label that need to be recycled
7869
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
7870
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
7871
7872
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7873
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7874
0
    std::string begin_recycle_txn_key;
7875
0
    std::string end_recycle_txn_key;
7876
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7877
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7878
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7879
0
    int64_t current_time_ms =
7880
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7881
7882
    // for calculate the total num or bytes of recyled objects
7883
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
7884
0
        RecycleTxnPB recycle_txn_pb;
7885
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7886
0
            return 0;
7887
0
        }
7888
0
        if ((config::force_immediate_recycle) ||
7889
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7890
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7891
0
             current_time_ms)) {
7892
0
            metrics_context.total_need_recycle_num++;
7893
0
        }
7894
0
        return 0;
7895
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_
7896
7897
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key, std::move(handle_expired_txn_label_kv));
7898
0
    metrics_context.report(true);
7899
0
    return ret;
7900
0
}
7901
7902
// Scan and statistics copy_jobs that need to be recycled
7903
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
7904
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
7905
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7906
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7907
0
    std::string key0;
7908
0
    std::string key1;
7909
0
    copy_job_key(key_info0, &key0);
7910
0
    copy_job_key(key_info1, &key1);
7911
7912
    // for calculate the total num or bytes of recyled objects
7913
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
7914
0
        CopyJobPB copy_job;
7915
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7916
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7917
0
            return 0;
7918
0
        }
7919
7920
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7921
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
7922
0
                int64_t current_time =
7923
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7924
0
                if (copy_job.finish_time_ms() > 0) {
7925
0
                    if (!config::force_immediate_recycle &&
7926
0
                        current_time < copy_job.finish_time_ms() +
7927
0
                                               config::copy_job_max_retention_second * 1000) {
7928
0
                        return 0;
7929
0
                    }
7930
0
                } else {
7931
0
                    if (!config::force_immediate_recycle &&
7932
0
                        current_time < copy_job.start_time_ms() +
7933
0
                                               config::copy_job_max_retention_second * 1000) {
7934
0
                        return 0;
7935
0
                    }
7936
0
                }
7937
0
            }
7938
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7939
0
            int64_t current_time =
7940
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7941
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7942
0
                return 0;
7943
0
            }
7944
0
        }
7945
0
        metrics_context.total_need_recycle_num++;
7946
0
        return 0;
7947
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_
7948
7949
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7950
0
    metrics_context.report(true);
7951
0
    return ret;
7952
0
}
7953
7954
// Scan and statistics stage that need to be recycled
7955
0
int InstanceRecycler::scan_and_statistics_stage() {
7956
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
7957
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7958
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7959
0
    std::string key0 = recycle_stage_key(key_info0);
7960
0
    std::string key1 = recycle_stage_key(key_info1);
7961
7962
    // for calculate the total num or bytes of recyled objects
7963
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
7964
0
                                                        std::string_view v) -> int {
7965
0
        RecycleStagePB recycle_stage;
7966
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7967
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7968
0
            return 0;
7969
0
        }
7970
7971
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
7972
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7973
0
            LOG(WARNING) << "invalid idx: " << idx;
7974
0
            return 0;
7975
0
        }
7976
7977
0
        std::shared_ptr<StorageVaultAccessor> accessor;
7978
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7979
0
                [&] {
7980
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7981
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7982
0
                    if (!s3_conf) {
7983
0
                        return 0;
7984
0
                    }
7985
7986
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7987
0
                    std::shared_ptr<S3Accessor> s3_accessor;
7988
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7989
0
                    if (ret != 0) {
7990
0
                        return 0;
7991
0
                    }
7992
7993
0
                    accessor = std::move(s3_accessor);
7994
0
                    return 0;
7995
0
                }(),
7996
0
                "recycle_stage:get_accessor", &accessor);
7997
7998
0
        if (ret != 0) {
7999
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
8000
0
            return 0;
8001
0
        }
8002
8003
0
        metrics_context.total_need_recycle_num++;
8004
0
        return 0;
8005
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_
8006
8007
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
8008
0
    metrics_context.report(true);
8009
0
    return ret;
8010
0
}
8011
8012
// Scan and statistics expired_stage_objects that need to be recycled
8013
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
8014
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
8015
8016
    // for calculate the total num or bytes of recyled objects
8017
0
    auto scan_and_statistics = [&metrics_context, this]() {
8018
0
        for (const auto& stage : instance_info_.stages()) {
8019
0
            if (stopped()) {
8020
0
                break;
8021
0
            }
8022
0
            if (stage.type() == StagePB::EXTERNAL) {
8023
0
                continue;
8024
0
            }
8025
0
            int idx = stoi(stage.obj_info().id());
8026
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
8027
0
                continue;
8028
0
            }
8029
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
8030
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8031
0
            if (!s3_conf) {
8032
0
                continue;
8033
0
            }
8034
0
            s3_conf->prefix = stage.obj_info().prefix();
8035
0
            std::shared_ptr<S3Accessor> accessor;
8036
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
8037
0
            if (ret1 != 0) {
8038
0
                continue;
8039
0
            }
8040
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
8041
0
                continue;
8042
0
            }
8043
0
            metrics_context.total_need_recycle_num++;
8044
0
        }
8045
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
8046
8047
0
    scan_and_statistics();
8048
0
    metrics_context.report(true);
8049
0
    return 0;
8050
0
}
8051
8052
// Scan and statistics versions that need to be recycled
8053
0
int InstanceRecycler::scan_and_statistics_versions() {
8054
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
8055
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
8056
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
8057
8058
0
    int64_t last_scanned_table_id = 0;
8059
0
    bool is_recycled = false; // Is last scanned kv recycled
8060
    // for calculate the total num or bytes of recyled objects
8061
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
8062
0
                                       std::string_view k, std::string_view) {
8063
0
        auto k1 = k;
8064
0
        k1.remove_prefix(1);
8065
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
8066
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8067
0
        decode_key(&k1, &out);
8068
0
        DCHECK_EQ(out.size(), 6) << k;
8069
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
8070
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
8071
0
            metrics_context.total_need_recycle_num +=
8072
0
                    is_recycled; // Version kv of this table has been recycled
8073
0
            return 0;
8074
0
        }
8075
0
        last_scanned_table_id = table_id;
8076
0
        is_recycled = false;
8077
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
8078
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
8079
0
        std::unique_ptr<Transaction> txn;
8080
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8081
0
        if (err != TxnErrorCode::TXN_OK) {
8082
0
            return 0;
8083
0
        }
8084
0
        std::unique_ptr<RangeGetIterator> iter;
8085
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
8086
0
        if (err != TxnErrorCode::TXN_OK) {
8087
0
            return 0;
8088
0
        }
8089
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
8090
0
            return 0;
8091
0
        }
8092
0
        metrics_context.total_need_recycle_num++;
8093
0
        is_recycled = true;
8094
0
        return 0;
8095
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_
8096
8097
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
8098
0
    metrics_context.report(true);
8099
0
    return ret;
8100
0
}
8101
8102
// Scan and statistics restore jobs that need to be recycled
8103
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
8104
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
8105
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
8106
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
8107
0
    std::string restore_job_key0;
8108
0
    std::string restore_job_key1;
8109
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
8110
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
8111
8112
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8113
8114
    // for calculate the total num or bytes of recyled objects
8115
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
8116
0
        RestoreJobCloudPB restore_job_pb;
8117
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
8118
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
8119
0
            return 0;
8120
0
        }
8121
0
        int64_t expiration =
8122
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
8123
0
        int64_t current_time = ::time(nullptr);
8124
0
        if (current_time < expiration) { // not expired
8125
0
            return 0;
8126
0
        }
8127
0
        metrics_context.total_need_recycle_num++;
8128
0
        if(restore_job_pb.need_recycle_data()) {
8129
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
8130
0
        }
8131
0
        return 0;
8132
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_
8133
8134
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
8135
0
    metrics_context.report(true);
8136
0
    return ret;
8137
0
}
8138
8139
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
8140
3
    if (!should_recycle_versioned_keys()) {
8141
0
        return;
8142
0
    }
8143
8144
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
8145
8146
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
8147
3
    if (recycle_checker.init() != 0) {
8148
0
        return;
8149
0
    }
8150
8151
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
8152
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
8153
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
8154
8155
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
8156
8
    for (; iter->valid(); iter->next()) {
8157
5
        OperationLogPB operation_log;
8158
5
        if (!iter->parse_value(&operation_log)) {
8159
0
            continue;
8160
0
        }
8161
8162
5
        std::string_view key = iter->key();
8163
5
        Versionstamp log_versionstamp;
8164
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
8165
0
            continue;
8166
0
        }
8167
8168
5
        OperationLogReferenceInfo ref_info;
8169
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
8170
5
                                         &ref_info)) {
8171
4
            metrics_context.total_need_recycle_num++;
8172
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
8173
4
        }
8174
5
    }
8175
8176
3
    metrics_context.report(true);
8177
3
}
8178
8179
int InstanceRecycler::classify_rowset_task_by_ref_count(
8180
60
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
8181
60
    constexpr int MAX_RETRY = 10;
8182
60
    const auto& rowset_meta = task.rowset_meta;
8183
60
    int64_t tablet_id = rowset_meta.tablet_id();
8184
60
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
8185
60
    std::string_view reference_instance_id = instance_id_;
8186
60
    if (rowset_meta.has_reference_instance_id()) {
8187
5
        reference_instance_id = rowset_meta.reference_instance_id();
8188
5
    }
8189
8190
61
    for (int i = 0; i < MAX_RETRY; ++i) {
8191
61
        std::unique_ptr<Transaction> txn;
8192
61
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8193
61
        if (err != TxnErrorCode::TXN_OK) {
8194
0
            LOG_WARNING("failed to create txn when classifying rowset task")
8195
0
                    .tag("instance_id", instance_id_)
8196
0
                    .tag("tablet_id", tablet_id)
8197
0
                    .tag("rowset_id", rowset_id)
8198
0
                    .tag("err", err);
8199
0
            return -1;
8200
0
        }
8201
8202
61
        std::string rowset_ref_count_key =
8203
61
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
8204
61
        task.rowset_ref_count_key = rowset_ref_count_key;
8205
8206
61
        int64_t ref_count = 0;
8207
61
        {
8208
61
            std::string value;
8209
61
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
8210
61
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
8211
0
                ref_count = 1;
8212
61
            } else if (err != TxnErrorCode::TXN_OK) {
8213
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
8214
0
                        .tag("instance_id", instance_id_)
8215
0
                        .tag("tablet_id", tablet_id)
8216
0
                        .tag("rowset_id", rowset_id)
8217
0
                        .tag("err", err);
8218
0
                return -1;
8219
61
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
8220
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
8221
0
                        .tag("instance_id", instance_id_)
8222
0
                        .tag("tablet_id", tablet_id)
8223
0
                        .tag("rowset_id", rowset_id)
8224
0
                        .tag("value", hex(value));
8225
0
                return -1;
8226
0
            }
8227
61
        }
8228
8229
61
        if (ref_count > 1) {
8230
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
8231
12
            txn->atomic_add(rowset_ref_count_key, -1);
8232
12
            LOG_INFO("decrease rowset data ref count in classification phase")
8233
12
                    .tag("instance_id", instance_id_)
8234
12
                    .tag("tablet_id", tablet_id)
8235
12
                    .tag("rowset_id", rowset_id)
8236
12
                    .tag("ref_count", ref_count - 1)
8237
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
8238
8239
12
            if (!task.recycle_rowset_key.empty()) {
8240
0
                txn->remove(task.recycle_rowset_key);
8241
0
                LOG_INFO("remove recycle rowset key in classification phase")
8242
0
                        .tag("key", hex(task.recycle_rowset_key));
8243
0
            }
8244
12
            if (!task.non_versioned_rowset_key.empty()) {
8245
12
                txn->remove(task.non_versioned_rowset_key);
8246
12
                LOG_INFO("remove non versioned rowset key in classification phase")
8247
12
                        .tag("key", hex(task.non_versioned_rowset_key));
8248
12
            }
8249
8250
12
            err = txn->commit();
8251
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
8252
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
8253
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
8254
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
8255
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
8256
1
                continue;
8257
11
            } else if (err != TxnErrorCode::TXN_OK) {
8258
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
8259
0
                        .tag("instance_id", instance_id_)
8260
0
                        .tag("tablet_id", tablet_id)
8261
0
                        .tag("rowset_id", rowset_id)
8262
0
                        .tag("err", err);
8263
0
                return -1;
8264
0
            }
8265
11
            return 1; // handled, not added to batch delete
8266
49
        } else {
8267
            // ref_count == 1: Add to batch delete plan without modifying any KV.
8268
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
8269
49
            LOG_INFO("add rowset to batch delete plan")
8270
49
                    .tag("instance_id", instance_id_)
8271
49
                    .tag("tablet_id", tablet_id)
8272
49
                    .tag("rowset_id", rowset_id)
8273
49
                    .tag("resource_id", rowset_meta.resource_id())
8274
49
                    .tag("ref_count", ref_count);
8275
8276
49
            batch_delete_tasks.push_back(std::move(task));
8277
49
            return 0; // added to batch delete
8278
49
        }
8279
61
    }
8280
8281
0
    LOG_WARNING("failed to classify rowset task after retry")
8282
0
            .tag("instance_id", instance_id_)
8283
0
            .tag("tablet_id", tablet_id)
8284
0
            .tag("rowset_id", rowset_id)
8285
0
            .tag("retry", MAX_RETRY);
8286
0
    return -1;
8287
60
}
8288
8289
10
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
8290
10
    int ret = 0;
8291
49
    for (const auto& task : tasks) {
8292
49
        int64_t tablet_id = task.rowset_meta.tablet_id();
8293
49
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
8294
8295
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
8296
        // so we don't need to call it again here.
8297
8298
        // Remove all metadata keys in one transaction
8299
49
        std::unique_ptr<Transaction> txn;
8300
49
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8301
49
        if (err != TxnErrorCode::TXN_OK) {
8302
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
8303
0
                    .tag("instance_id", instance_id_)
8304
0
                    .tag("tablet_id", tablet_id)
8305
0
                    .tag("rowset_id", rowset_id)
8306
0
                    .tag("err", err);
8307
0
            ret = -1;
8308
0
            continue;
8309
0
        }
8310
8311
49
        std::string_view reference_instance_id = instance_id_;
8312
49
        if (task.rowset_meta.has_reference_instance_id()) {
8313
5
            reference_instance_id = task.rowset_meta.reference_instance_id();
8314
5
        }
8315
8316
49
        txn->remove(task.rowset_ref_count_key);
8317
49
        LOG_INFO("delete rowset data ref count key in cleanup phase")
8318
49
                .tag("instance_id", instance_id_)
8319
49
                .tag("tablet_id", tablet_id)
8320
49
                .tag("rowset_id", rowset_id)
8321
49
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
8322
8323
49
        std::string dbm_start_key =
8324
49
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
8325
49
        std::string dbm_end_key = meta_delete_bitmap_key(
8326
49
                {reference_instance_id, tablet_id, rowset_id,
8327
49
                 std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
8328
49
        txn->remove(dbm_start_key, dbm_end_key);
8329
49
        LOG_INFO("remove delete bitmap kv in cleanup phase")
8330
49
                .tag("instance_id", instance_id_)
8331
49
                .tag("tablet_id", tablet_id)
8332
49
                .tag("rowset_id", rowset_id)
8333
49
                .tag("begin", hex(dbm_start_key))
8334
49
                .tag("end", hex(dbm_end_key));
8335
8336
49
        std::string versioned_dbm_start_key =
8337
49
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
8338
49
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
8339
49
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
8340
49
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
8341
49
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
8342
49
                .tag("instance_id", instance_id_)
8343
49
                .tag("tablet_id", tablet_id)
8344
49
                .tag("rowset_id", rowset_id)
8345
49
                .tag("begin", hex(versioned_dbm_start_key))
8346
49
                .tag("end", hex(versioned_dbm_end_key));
8347
8348
        // Remove versioned meta rowset key
8349
49
        if (!task.versioned_rowset_key.empty()) {
8350
49
            versioned::document_remove<RowsetMetaCloudPB>(
8351
49
                txn.get(), task.versioned_rowset_key, task.versionstamp);
8352
49
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
8353
49
                    .tag("instance_id", instance_id_)
8354
49
                    .tag("tablet_id", tablet_id)
8355
49
                    .tag("rowset_id", rowset_id)
8356
49
                    .tag("key_prefix", hex(task.versioned_rowset_key));
8357
49
        }
8358
8359
49
        if (!task.non_versioned_rowset_key.empty()) {
8360
49
            txn->remove(task.non_versioned_rowset_key);
8361
49
            LOG_INFO("remove non versioned rowset key in cleanup phase")
8362
49
                    .tag("instance_id", instance_id_)
8363
49
                    .tag("tablet_id", tablet_id)
8364
49
                    .tag("rowset_id", rowset_id)
8365
49
                    .tag("key", hex(task.non_versioned_rowset_key));
8366
49
        }
8367
8368
        // Remove recycle_rowset_key last to ensure retry safety:
8369
        // if cleanup fails, this key remains and triggers next round retry.
8370
49
        if (!task.recycle_rowset_key.empty()) {
8371
0
            txn->remove(task.recycle_rowset_key);
8372
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
8373
0
                    .tag("instance_id", instance_id_)
8374
0
                    .tag("tablet_id", tablet_id)
8375
0
                    .tag("rowset_id", rowset_id)
8376
0
                    .tag("key", hex(task.recycle_rowset_key));
8377
0
        }
8378
8379
49
        err = txn->commit();
8380
49
        if (err != TxnErrorCode::TXN_OK) {
8381
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
8382
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
8383
0
                    .tag("instance_id", instance_id_)
8384
0
                    .tag("tablet_id", tablet_id)
8385
0
                    .tag("rowset_id", rowset_id)
8386
0
                    .tag("err", err);
8387
0
            ret = -1;
8388
0
            continue;
8389
0
        }
8390
8391
49
        LOG_INFO("cleanup rowset metadata success")
8392
49
                .tag("instance_id", instance_id_)
8393
49
                .tag("tablet_id", tablet_id)
8394
49
                .tag("rowset_id", rowset_id);
8395
49
    }
8396
10
    return ret;
8397
10
}
8398
8399
} // namespace doris::cloud